kylin-nm/0000775000175000017500000000000015167651420011245 5ustar fengfengkylin-nm/kylin-nm.pro0000664000175000017500000000032715167651420013527 0ustar fengfengTEMPLATE = subdirs CONFIG += \ ordered \ qt \ SUBDIRS = \ plugins/plugin.pro \ src-vpn/src-vpn.pro \ src \ sys-dbus-register \ qml-network \ QT += widgets kylin-nm/src/0000775000175000017500000000000015167651420012034 5ustar fengfengkylin-nm/src/translations/0000775000175000017500000000000015167651420014555 5ustar fengfengkylin-nm/src/translations/kylin-nm_tr.ts0000664000175000017500000027077415167646234017420 0ustar fengfeng BackThread Confirm your WLAN password WLAN parolasını doğrula ConfForm edit network Ağı düzenle LAN name: LAN adı: Method: Yöntem: Address: Adres: Netmask: Netmask: DNS 1: DNS 1: DNS 2: DNS 2: Edit Conn Bağ. Düzenle Auto(DHCP) Oto(DHCP) Manual Elle Cancel İptal Save Kaydet Ok Tamam Can not create new wired network for without wired card Kablolu kart olmadan yeni kablolu ağ oluşturulamıyor New network already created Yeni ağ zaten oluşturuldu New network settings already finished Yeni ağ ayarları zaten tamamlandı kylin network applet desktop message Kylin ağ uygulaması masaüstü mesajı Edit Network Ağı Düzenle Add Wired Network Kablolu Ağ Ekle create wired network successfully Başarıyla kablolu ağ oluşturuldu change configuration of wired network successfully Kablolu ağın yapılandırmasını başarıyla değiştirildi New settings already effective Yeni ayarlar zaten etkili ConfigPage Network profile type Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. Config firewall and security settings ConnectivityPage Network connectivity detection If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. Public network (default) Local area network (intranet) Confirm The network is connected and can access the Internet normally. The network is connected and access to the Internet is restricted. Please enter the local area network (intranet) detection address Format error CreatNetPage Connection Name IPv4Config Address Netmask Default Gateway Invalid address Invalid subnet mask Required Address conflict Auto(DHCP) Oto(DHCP) Manual Elle DetailPage Auto Connection SSID: Copied successfully! Copy all Please input SSID: Protocol: Security Type: Hz: Chan: BandWidth: IPv4: IPv6 adresi: {4:?} IPv4 DNS: IPv6: IPv6 adresi: {6:?} Mac: DlgHideWifi Add Hidden WLAN Gizli WLAN Ekle Connection Bağlantı WLAN name WLAN adı WLAN security WLAN güvenlik Cancel İptal Connect Bağlantı C_reate… Oluştur... None Yok Conn WLAN Success WLAN Bağlantısı Başarılı Confirm your WLAN password or usable of wireless card Kablosuz şifrenizi veya kablosuz kart kullanılabilirliğini onaylayın WPA & WPA2 Personal WPA & WPA2 Kişisel WEP 40/128-bit Key (Hex or ASCII) WEP 40/128-bit Key (Hex veya ASCII) WEP 128-bit Passphrase WEP 128-bit Passphrase Dynamic WEP (802.1X) Dinamik WEP (802.1x) WPA & WPA2 Enterprise WPA & WPA2 Enterprise Connect to Hidden WLAN Network Gizli WLAN Ağına Bağlan DlgHideWifiEapFast Connect to Hidden WLAN Network Gizli WLAN Ağına Bağlan Add hidden WLAN Gizli WLAN Ekle Connection Bağlantı: Network name Ağ adı WLAN security WLAN güvenliği Authentication Kimlik Doğrulama Anonymous identity Anonim kimlik Allow automatic PAC pro_visioning Otomatik PAC pro_visioning'e izin ver PAC file PAC dosyası Inner authentication İç kimlik doğrulama: Username Kullanıcı adı Password Parola Cancel İptal Connect Bağlan C_reate… Oluştur... None Yok WPA & WPA2 Personal WPA & WPA2 Kişisel WEP 40/128-bit Key (Hex or ASCII) WEP 40/128-bit Key (Hex veya ASCII) WEP 128-bit Passphrase WEP 128-bit Passphrase Dynamic WEP (802.1X) Dinamik WEP (802.1x) WPA & WPA2 Enterprise WPA & WPA2 Enterprise Tunneled TLS Tünelli TLS Protected EAP (PEAP) Korumalı EAP (PEAP) Anonymous Anonim Authenticated Doğrulanmış Both Her ikisi de DlgHideWifiEapLeap Connect to Hidden WLAN Network Gizli WLAN ağına bağlan Add hidden WLAN Gizli WLAN ekle Connection Bağlantı: Network name Ağ adı: WLAN security WLAN güvenliği: Authentication Kimlik Doğrulama: Username Kullanıcı adı: Password Parola: Cancel 取消 Connect Bağlan C_reate… Oluştur... None Yok WPA & WPA2 Personal WPA & WPA2 Kişisel WEP 40/128-bit Key (Hex or ASCII) WEP 40/128-bit Key (Hex veya ASCII) WEP 128-bit Passphrase WEP 128-bit Passphrase Dynamic WEP (802.1X) Dinamik WEP (802.1x) WPA & WPA2 Enterprise WPA & WPA2 Enterprise Tunneled TLS Tünelli TLS Protected EAP (PEAP) Korumalı EAP (PEAP) DlgHideWifiEapPeap Connect to Hidden WLAN Network Gizli WLAN Ağına Bağlan Add hidden WLAN Gizli WLAN ekle Connection Bağlantı: Network name Ağ adı: WLAN security WLAN güvenliği: Authentication Kimlik Doğrulama: Anonymous identity Anonim kimlik: Domain Domain: CA certificate CA sertifikası: CA certificate password CA sertifika şifresi: No CA certificate is required CA sertifikası gerekmez PEAP version PEAP sürümü: Inner authentication İç kimlik doğrulama: Username Kullanıcı adı: Password Parola: Cancel İptal Connect Bağlan None Yok WPA & WPA2 Personal WPA & WPA2 Kişisel WEP 40/128-bit Key (Hex or ASCII) WEP 40/128-bit Key (Hex veya ASCII) WEP 128-bit Passphrase WEP 128-bit Passphrase Dynamic WEP (802.1X) Dinamik WEP (802.1x) WPA & WPA2 Enterprise WPA & WPA2 Enterprise Tunneled TLS Tünelli TLS Protected EAP (PEAP) Korumalı EAP (PEAP) Choose from file Dosyadan seçin... Automatic Otomatik Version 0 Sürüm 0 Version 1 Sürüm 1 DlgHideWifiEapPwd Connect to Hidden WLAN Network Gizli WLAN Ağına Bağlan Add hidden WLAN Gizli WLAN ekle Connection Bağlantı: Network name Ağ adı: WLAN security WLAN güvenliği: Authentication Kimlik Doğrulama: Username Kullanıcı adı: Password Parola: Cancel İptal Connect Bağlan C_reate… Oluştur... None Yok WPA & WPA2 Personal WPA & WPA2 Kişisel WEP 40/128-bit Key (Hex or ASCII) WEP 40/128-bit Key (Hex veya ASCII) WEP 128-bit Passphrase WEP 128-bit Passphrase Dynamic WEP (802.1X) Dinamik WEP (802.1x) WPA & WPA2 Enterprise WPA & WPA2 Enterprise Tunneled TLS Tünelli TLS Protected EAP (PEAP) Korumalı EAP (PEAP) DlgHideWifiEapTTLS Connect to Hidden WLAN Network Gizli WLAN Ağına Bağlan Add hidden WLAN Gizli WLAN ekle Connection Bağlantı: Network name Ağ adı: WLAN security WLAN Güvenliği: Authentication Kimlik Doğrulama: Anonymous identity Anonim kimlik: Domain Domain: CA certificate CA Sertifikası: CA certificate password CA sertifika şifresi: No CA certificate is required CA sertifikası gerekmez Inner authentication İç kimlik doğrulama: Username Kullanıcı adı: Password Parola: Cancel İptal Connect Bağlan C_reate… Oluştur... None Yok WPA & WPA2 Personal WPA & WPA2 Kişisel WEP 40/128-bit Key (Hex or ASCII) WEP 40/128-bit Key (Hex veya ASCII) WEP 128-bit Passphrase WEP 128-bit Passphrase Dynamic WEP (802.1X) Dinamik WEP (802.1x) WPA & WPA2 Enterprise WPA & WPA2 Enterprise Tunneled TLS Tünelli TLS Protected EAP (PEAP) Korumalı EAP (PEAP) Choose from file Dosyadan seçiniz... DlgHideWifiEapTls Connect to Hidden WLAN Network Gizli WLAN Ağına Bağlan Add hidden WLAN Gizli WLAN ekle Connection Bağlantı: Network name Ağ adı: WLAN security WLAN güvenliği: Authentication Kimlik Doğrulama: Identity Kimlik: Domain Domain: CA certificate CA sertifikası: CA certificate password CA sertifika şifresi: No CA certificate is required CA sertifikası gerekmez User certificate Kullanıcı sertifikası: User certificate password Kullanıcı sertifikası şifresi: User private key Kullanıcı özel anahtarı: User key password Kullanıcı anahtarı şifresi: Cancel İptal Connect Bağlan C_reate… Oluştur... None Yok WPA & WPA2 Personal WPA & WPA2 Kişisel WEP 40/128-bit Key (Hex or ASCII) WEP 40/128-bit Key (Hex veya ASCII) WEP 128-bit Passphrase WEP 128-bit Passphrase Dynamic WEP (802.1X) Dinamik WEP (802.1x) WPA & WPA2 Enterprise WPA & WPA2 Enterprise Tunneled TLS Tünelli TLS Protected EAP (PEAP) Korumalı EAP (PEAP) Choose from file Dosyadan seç... DlgHideWifiLeap Connect to Hidden WLAN Network Gizli WLAN Ağına Bağlan Add hidden WLAN Gizli WLAN Ekle Connection Bağlantı Network name Ağ adı WLAN security WLAN Güvenlik Username Kullanıcı adı Password Parola Cancel İptal Connect Bağlan C_reate… Oluştur... None Yok WPA & WPA2 Personal WPA & WPA2 Kişisel WEP 40/128-bit Key (Hex or ASCII) WEP 40/128-bit Key (Hex veya ASCII) WEP 128-bit Passphrase WEP 128-bit Passphrase Dynamic WEP (802.1X) Dinamik WEP (802.1X) WPA & WPA2 Enterprise WPA & WPA2 Enterprise DlgHideWifiWep Connect to Hidden WLAN Network Gizli WLAN Ağına Bağlan Add hidden WLAN Gizli WLAN Ekle Connection Bağlantı: Network name Ağ adı: WLAN security WLAN Güvenliği: Key Anahtar WEP index WEP index Authentication Kimlik Doğrulama: Cancel İptal Connect Bağlan C_reate… Oluştur... None Yok WPA & WPA2 Personal WPA & WPA2 Kişisel WEP 40/128-bit Key (Hex or ASCII) WEP 40/128-bit Key (Hex veya ASCII) WEP 128-bit Passphrase WEP 128-bit Passphrase Dynamic WEP (802.1X) Dinamik WEP (802.1x) WPA & WPA2 Enterprise WPA & WPA2 Enterprise 1(default) 1(default) Open System Sistemi aç Shared Key Paylaşılan Anahtar DlgHideWifiWpa Connect to Hidden WLAN Network Gizli WLAN Ağına Bağlan Add Hidden WLAN Gizli WLAN Ekle Connection Bağlantı: WLAN name WLAN adı: WLAN security WLAN güvenlik: Password Parola: Cancel İptal Connect Bağlan C_reate… Oluştur... None Yok Conn WLAN Success WLAN Bağlantısı Başarılı Confirm your WLAN password or usable of wireless card Kablosuz şifrenizi veya kablosuz kart kullanılabilirliğini onaylayın WPA & WPA2 Personal WPA & WPA2 Kişisel WPA & WPA2 Enterprise WPA & WPA2 Enterprise WEP 40/128-bit Key (Hex or ASCII) WEP 40/128-bit Key (Hex veya ASCII) Dynamic WEP (802.1X) Dinamik WEP (802.1x) DlgHotspotCreate Create Hotspot Etkin Nokta Oluştur Network name Ağ adı: WLAN security WLAN Güvenlik: Password Parola: Cancel İptal Ok Tamam None Yok WPA & WPA2 Personal WPA & WPA2 Kişisel DnsSettingWidget DNS Server Advanced Settings Tactic Timeout Retry Count order rotate concurrency s times Close Cancel Confirm EnterpriseWlanDialog Wi-Fi network requires authentication Access to Wi-Fi network " " requires a password or encryption key. Cancel Connect FirewallDialog Allow other devices on this network to discover this computer? It is not recommended to enable this feature on public networks Not allowed (recommended) Allowed Ipv4Page Address Netmask Default Gateway IPv4Config Auto(DHCP) Oto(DHCP) Manual Elle Invalid address Invalid subnet mask Required Address conflict Ipv6Page Address Subnet prefix Length Default Gateway IPv6Config Auto(DHCP) Oto(DHCP) Manual Elle Required Invalid address Invalid gateway Address conflict JoinHiddenWiFiPage Please enter the network information Network name(SSID) Show Network List Cancel Join Required Find and Join WLAN KylinDBus kylin network applet desktop message Kylin ağ uygulaması masaüstü mesajı LanListItem Not connected Bağlanamadı Wired Device not carried Disconnect Bağlantıyı Kes Connect Property Delete LanPage LAN conflict, unable to connect to the network normally! Activated LAN Inactivated LAN Wired Device not carried Connected: (Limited) Not Connected ListItem Kylin NM kylin network applet desktop message Kylin ağ uygulaması masaüstü mesajı MainWindow kylin-nm Network Advanced Gelişmiş Ethernet Kablolu Ağ Connect Hide Network Gizli Ağı Bağlan LAN WLAN WLAN Settings Network Connectivity Detection Network tool Network Card Not connected to the network Enabled Aktif Disabled Pasif HotSpot HotSpot Show MainWindow Ana Pencereyi Göster Not connected Bağlanamadı Disconnected Bağlantı Kesildi No Other Wired Network Scheme Başka Kablolu Ağ Düzeni Yok No Other Wireless Network Scheme Başka Kablosuz Ağ Düzeni Yok Wired net is disconnected Kablolu ağ bağlantısı kesildi WLAN is disconnected Kablosuz bağlantı kesildi Confirm your WLAN password or usable of wireless card Kablosuz şifrenizi veya kablosuz kart kullanılabilirliğini onaylayın Confirm your WLAN password WLAN parolasını doğrula Ethernet Networks Ethernet Ağları New LAN Yeni LAN Hide WLAN Gizli WLAN No usable network in the list Listede kullanılabilir ağ yok WLAN Networks WLAN Ağları None Yok keep wired network switch is on before turning on wireless switch Kablosuz anahtarı açmadan önce kablolu ağ anahtarını açık tut please insert the wireless network adapter Lütfen kablosuz ağ adaptörünü takın Abnormal connection exist, program will delete it Anormal bağlantı var, program onu ​​silecek update WLAN list now, click again Kablosuz listesini şimdi güncelle, tekrar tıkla update WLAN list now Kablosuz listesini şimdi güncelle Conn Ethernet Success Ethernet Bağlantısı Başarılı Conn Ethernet Fail Ethernet Bağlantısı Hatası Conn WLAN Success WLAN Bağlantısı Başarılı MultipleDnsWidget DNS server(Drag to sort) Click "+" to configure DNS Settings NetDetail Kylin NM kylin network desktop message Detail Security Config Ayar Confirm Cancel Forget this network IPv4 IPv6 adresi: {4?} IPv6 IPv6 adresi: {6?} Add LAN Connect Connect Hidden WLAN Delete this network None Yok Auto Oto start check ipv4 address conflict start check ipv6 address conflict this wifi no support enterprise type this wifi no support None type this wifi no support WPA2 type this wifi no support WPA3 type NotifySend Form -- OldMainWindow Ethernet Networks Ethernet Ağları New LAN Yeni LAN WLAN Networks WLAN Ağları Hide WLAN Gizli WLAN No usable network in the list Listede kullanılabilir ağ yok Ethernet Kablolu Ağ HotSpot HotSpot Advanced Gelişmiş Show MainWindow Ana Pencereyi Göster Wired net is disconnected Kablolu ağ bağlantısı kesildi Not connected Bağlanamadı Disconnected Bağlantı Kesildi No Other Wired Network Scheme Başka Kablolu Ağ Düzeni Yok No Other Wireless Network Scheme Başka Kablosuz Ağ Düzeni Yok WLAN is disconnected Kablosuz bağlantı kesildi Conn Ethernet Success Ethernet Bağlantısı Başarılı Conn WLAN Success WLAN Bağlantısı Başarılı Confirm your WLAN password or usable of wireless card Kablosuz şifrenizi veya kablosuz kart kullanılabilirliğini onaylayın Confirm your WLAN password WLAN parolasını doğrula OneConnForm Form -- Input password Parola gir Config Ayar Connect Bağlan Disconnect Bağlantıyı Kes Input Password... Parola gir... Connect to Hidden WLAN Network Gizli WLAN Ağına Bağlan Public Halka açık Safe Güvenli Rate Oran None Yok WLAN Security: WLAN güvenliği: Sifnal: Sinyal gücü: MAC: Fiziksel adres: Conn WLAN Success WLAN Bağlantısı Başarılı Confirm your WLAN password or usable of wireless card Kablosuz şifrenizi veya kablosuz kart kullanılabilirliğini onaylayın Conn WLAN Failed WLAN Bağlantısı Başarısız OneLancForm Form -- Config Ayar Connect Bağlan Disconnect Bağlantıyı Kes Not connected Bağlanamadı Disconnected Bağlantı Kesildi Ethernet Kablolu Ağ No Configuration Yapılandırma Yok IPv4: IPv4 adresi: IPv6: IPv6 adresi: BandWidth: Bant genişliği: MAC: Fiziksel adres: Auto Oto SecurityPage Remember the Network Security Password EAP type Identity Kimlik: Domain Domain: CA certficate no need for CA certificate User certificate Kullanıcı sertifikası: User private key Kullanıcı özel anahtarı: User key password Kullanıcı anahtarı şifresi: Password options Required Ineer authentication Username Ask pwd each query None Yok WPA&WPA2 Personal WPA&WPA2 Enterprise WPA3 Personal Choose from file... Store passwords only for this user Store password only for this user Store passwords for all users Store password for all users Ask this password every time Ask password every time PAC provisioning Allow automatic PAC provisioning PAC file PAC dosyası Anonymous Anonim Authenticated Doğrulanmış Both Her ikisi de Choose a CA certificate CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a PAC file PAC Files (*.pac) TabPage Current Device Devices Closed! Settings Kylin NM kylin network applet desktop message Kylin ağ uygulaması masaüstü mesajı Utils kylin network applet desktop message Kylin ağ uygulaması masaüstü mesajı WiFiConfigDialog Ok Tamam WlanListItem Not connected Bağlanamadı Disconnect Bağlantıyı Kes Connect Property Forget Auto Connect WlanMoreItem Add Others... WlanPage WLAN WLAN Activated WLAN Other WLAN Connected: Not Connected No wireless network card detected WLAN Connected Successfully WLAN Disconnected Successfully WpaWifiDialog Identity Kimlik: Domain Domain: None Yok main kylinnm show kylin-nm wifi page show kylin-nm lan page kylin-nm/src/translations/kylin-nm_de.ts0000664000175000017500000017661115167646234017356 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type Typ des Netzwerkprofils Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. Öffentlich (empfohlen) Geräte im Netzwerk können diesen Computer nicht erkennen. Im Allgemeinen eignet es sich für Netzwerke an öffentlichen Orten wie Flughäfen oder Cafés usw. Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. Private Geräte im Netzwerk können diesen Computer erkennen. Allgemein anwendbar auf ein Netzwerk zu Hause oder am Arbeitsplatz, in dem Sie die Personen und Geräte im Netzwerk kennen und ihnen vertrauen. Config firewall and security settings Firewall und Sicherheitseinstellungen konfigurieren ConnectivityPage Network connectivity detection If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. Public network (default) Local area network (intranet) Confirm Bestätigen The network is connected and can access the Internet normally. The network is connected and access to the Internet is restricted. Please enter the local area network (intranet) detection address Format error CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name Name der Verbindung IPv4Config IPv4Config Address Adresse Netmask Netzmaske Default Gateway Standardgateway Address conflict Konflikte angehen Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Auto (DHCP) Manual Manuell Invalid address Ungültige Adresse Invalid subnet mask Ungültige Subnetzmaske Required Erforderlich DetailPage Auto Connection Automatische Verbindung SSID: SSID: Copied successfully! Erfolgreich kopiert! Copy all Alle kopieren Please input SSID: Bitte geben Sie die SSID ein: Protocol: Protokoll: Security Type: Sicherheitstyp: Hz: Hz: Chan: Chan: BandWidth: Bandbreite: IPv6: IPv6: IPv4: IPv4: IPv4 DNS: IPv4-DNS: Mac: Mac: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings Erweiterte Einstellungen für den DNS-Server Tactic Taktik Timeout Zeitüberschreitung Retry Count Anzahl der Wiederholungsversuche order Bestellung rotate drehen concurrency Gleichzeitigkeit s s times mal Close Schließen Cancel Abbrechen Confirm Bestätigen EnterpriseWlanDialog Connect Enterprise WLAN 连接企业网 Close 关闭 Wi-Fi network requires authentication Wi-Fi-Netzwerk erfordert Authentifizierung Access to Wi-Fi network " Zugriff auf das Wi-Fi-Netzwerk " " requires a password or encryption key. " erfordert ein Kennwort oder einen Verschlüsselungsschlüssel. Cancel Abbrechen Connect Verbinden FirewallDialog Allow your computer to be discovered by other computers and devices on this network? 是否允许你的电脑被此网络上的其他电脑和设备发现? It is recommended that you enable this feature on your home and work networks rather than public networks. 建议你在家庭和工作网络上而非公共网络上启用此功能。 Yse No Allow other devices on this network to discover this computer? Zulassen, dass andere Geräte in diesem Netzwerk diesen Computer erkennen? It is not recommended to enable this feature on public networks Es wird nicht empfohlen, diese Funktion in öffentlichen Netzwerken zu aktivieren Not allowed (recommended) Nicht erlaubt (empfohlen) Allowed Erlaubt Ipv4Page IPv4Config IPv4Config Address Adresse Netmask Netzmaske Default Gateway Standardgateway Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Auto (DHCP) Manual Manuell Invalid address Ungültige Adresse Invalid subnet mask Ungültige Subnetzmaske Required Erforderlich Address conflict Konflikte angehen Ipv6Page IPv6Config IPv6Config (IPv6-Konfiguration) Address Adresse Subnet prefix Length Länge des Subnetzpräfixes Default Gateway Standardgateway Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Auto (DHCP) Manual Manuell Required Erforderlich Invalid address Ungültige Adresse Invalid gateway Ungültiges Gateway Address conflict Konflikte angehen JoinHiddenWiFiPage Please enter the network information Bitte geben Sie die Netzwerkinformationen ein Network name(SSID) Netzwerkname (SSID) Remember the Network 记住该网络 Show Network List Netzwerkliste anzeigen Cancel Abbrechen Join Verbinden Required Erforderlich Find and Join WLAN WLAN finden und verbinden LanListItem Not connected Nicht verbunden Wired Device not carried Kabelgebundenes Gerät nicht mitgeführt Disconnect Trennen Connect Verbinden Property Eigentum Delete Löschen LanPage No ethernet device avaliable Kein Ethernet-Gerät verfügbar LAN LAN conflict, unable to connect to the network normally! Konflikt, es kann keine normale Verbindung zum Netzwerk hergestellt werden! Activated LAN Aktiviertes LAN Inactivated LAN Inaktiviertes LAN LAN Disconnected Successfully 有线网络已断开 Wired Device not carried Kabelgebundenes Gerät nicht mitgeführt LAN Connected Successfully 有线网络已连接 Connected: Verbunden: Not Connected Nicht verbunden (Limited) (Begrenzt) ListItem Kylin NM Kylin NM kylin network applet desktop message Kylin Network Applet Desktop-Nachricht MainWindow kylin-nm Kylin-NM LAN 有线网络 LAN WLAN 无线局域网 WLAN Show MainWindow MainWindow anzeigen Settings 设置网络项 Einstellungen Network Connectivity Detection Network tool Netzwerk-Tool Network Card Netzwerkkarte Not connected to the network Nicht mit dem Netzwerk verbunden MultipleDnsWidget DNS server(Drag to sort) DNS-Server (zum Sortieren ziehen) Click "+" to configure DNS Klicken Sie auf "+", um DNS zu konfigurieren Settings Einstellungen NetDetail Kylin NM Kylin NM kylin network desktop message Kylin Network Desktop-Nachricht Detail Detail IPv4 IPv4-Schnittstelle IPv6 IPv6-Schnittstelle Security Sicherheit Close 关闭 Config Konfiguration Confirm Bestätigen Cancel Abbrechen Forget this network Vergessen Sie dieses Netzwerk Delete this network Dieses Netzwerk löschen Add LAN Connect LAN-Verbindung hinzufügen Connect Hidden WLAN Verstecktes WLAN verbinden None Nichts Auto Auto start check ipv4 address conflict IPv4-Adresskonflikt prüfen start check ipv6 address conflict IPv6-Adresskonflikt prüfen ipv4 address conflict! ipv4地址冲突! ipv6 address conflict! ipv6地址冲突! this wifi no support enterprise type Dieser Wifi-Enterprise-Typ ohne Support this wifi no support None type dieses WLAN keine Unterstützung Keiner Typ this wifi no support WPA2 type Dieses WLAN unterstützt keinen WPA2-Typ this wifi no support WPA3 type Dieses WLAN unterstützt keinen WPA3-Typ SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network Merken Sie sich das Netzwerk Security Sicherheit Password Passwort EAP type EAP-Typ Identity Identität Domain Domäne CA certficate CA-Zertifikat no need for CA certificate kein CA-Zertifikat erforderlich User certificate Benutzerzertifikat User private key Privater Schlüssel des Benutzers User key password Kennwort des Benutzerschlüssels Password options Passwort-Optionen Required Erforderlich Ineer authentication Ineer-Authentifizierung Username Nutzername Ask pwd each query Fragen Sie pwd bei jeder Anfrage None Nichts WPA&WPA2 Personal WPA&WPA2 Persönlich WPA&WPA2 Enterprise WPA&WPA2 Enterprise WPA3 Personal WPA3 Persönlich Choose from file... Wählen Sie aus Datei... Store passwords only for this user Kennwörter nur für diesen Benutzer speichern Store password only for this user Passwort nur für diesen Benutzer speichern Store passwords for all users Passwörter für alle Benutzer speichern Store password for all users Passwort für alle Benutzer speichern Ask this password every time Fragen Sie jedes Mal nach diesem Passwort Ask password every time Jedes Mal nach dem Passwort fragen Choose a CA certificate Auswählen eines CA-Zertifikats CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA-Dateien (*.pem, *.der, *.p12, *.crt, *.cer, *.pfx) PAC provisioning PAC-Bereitstellung Allow automatic PAC provisioning Automatische PAC-Bereitstellung zulassen PAC file PAC-Datei Anonymous Anonym Authenticated Beglaubigt Both Beide Choose a PAC file Wählen Sie eine PAC-Datei aus PAC Files (*.pac) PAC-Dateien (*.pac) TabPage Current Device Aktuelles Gerät Devices Closed! Geräte geschlossen! Settings Einstellungen Kylin NM Kylin NM kylin network applet desktop message Kylin Network Applet Desktop-Nachricht VpnPage Wired Device not carried 未插入网线 WiFiConfigDialog WLAN Authentication WLAN-Authentifizierung Input WLAN Information Please Bitte WLAN-Informationen eingeben WLAN ID: WLAN-Kennung: WLAN Name: WLAN-Name: Password: Passwort: Cancl Cancl Ok Okay WlanListItem Not connected Nicht verbunden Disconnect Trennen Connect Verbinden Forget Vergessen Property Eigentum Auto Connect Automatische Verbindung WlanMoreItem More... 更多... Add Others... Weitere hinzufügen... WlanPage WLAN WLAN No wireless network card detected Keine Wireless-Netzwerkkarte erkannt Activated WLAN Aktiviertes WLAN Other WLAN Sonstiges WLAN More... 更多... WLAN Connected Successfully WLAN erfolgreich verbunden WLAN Disconnected Successfully WLAN-Verbindung erfolgreich getrennt Connected: Verbunden: Not Connected Nicht verbunden (Limited) (网络受限) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm kylinnm show kylin-nm wifi page Kylin-NM WLAN-Seite anzeigen show kylin-nm lan page Kylin-NM LAN-Seite anzeigen kylin-nm/src/translations/kylin-nm_fr.ts0000664000175000017500000017731715167646234017401 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type Type de profil réseau Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. Public (recommandé) Les périphériques du réseau ne peuvent pas détecter cet ordinateur. Généralement, il est adapté aux réseaux dans les lieux publics, tels que les aéroports ou les cafés, etc. Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. Les périphériques privés du réseau peuvent détecter cet ordinateur. S’applique généralement à un réseau à la maison ou au travail où vous connaissez et faites confiance aux personnes et aux appareils sur le réseau. Config firewall and security settings Configurer les paramètres de pare-feu et de sécurité ConnectivityPage Network connectivity detection If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. Public network (default) Local area network (intranet) Confirm Confirmer The network is connected and can access the Internet normally. The network is connected and access to the Internet is restricted. Please enter the local area network (intranet) detection address Format error CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name Nom de la connexion IPv4Config IPv4Config Address Adresse Netmask Masque de réseau Default Gateway Passerelle par défaut Address conflict Résoudre les conflits Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Auto (DHCP) Manual Manuelle Invalid address Adresse non valide Invalid subnet mask Masque de sous-réseau non valide Required Obligatoire DetailPage Auto Connection Connexion automatique SSID: SSID : Copied successfully! Copié avec succès ! Copy all Copier tout Please input SSID: Veuillez saisir le SSID : Protocol: Protocole: Security Type: Type de sécurité : Hz: Hz: Chan: Chan: BandWidth: Bande passante: IPv6: IPv6 : IPv4: IPv4 : IPv4 DNS: DNS IPv4 : Mac: Mac: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings Paramètres avancés du serveur DNS Tactic Tactique Timeout Timeout Retry Count Nombre de nouvelles tentatives order commande rotate tourner concurrency Concurrence s s times fois Close Fermer Cancel Annuler Confirm Confirmer EnterpriseWlanDialog Connect Enterprise WLAN 连接企业网 Close 关闭 Wi-Fi network requires authentication Le réseau Wi-Fi nécessite une authentification Access to Wi-Fi network " Accès au réseau Wi-Fi » " requires a password or encryption key. » nécessite un mot de passe ou une clé de chiffrement. Cancel Annuler Connect Relier FirewallDialog Allow your computer to be discovered by other computers and devices on this network? 是否允许你的电脑被此网络上的其他电脑和设备发现? It is recommended that you enable this feature on your home and work networks rather than public networks. 建议你在家庭和工作网络上而非公共网络上启用此功能。 Yse No Allow other devices on this network to discover this computer? Autoriser d’autres périphériques de ce réseau à découvrir cet ordinateur ? It is not recommended to enable this feature on public networks Il n’est pas recommandé d’activer cette fonctionnalité sur les réseaux publics Not allowed (recommended) Non autorisé (recommandé) Allowed Autorisé Ipv4Page IPv4Config IPv4Config Address Adresse Netmask Masque de réseau Default Gateway Passerelle par défaut Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Auto (DHCP) Manual Manuelle Invalid address Adresse non valide Invalid subnet mask Masque de sous-réseau non valide Required Obligatoire Address conflict Résoudre les conflits Ipv6Page IPv6Config IPv6Config Address Adresse Subnet prefix Length Préfixe de sous-réseau Longueur Default Gateway Passerelle par défaut Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Auto (DHCP) Manual Manuelle Required Obligatoire Invalid address Adresse non valide Invalid gateway Passerelle non valide Address conflict Résoudre les conflits JoinHiddenWiFiPage Please enter the network information Veuillez saisir les informations du réseau Network name(SSID) Nom du réseau (SSID) Remember the Network 记住该网络 Show Network List Afficher la liste des réseaux Cancel Annuler Join Unir Required Obligatoire Find and Join WLAN Rechercher et rejoindre le WLAN LanListItem Not connected Non connecté Wired Device not carried Appareil filaire non transporté Disconnect Déconnecter Connect Relier Property Propriété Delete Supprimer LanPage No ethernet device avaliable Aucun périphérique Ethernet n’est disponible LAN LAN conflict, unable to connect to the network normally! conflit, impossible de se connecter au réseau normalement ! Activated LAN LAN activé Inactivated LAN LAN inactivé LAN Disconnected Successfully 有线网络已断开 Wired Device not carried Appareil filaire non transporté LAN Connected Successfully 有线网络已连接 Connected: Relié: Not Connected Non connecté (Limited) (Limité) ListItem Kylin NM Kylin NM kylin network applet desktop message Kylin Network applet message de bureau MainWindow kylin-nm kylin-nm LAN 有线网络 LAN WLAN 无线局域网 Réseau local sans fil (WLAN) Show MainWindow Afficher MainWindow Settings 设置网络项 Paramètres Network Connectivity Detection Network tool Outil réseau Network Card Carte réseau Not connected to the network Non connecté au réseau MultipleDnsWidget DNS server(Drag to sort) Serveur DNS(Glisser pour trier) Click "+" to configure DNS Cliquez sur « + » pour configurer le DNS Settings Paramètres NetDetail Kylin NM Kylin NM kylin network desktop message Message de Kylin Network Desktop Detail Détail IPv4 IPv4 (en anglais seulement) IPv6 IPv6 (en anglais seulement) Security Sécurité Close 关闭 Config Configuration Confirm Confirmer Cancel Annuler Forget this network Oubliez ce réseau Delete this network Supprimer ce réseau Add LAN Connect Ajouter une connexion LAN Connect Hidden WLAN Connecter un WLAN caché None Aucun Auto Auto start check ipv4 address conflict Démarrer la vérification du conflit d’adresses IPv4 start check ipv6 address conflict Démarrer la vérification du conflit d’adresses IPv6 ipv4 address conflict! ipv4地址冲突! ipv6 address conflict! ipv6地址冲突! this wifi no support enterprise type Ce type d’entreprise WiFi sans prise en charge this wifi no support None type ce wifi pas de support Aucun type this wifi no support WPA2 type ce wifi ne prend pas en charge le type WPA2 this wifi no support WPA3 type ce wifi ne prend pas en charge le type WPA3 SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network N’oubliez pas le réseau Security Sécurité Password Mot de passe EAP type Type de PAE Identity Identité Domain Domaine CA certficate Certificat CA no need for CA certificate pas besoin de certificat d’autorité de certification User certificate Certificat d’utilisateur User private key Clé privée de l’utilisateur User key password Mot de passe de la clé utilisateur Password options Options de mot de passe Required Obligatoire Ineer authentication Authentification Ineer Username Nom d’utilisateur Ask pwd each query Demandez à pwd chaque requête None Aucun WPA&WPA2 Personal WPA&WPA2 Personnel WPA&WPA2 Enterprise WPA&WPA2 Entreprise WPA3 Personal WPA3 Personnel Choose from file... Choisissez parmi le fichier... Store passwords only for this user Stocker les mots de passe uniquement pour cet utilisateur Store password only for this user Stocker le mot de passe uniquement pour cet utilisateur Store passwords for all users Stocker les mots de passe de tous les utilisateurs Store password for all users Stocker le mot de passe de tous les utilisateurs Ask this password every time Demandez ce mot de passe à chaque fois Ask password every time Demander le mot de passe à chaque fois Choose a CA certificate Choisir un certificat d’autorité de certification CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Fichiers CA (*.pem *.der *.p12 *.crt *.cer *.pfx) PAC provisioning Approvisionnement PAC Allow automatic PAC provisioning Autoriser le provisionnement automatique des PAC PAC file Fichier PAC Anonymous Anonyme Authenticated Authentifié Both Les deux Choose a PAC file Choisir un fichier PAC PAC Files (*.pac) Fichiers PAC (*.pac) TabPage Current Device Appareil actuel Devices Closed! Appareils fermés ! Settings Paramètres Kylin NM Kylin NM kylin network applet desktop message Kylin Network applet message de bureau VpnPage Wired Device not carried 未插入网线 WiFiConfigDialog WLAN Authentication Authentification WLAN Input WLAN Information Please Entrez les informations WLAN s’il vous plaît WLAN ID: ID WLAN : WLAN Name: Nom du WLAN : Password: Mot de passe: Cancl Cancl (en anglais seulement) Ok D’accord WlanListItem Not connected Non connecté Disconnect Déconnecter Connect Relier Forget Oublier Property Propriété Auto Connect Connexion automatique WlanMoreItem More... 更多... Add Others... Ajoutez-en d’autres... WlanPage WLAN Réseau local sans fil (WLAN) No wireless network card detected Aucune carte réseau sans fil n’a été détectée Activated WLAN WLAN activé Other WLAN Autre WLAN More... 更多... WLAN Connected Successfully Connexion WLAN réussie WLAN Disconnected Successfully Le WLAN s’est déconnecté avec succès Connected: Relié: Not Connected Non connecté (Limited) (网络受限) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm kylinnm show kylin-nm wifi page Afficher la page WiFi Kylin-NM show kylin-nm lan page Afficher la page LAN Kylin-NM kylin-nm/src/translations/kylin-nm_es.ts0000664000175000017500000017704615167646234017400 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type Tipo de perfil de red Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. Público (recomendado) Los dispositivos de la red no pueden detectar este equipo. Generalmente, es adecuado para redes en lugares públicos, como aeropuertos o cafeterías, etc. Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. Los dispositivos privados de la red pueden detectar este equipo. Por lo general, se aplica a una red en el hogar o el trabajo en la que conoce y confía en las personas y los dispositivos de la red. Config firewall and security settings Configurar el cortafuegos y la configuración de seguridad ConnectivityPage Network connectivity detection If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. Public network (default) Local area network (intranet) Confirm Confirmar The network is connected and can access the Internet normally. The network is connected and access to the Internet is restricted. Please enter the local area network (intranet) detection address Format error CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name Nombre de la conexión IPv4Config IPv4Config Address Dirección Netmask Máscara de red Default Gateway Puerta de enlace predeterminada Address conflict Abordar los conflictos Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Automático (DHCP) Manual Manual Invalid address Dirección no válida Invalid subnet mask Máscara de subred no válida Required Obligatorio DetailPage Auto Connection Conexión automática SSID: SSID: Copied successfully! ¡Copiado con éxito! Copy all Copiar todo Please input SSID: Por favor, introduzca el SSID: Protocol: Protocolo: Security Type: Tipo de seguridad: Hz: Hz: Chan: Chan: BandWidth: Ancho de banda: IPv6: IPv6: IPv4: IPv4: IPv4 DNS: DNS IPv4: Mac: Mac: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings Configuración avanzada del servidor DNS Tactic Táctica Timeout Interrupción Retry Count Recuento de reintentos order orden rotate rotar concurrency concurrencia s s times veces Close Cerrar Cancel Cancelar Confirm Confirmar EnterpriseWlanDialog Connect Enterprise WLAN 连接企业网 Close 关闭 Wi-Fi network requires authentication La red Wi-Fi requiere autenticación Access to Wi-Fi network " Acceso a la red Wi-Fi " " requires a password or encryption key. " requiere una contraseña o clave de cifrado. Cancel Cancelar Connect Conectar FirewallDialog Allow your computer to be discovered by other computers and devices on this network? 是否允许你的电脑被此网络上的其他电脑和设备发现? It is recommended that you enable this feature on your home and work networks rather than public networks. 建议你在家庭和工作网络上而非公共网络上启用此功能。 Yse No Allow other devices on this network to discover this computer? ¿Permitir que otros dispositivos de esta red detecten este equipo? It is not recommended to enable this feature on public networks No se recomienda habilitar esta función en redes públicas Not allowed (recommended) No permitido (recomendado) Allowed Permitido Ipv4Page IPv4Config IPv4Config Address Dirección Netmask Máscara de red Default Gateway Puerta de enlace predeterminada Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Automático (DHCP) Manual Manual Invalid address Dirección no válida Invalid subnet mask Máscara de subred no válida Required Obligatorio Address conflict Abordar los conflictos Ipv6Page IPv6Config IPv6Config Address Dirección Subnet prefix Length Longitud del prefijo de subred Default Gateway Puerta de enlace predeterminada Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Automático (DHCP) Manual Manual Required Obligatorio Invalid address Dirección no válida Invalid gateway Puerta de enlace no válida Address conflict Abordar los conflictos JoinHiddenWiFiPage Please enter the network information Introduzca la información de la red Network name(SSID) Nombre de la red (SSID) Remember the Network 记住该网络 Show Network List Mostrar lista de redes Cancel Cancelar Join Juntar Required Obligatorio Find and Join WLAN Buscar y unirse a WLAN LanListItem Not connected No conectado Wired Device not carried Dispositivo con cable no transportado Disconnect Desconectar Connect Conectar Property Propiedad Delete Borrar LanPage No ethernet device avaliable No hay dispositivos ethernet disponibles LAN LAN conflict, unable to connect to the network normally! conflicto, no se puede conectar a la red normalmente! Activated LAN LAN activada Inactivated LAN LAN inactivada LAN Disconnected Successfully 有线网络已断开 Wired Device not carried Dispositivo con cable no transportado LAN Connected Successfully 有线网络已连接 Connected: Conexo: Not Connected No conectado (Limited) (Limitado) ListItem Kylin NM Kylin NM kylin network applet desktop message Mensaje de escritorio del applet de red Kylin MainWindow kylin-nm Kylin-NM LAN 有线网络 LAN WLAN 无线局域网 WLAN Show MainWindow Mostrar MainWindow Settings 设置网络项 Configuración Network Connectivity Detection Network tool Herramienta de red Network Card Tarjeta de red Not connected to the network No conectado a la red MultipleDnsWidget DNS server(Drag to sort) Servidor DNS (Arrastrar para ordenar) Click "+" to configure DNS Haga clic en "+" para configurar DNS Settings Configuración NetDetail Kylin NM Kylin NM kylin network desktop message Mensaje de escritorio de Kylin Network Detail Detalle IPv4 IPv4 IPv6 IPv6 Security Seguridad Close 关闭 Config Configuración Confirm Confirmar Cancel Cancelar Forget this network Olvídate de esta red Delete this network Eliminar esta red Add LAN Connect Agregar LAN Connect Connect Hidden WLAN Conectar WLAN oculta None Ninguno Auto Automático start check ipv4 address conflict Iniciar la comprobación del conflicto de direcciones IPv4 start check ipv6 address conflict Iniciar la comprobación del conflicto de direcciones IPv6 ipv4 address conflict! ipv4地址冲突! ipv6 address conflict! ipv6地址冲突! this wifi no support enterprise type Este tipo de empresa WiFi no es compatible this wifi no support None type este wifi no es compatible Ninguno tipo this wifi no support WPA2 type este wifi no es compatible con el tipo WPA2 this wifi no support WPA3 type este wifi no es compatible con el tipo WPA3 SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form Forma Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form Forma Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network Recuerde la Red Security Seguridad Password Contraseña EAP type Tipo de EAP Identity Identidad Domain Dominio CA certficate Certificado de CA no need for CA certificate sin necesidad de certificado de CA User certificate Certificado de usuario User private key Clave privada de usuario User key password Clave de usuario contraseña Password options Opciones de contraseña Required Obligatorio Ineer authentication Autenticación ineer Username Nombre de usuario Ask pwd each query Pregunte a pwd cada consulta None Ninguno WPA&WPA2 Personal WPA&WPA2 Personal WPA&WPA2 Enterprise WPA&WPA2 Empresa WPA3 Personal WPA3 Personal Choose from file... Elegir del archivo... Store passwords only for this user Almacenar contraseñas solo para este usuario Store password only for this user Almacenar contraseña solo para este usuario Store passwords for all users Almacenar contraseñas para todos los usuarios Store password for all users Almacenar contraseña para todos los usuarios Ask this password every time Pregunte esta contraseña cada vez Ask password every time Pregunte la contraseña cada vez Choose a CA certificate Elección de un certificado de CA CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Archivos CA (*.pem *.der *.p12 *.crt *.cer *.pfx) PAC provisioning Aprovisionamiento de PAC Allow automatic PAC provisioning Permitir el aprovisionamiento automático de PAC PAC file Archivo PAC Anonymous Anónimo Authenticated Autenticado Both Ambos Choose a PAC file Elegir un archivo PAC PAC Files (*.pac) Archivos PAC (*.pac) TabPage Current Device Dispositivo actual Devices Closed! ¡Dispositivos cerrados! Settings Configuración Kylin NM Kylin NM kylin network applet desktop message Mensaje de escritorio del applet de red Kylin VpnPage Wired Device not carried 未插入网线 WiFiConfigDialog Dialog Diálogo WLAN Authentication Autenticación WLAN Input WLAN Information Please Ingrese la información de WLAN, por favor WLAN ID: ID de WLAN: WLAN Name: Nombre de WLAN: Password: Contraseña: Cancl Cancl Ok De acuerdo WlanListItem Not connected No conectado Disconnect Desconectar Connect Conectar Forget Olvidar Property Propiedad Auto Connect Conexión automática WlanMoreItem More... 更多... Add Others... Añadir otros... WlanPage WLAN WLAN No wireless network card detected No se ha detectado ninguna tarjeta de red inalámbrica Activated WLAN WLAN activada Other WLAN Otras WLAN More... 更多... WLAN Connected Successfully WLAN conectada correctamente WLAN Disconnected Successfully WLAN desconectada correctamente Connected: Conexo: Not Connected No conectado (Limited) (网络受限) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm kylinnm show kylin-nm wifi page Mostrar la página de Kylin-NM WiFi show kylin-nm lan page Mostrar página LAN de Kylin-NM kylin-nm/src/translations/kylin-nm_bo.ts0000664000175000017500000013360015167646234017355 0ustar fengfeng ConfigPage Network profile type Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. Config firewall and security settings ConnectivityPage Network connectivity detection If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. Public network (default) Local area network (intranet) Confirm The network is connected and can access the Internet normally. The network is connected and access to the Internet is restricted. Please enter the local area network (intranet) detection address Format error CreatNetPage Connection Name IPv4Config Address Netmask Default Gateway Invalid address Invalid subnet mask Required Address conflict Auto(DHCP) Manual DetailPage Auto Connection SSID: Copied successfully! Copy all Please input SSID: Protocol: Security Type: Hz: Chan: BandWidth: IPv4: IPv4 DNS: IPv6: Mac: DnsSettingWidget DNS Server Advanced Settings Tactic Timeout Retry Count order rotate concurrency s times Close Cancel Confirm EnterpriseWlanDialog Wi-Fi network requires authentication Access to Wi-Fi network " " requires a password or encryption key. Cancel Connect FirewallDialog Allow other devices on this network to discover this computer? It is not recommended to enable this feature on public networks Not allowed (recommended) Allowed Ipv4Page Address Netmask Default Gateway IPv4Config Auto(DHCP) Manual Invalid address Invalid subnet mask Required Address conflict Ipv6Page Address Subnet prefix Length Default Gateway IPv6Config Auto(DHCP) Manual Required Invalid address Invalid gateway Address conflict JoinHiddenWiFiPage Please enter the network information Network name(SSID) Show Network List Cancel Join Required Find and Join WLAN LanListItem Not connected Wired Device not carried Disconnect Connect Property Delete LanPage LAN conflict, unable to connect to the network normally! Activated LAN Inactivated LAN Wired Device not carried Connected: (Limited) Not Connected ListItem Kylin NM kylin network applet desktop message MainWindow kylin-nm LAN WLAN Settings Network Connectivity Detection Network tool Network Card Not connected to the network MultipleDnsWidget DNS server(Drag to sort) Click "+" to configure DNS Settings NetDetail Kylin NM kylin network desktop message Detail Security Config Confirm Cancel Forget this network IPv4 IPv6 Add LAN Connect Connect Hidden WLAN Delete this network None Auto start check ipv4 address conflict start check ipv6 address conflict this wifi no support enterprise type this wifi no support None type this wifi no support WPA2 type this wifi no support WPA3 type OneConnForm Form OneLancForm Form SecurityPage Remember the Network Security Password EAP type Identity Domain CA certficate no need for CA certificate User certificate User private key User key password Password options Required Ineer authentication Username Ask pwd each query None WPA&WPA2 Personal WPA&WPA2 Enterprise WPA3 Personal Choose from file... Store passwords only for this user Store password only for this user Store passwords for all users Store password for all users Ask this password every time Ask password every time PAC provisioning Allow automatic PAC provisioning PAC file Anonymous Authenticated Both Choose a CA certificate CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a PAC file PAC Files (*.pac) TabPage Current Device Devices Closed! Settings Kylin NM kylin network applet desktop message WlanListItem Not connected Disconnect Connect Property Forget Auto Connect WlanMoreItem Add Others... WlanPage WLAN Activated WLAN Other WLAN Connected: Not Connected No wireless network card detected WLAN Connected Successfully WLAN Disconnected Successfully main kylinnm show kylin-nm wifi page show kylin-nm lan page kylin-nm/src/translations/kylin-nm_kk.ts0000664000175000017500000022433715167651420017363 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type تور تولىقتاما حۇجات تيپى Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. تورداعٸ الەۋمەتتٸك (ۇسٸنٸس بەرۋ) جابدىقتار نۇ كومپيۋتەردى بايقىيالمايدۇ. ادەتتەگٸندەي ورىنداپ ايتقاندا، ول، الەۋمەتتٸك كەيدە تورعا بۇرشاق كەلەدى ماسەلەن، اۋەجاي ياكي كاقە قاتارلىلار. Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. تورداعٸ ارناۋلى جابدىقتار نۇ كومپيۋتەردى بايقىيالايدۇ. ادەتتە تورداعٸ ٴسىز تۇسىنەتىن ۋا ىستەتىلەتىن شەخس ۋا جابدىقتار، وتباسى ياكي قىزىمەت تورعا بۇرشاق كەلەدى. Config firewall and security settings براندماۋار ۋا حاۋىپسىزدىك تەڭگەرگٸشتٸ تولىقتاۋ ConnectivityPage Network connectivity detection تور جالعانۋدٸ تەكسەرۋ If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. قيسٸق تورعا كىرۋ ولشەمگە ۇشٸراسا، تور IP جالعانۋدٸ تەكسەرۋ تاسٸلدٸ الماستٸر، سونان قاتە سىناڭ. Public network (default) الەۋمەتتٸك تور (كوڭىلدەگى) Local area network (intranet) سۇيىر كولەمدىك تور (intranet) Confirm تۇراقتاندىرۋ The network is connected and can access the Internet normally. تور جالعاندٸ، ينتٸرت توردى نورمال ۇسىنس قىلعالى بولادٸ. The network is connected and access to the Internet is restricted. تور جالعاندٸ، ينتٸرت تورعا بولعان ۇسىنس ولشەمگە كەزٸكتٸ. Please enter the local area network (intranet) detection address سۇيىر كولەمدىك تور (intranet) تەكسەرۋ ٵدٸرىستٸ كىرگىزىڭىز Format error ٴپىشىم قاتەلىگى CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name تور مى IPv4Config IPv4 اتقار بۇيرٸعٸ Address ٵدىرىس Netmask تارماق تور جاسىرىن نومەرى Default Gateway وز قالپٸ تور وتكەلى Connection name is empty or invalid IPv4 address is empty or invalid IPv4 netMask is empty or invalid IPv4 gateway is empty or invalid Address conflict سوقتٸعٸۋٸ شەشىم ەتۋ ەتۋ Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) اۆتوماتتى(DHCP) Manual قولدانبا Invalid address كۇشكە يە ەمەس IPٵدىرىسى Invalid subnet mask كۇشكە يە ەمەس تارماق تور جاسىرىن نومەرى Required ٴسوزسىز DetailPage Auto Connection اۆتوماتتى اۋلاۋ SSID: Copied successfully! ناتيجەلى كوشىرىلگەن! Copy all ٴبارىن كوشىرۋ Please input SSID: SSID نى كىرگىزىڭىز: Protocol: كەلىسىم: Security Type: حاۋىپسىزدىك تيپى: Hz: تور جيىلىگى: Chan: تور جولى: BandWidth: كەڭ بەلدىك: IPv6: IPv4: IPv4 DNS: Mac: فيزيكالىق ٵدىرىس: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings DNS قىزىمەت وتەۋ تۇرلەرى جوعارى دارەجەلىك تەڭگەرگٸش Tactic تاكتيكا Timeout ۋاقىت ٸشٸپ كەتتى Retry Count قاتە ساناۋ order رەت جاعٸ rotate شيراتىلىۋ concurrency جانداس تارقاتۋ s times ٴداۋىر Close تاقاۋ Cancel كۇشىنەن قالدىرۋ Confirm تۇراقتاندىرۋ EnterpriseWlanDialog Connect Enterprise WLAN 连接企业网 Close 关闭 Wi-Fi network requires authentication Wi-Fi تورى ازاماتتىق دالەلدەۋگە مۇقتاج Access to Wi-Fi network " Wi-Fi تورعا اۋلاۋ " requires a password or encryption key. قۇپيا نومەر ياكي سيفىرلاستىرىلعان كىلت قاجەت. Cancel كۇشىنەن قالدىرۋ Connect جالعانۋ FirewallDialog Allow your computer to be discovered by other computers and devices on this network? 是否允许你的电脑被此网络上的其他电脑和设备发现? It is recommended that you enable this feature on your home and work networks rather than public networks. 建议你在家庭和工作网络上而非公共网络上启用此功能。 Yse No Allow other devices on this network to discover this computer? نۇ تورداعٸ باسقا اسباپتاردىڭ نۇ كومپيۋتەردى اشۋ جول قۇياما؟ It is not recommended to enable this feature on public networks الەۋمەتتٸك توردا نۇ قىزىمەتىن قوزعالتۋ ۇسٸنٸس بەرۋ ورىندالمايدى Not allowed (recommended) جول قويىلمايدى (ۇسٸنٸس بەرۋ قىلىندى) Allowed جول قويىلادى Ipv4Page IPv4Config IPv4 اتقار بۇيرٸعٸ Address ٵدىرىس Netmask تارماق تور جاسىرىن نومەرى Default Gateway وز قالپٸ تور وتكەلى Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) اۆتوماتتى(DHCP) Manual قولدانبا IPv4 address is empty or invalid IPv4 netMask is empty or invalid IPv4 gateway is empty or invalid Invalid address كۇشكە يە ەمەس IPٵدىرىسى Invalid subnet mask كۇشكە يە ەمەس تارماق تور جاسىرىن نومەرى Required ٴسوزسىز Address conflict سوقتٸعٸۋٸ شەشىم ەتۋ ەتۋ Ipv6Page IPv6Config IPv6 اتقار بۇيرٸعٸ Address ٵدىرىس Subnet prefix Length تارماق تور الدى قوسىمشا ۇزىندىق Default Gateway وز قالپٸ تور وتكەلى Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) اۆتوماتتى(DHCP) Manual قولدانبا Required ٴسوزسىز Invalid address كۇشكە يە ەمەس IPٵدىرىسى Invalid gateway كۇشكە يە ەمەس تور وتكەلى ٵدىرىسى IPv6 address is empty or invalid IPv6 prefix length is empty or invalid Address conflict سوقتٸعٸۋٸ شەشىم ەتۋ ەتۋ JoinHiddenWiFiPage Please enter the network information تور حاباردٸ كىرگىزىڭىز Network name(SSID) تور مى (SSID) Remember the Network 记住该网络 Show Network List تور تٸزٸمدٸكدٸ كورسەتۋ Cancel كۇشىنەن قالدىرۋ Join قوسىلۋ Required ٴسوزسىز Find and Join WLAN WLAN نى تابۋ ۋا قوسۋ LanListItem Not connected جالعاۋنبادٸ Wired Device not carried تور سىمى قاتىسپاعان Disconnect ۇزارتىۋ Connect جالعانۋ Property قاسيەت Delete ٴوشىرۋ LanPage No ethernet device avaliable LAN conflict, unable to connect to the network normally! سوقتٸعٸۋ، تورعا نورمال جالعاعالٸ بولمادى! No wired network card detected Activated LAN اتۋ Inactivated LAN قۇزغىتىلمىغان Connected, restricting access No internet access. Please click Network Check to specific reasons. Network Check LAN Disconnected Successfully 有线网络已断开 Wired Device not carried تور سىمى قاتىسپاعان LAN Connected Successfully 有线网络已连接 Connected: سىلتەمەلەر: Not Connected جالعاۋنبادٸ (Limited) (شەكتەلگەن) ListItem Kylin NM kylin network applet desktop message چىلىن تور قۇرالى حابار كورسەتپەسى MainWindow kylin-nm kylin-تور قۇرالى LAN 有线网络 WLAN 无线局域网 سىمسىز تور Show MainWindow 打开网络工具 Settings 设置网络项 ورنالاسترعان ەتۋ Network Connectivity Detection تور جالعانۋدٸ تەكسەرۋ Network tool تور قۇرالى Network Card تور كارتاسى Not connected to the network تورعا جالعانباعان MultipleDnsWidget DNS server(Drag to sort) DNS قىزىمەت وتەۋ تۇرلەرى (سوزىلمالى تارتىپ بويىنشا تٸزٸلدٸ) Click "+" to configure DNS + نى تۇرتىپ DNS نى ورنالاستىر Settings ورنالاسترعان ەتۋ NetDetail Kylin NM kylin network desktop message تور ەسكەرتپە حابارى Detail ناقتىلاپ مازمۇنى IPv4 IPv6 Security حاۋىپسىزدىك start check IPv4 address conflict start check IPv6 address conflict Close 关闭 Config تولىقتاما Confirm تۇراقتاندىرۋ Cancel كۇشىنەن قالدىرۋ Forget this network نۇ توردى ۇمٸتٸلپ ۇياتسىز Delete this network نۇ توردى ٴوشىرۋ Add LAN Connect LAN جالعانۋدٸ قوسۋ Connect Hidden WLAN جاسىرىن WLAN عا اۋلاۋ None جوق Auto ماشينا start check ipv4 address conflict 开始检测 ipv4 地址冲突 start check ipv6 address conflict 开始检测 ipv6 地址冲突 ipv4 address conflict! ipv4地址冲突! ipv6 address conflict! ipv6地址冲突! this wifi no support enterprise type نۇ سىمسىز تور كاسپورىن تور ادەتتە قولدامايدى this wifi no support None type بۇسىمسىز تور قۇرعاق كيكستارتەر قولدامايدى this wifi no support WPA2 type نۇ سىمسىز تور WPA2ادەتتە قولدامايدى this wifi no support WPA3 type نۇ سىمسىز تور WPA3ادەتتە قولدامايدى SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form پىشىن Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form پىشىن Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network وسى توردى ەستە ساقتاۋ Security حاۋىپسىزدىك Password قۇپيا نۇمىردى وزگەرتۋ EAP type EAP تۇرى Identity ازاماتتىق كۋالىك Domain تور مى CA certficate CA كىناشكا no need for CA certificate CA كنەشكاسنڭ قاجەتى جوق User certificate پايدالانۋشٸ كناشكاسى User private key پايدالانۋشٸ جەكە كىلت User key password پايدالانۋشٸ كىلت پارولى Password options قۇپيا نومەر تالدانباسٸ Required ٴسوزسىز Ineer authentication ٸشكٸ قىسىمى دالەلدەۋ Username پايدالانۋشٸ مى Ask pwd each query ٵر رەت قۇپيا نۇمىردى سۇراۋ None جوق WPA&WPA2 Personal WPA&WPA2 جەكە WPA&WPA2 Enterprise WPA&WPA2 كاسپورىن WPA3 Personal WPA3 جەكە Choose from file... حۇجاتىن تالداۋ... Store passwords only for this user تەك نۇ ٸستەتۋشٸنٸڭ قۇپيا نۇمىردى ساقتايدى Store password only for this user تەك نۇ ٸستەتۋشٸنٸڭ قۇپيا نۇمىردى ساقتاۋ Store passwords for all users بارلٸق ٸستەتۋشٸنٸڭ قۇپيا نۇمىردى ساقتاۋ Store password for all users بارلٸق ٸستەتۋشٸنٸڭ قۇپيا نۇمىردى ساقتاۋ Ask this password every time ٵر رەت نۇ قۇپيا نۇمىردى سۇراۋ Ask password every time ٵر رەت قۇپيا نومەر سۇراۋ Wifi password length less than 8 TLS identity is empty CA cert filepath is invalid Client cert filepath is invalid Client private key filepath is invalid Client private key password is empty User name or user password is empty No PAC file is selected Choose a CA certificate CA كناشكاسى تالداۋ PAC Files ( *.pac) CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) PAC provisioning PAC مەنەن قامداعٸش Allow automatic PAC provisioning PAC نى اۆتوماتتى تەڭشەۋگە جول قويادى PAC file PAC حۇجاتى Anonymous اتسىز Authenticated راستلىق دالەلدەۋ Both ەكەۋى CA Files ( *.pem *.der *.p12 *.crt *.cer *.pfx) Choose a PAC file PAC مەنەن قامداعٸش PAC Files (*.pac) PAC 文件(*.pac) TabPage Current Device كەزەكتەگى تور قاريتا Devices Closed! جابدىقتار جابٸلدٸ! Settings ورنالاسترعان ەتۋ Kylin NM kylin network applet desktop message چىلىن تور قۇرالى حابار كورسەتپەسى connected جالعانعان VpnPage Wired Device not carried 未插入网线 WarningDialog Unable to save modifications Confirm تۇراقتاندىرۋ WiFiConfigDialog Dialog كوز بەك WLAN Authentication Input WLAN Information Please WLAN ID: WLAN Name: Password: Cancl Ok ماقۇل WlanListItem Not connected جالعاۋنبادٸ Disconnect ۇزارتىۋ Connect جالعانۋ Forget نۇ توردى ۇمىتۋ Property قاسيەت Auto Connect نۇ تورعا اۆتوماتتى اۋلاۋ WlanMoreItem More... 更多... Add Others... باسقا تورعا قوسىلۋ... WlanPage WLAN سىمسىز تور No wireless network card detected سىمسىز تور كارتاسى بايقالمادٸ Activated WLAN قوزعالدى Other WLAN باسقا More... 更多... WLAN Connected Successfully سىمسىز تور جالعانۋ ناتيجەلى قالدى WLAN Disconnected Successfully سىمسىز تور ورنالاسٸۋٸ ناتيجەلى ٷزٸلدٸ The routing end rejects the access of the device The network access at the routing end is full usd set offline mode failed: Connected: سىلتەمەلەر: Not Connected جالعاۋنبادٸ (Limited) (网络受限) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm جەكە تور اسباپبٸ show kylin-nm wifi page جەكە تورٸنڭ سىمسىز تور شاراپات بەتىن كورسەتۋ show kylin-nm lan page جەكە تورٸنڭ سۇيىر كولەمدىك تورىنىڭ شاراپات بەتىن كورسەتۋ kylin-nm/src/translations/kylin-nm_ug.ts0000664000175000017500000023004615167651420017363 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type تور سەپلىمە ھۆججەت تىپى Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. توردىكى ئاممىۋى (تەۋسىيە) ئۈسكۈنىلەر بۇ كومپيۇتېرنى بايقىيالمايدۇ. ئادەتتىكىچە قىلىپ ئېيتقاندا، ئۇ، ئاممىۋى سورۇنلارنىڭ تورىغا ماس كېلىدۇ مەسىلەن، ئايرودروم ياكى قەھۋەخانا قاتارلىقلار. Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. توردىكى مەخسۇس ئۈسكۈنىلەر بۇ كومپيۇتېرنى بايقىيالايدۇ. ئادەتتە توردىكى سىز چۈشىنىدىغان ۋە ئىشىنىدىغان شەخس ۋە ئۈسكۈنىلەر، ئائىلە ياكى خىزمەت تورىغا ماس كېلىدۇ. Config firewall and security settings ئوتتام ۋە بىخەتەرلىك تەڭشىكىنى سەپلەش ConnectivityPage Network connectivity detection تور ئۇلىنىشىنى تەكشۈرۈش If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. ئەگەر تورغا كىرىش چەكلىمىگە ئۇچرىسا، تور IP ئۇلىنىشىنى تەكشۈرۈش ئۇسۇلىنى ئالماشتۇرۇڭ، ئاندىن قايتا سىناڭ. Public network (default) ئاممىۋى تور (كۆڭۈلدىكى) Local area network (intranet) تار دائىرىلىك تور (intranet) Confirm جەزملەش The network is connected and can access the Internet normally. تور ئۇلاندى، ئىنتېرنېت تورىنى نورمال زىيارەت قىلغىلى بولىدۇ. The network is connected and access to the Internet is restricted. تور ئۇلاندى، ئىنتېرنېت تورىغا بولغان زىيارەت چەكلىمىگە ئۇچرىدى. Please enter the local area network (intranet) detection address تار دائىرىلىك تور (intranet) تەكشۈرۈش ئادرېسىنى كىرگۈزۈڭ Format error فورمات خاتالىقى CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name تور نامى IPv4Config IPv4 ئىجرا بۇيرۇقى Address ئادرىس Netmask تارماق تور يوشۇرۇن نومۇرى Default Gateway ئەسلىدىكى تور ئۆتكىلى Connection name is empty or invalid ئۇلاش نامى قۇرۇق ياكى ئىناۋەتسىز IPv4 address is empty or invalid Ipv4 ئادرېسى قۇرۇق ياكى قانۇنسىز IPv4 netMask is empty or invalid IPv4 netMask قۇرۇق ياكى ئىناۋەتسىز IPv4 gateway is empty or invalid IPv4 تور بېكىتى قۇرۇق ياكى ئىناۋەتسىز Address conflict توقۇنۇشنى ھەل قىلىش Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) ئاپتوماتىك(DHCP) Manual قوللانما Invalid address ئىناۋەتسىز IPئادرېسى Invalid subnet mask ئىناۋەتسىز تارماق تور يوشۇرۇن نومۇرى Required مۇقەررەر تولدۇرۇش DetailPage Auto Connection ئاپتوماتىك ئۇلاش SSID: SSID: Copied successfully! مۇۋەپپەقىيەتلىك كۆچۈرۈلگەن! Copy all ھەممىنى كۆچۈرۈش Please input SSID: SSID نى كىرگۈزۈڭ: Protocol: كېلىشىم: Security Type: بىخەتەرلىك تىپى: Hz: تور چاستوتىسى: Chan: تور يولى: BandWidth: كەڭ بەلۋاغ: IPv6: يەرلىك ئۇلانما IPv6 ئادرېسى: IPv4: IPv4 ئادرېس IPv4 DNS: IPv4 DNS مۇلازىمېتىرى Mac: فىزىكىلىق ئادرېىس: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings DNS مۇلازىمېتىرى ئالىي دەرىجىلىك تەڭشىكى Tactic تاكتىكا Timeout ۋاقىت ئېشىپ كەتتى Retry Count قايتا ساناش order رەت تەرتىپى rotate پىرقىراش concurrency يانداش تارقىتىش s سېكۇنت times قېتىم سانى Close ياپ Cancel ئەمەلدىن قالدۇرۇش Confirm جەزملەش EnterpriseWlanDialog Connect Enterprise WLAN 连接企业网 Close 关闭 Wi-Fi network requires authentication Wi-Fi تورى سالاھىيەت دەلىللەشكە موھتاج Access to Wi-Fi network " Wi-Fi تورىغا ئۇلاش " requires a password or encryption key. مەخپىي نومۇر ياكى شىفىرلاشتۇرۇلغان ئاچقۇچ لازىم. Cancel ئەمەلدىن قالدۇرۇش Connect ئۇلىنىش FirewallDialog Allow your computer to be discovered by other computers and devices on this network? 是否允许你的电脑被此网络上的其他电脑和设备发现? It is recommended that you enable this feature on your home and work networks rather than public networks. 建议你在家庭和工作网络上而非公共网络上启用此功能。 Yse No Allow other devices on this network to discover this computer? بۇ توردىكى باشقا ئۈسكۈنىلەرنىڭ بۇ كومپيۇتېرنى بايقىشىغا يول قويامدۇ؟ It is not recommended to enable this feature on public networks ئاممىۋى توردا بۇ ئىقتىدارنى قوزغىتىش تەۋسىيە قىلىنمايدۇ Not allowed (recommended) يول قويۇلمايدۇ (تەۋسىيە قىلىنىدۇ) Allowed يول قويۇلىدۇ Ipv4Page IPv4Config IPv4 ئىجرا بۇيرۇقى Address ئادرىس Netmask تارماق تور يوشۇرۇن نومۇرى Default Gateway ئەسلىدىكى تور ئۆتكىلى Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) ئاپتوماتىك(DHCP) Manual قوللانما IPv4 address is empty or invalid Ipv4 ئادرېسى قۇرۇق ياكى قانۇنسىز IPv4 netMask is empty or invalid IPv4 netMask قۇرۇق ياكى ئىناۋەتسىز IPv4 gateway is empty or invalid IPv4 تور بېكىتى قۇرۇق ياكى ئىناۋەتسىز Invalid address ئىناۋەتسىز IPئادرېسى Invalid subnet mask ئىناۋەتسىز تارماق تور يوشۇرۇن نومۇرى Required مۇقەررەر تولدۇرۇش Address conflict توقۇنۇشنى ھەل قىلىش Ipv6Page IPv6Config IPv6 ئىجرا بۇيرۇقى Address ئادرىس Subnet prefix Length تارماق تور ئالدى قوشۇمچە ئۇزۇنلۇق Default Gateway ئەسلىدىكى تور ئۆتكىلى Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) ئاپتوماتىك(DHCP) Manual قوللانما Required مۇقەررەر تولدۇرۇش Invalid address ئىناۋەتسىز IPئادرېسى Invalid gateway ئىناۋەتسىز تور ئۆتكىلى ئادرېسى IPv6 address is empty or invalid IPv6 ئادرېسى قۇرۇق ياكى ئىناۋەتسىز IPv6 prefix length is empty or invalid ئالدى قوشۇمچە ئۇزۇنلۇقى قۇرۇق ياكى ئىناۋەتسىز IPv6 Address conflict توقۇنۇشنى ھەل قىلىش JoinHiddenWiFiPage Please enter the network information تور ئۇچۇرىنى كىرگۈزۈڭ Network name(SSID) تور نامى (SSID) Remember the Network 记住该网络 Show Network List تور تىزىملىكىنى كۆرسىتىش Cancel ئەمەلدىن قالدۇرۇش Join قوشۇلۇش Required مۇقەررەر تولدۇرۇش Find and Join WLAN WLAN نى تېپىش ۋە قوشۇش LanListItem Not connected ئۇلانمىدى Wired Device not carried تور سىمى چېتىلمىغان Disconnect ئۇلىنىش ئۈزۈلدى Connect ئۇلىنىش Property خاسلىق Delete ئۆچۈر LanPage No ethernet device avaliable سىملىق ئۈسكىنە ئۇلانمىغان LAN سىملىق تور conflict, unable to connect to the network normally! توقۇنۇش، تورغا نورمال ئۇلىغىلى بولمىدى! No wired network card detected سىملىق تور كارتىسىنى تەكشۈرمىگەن Activated LAN قورغىتىلدى Inactivated LAN قۇزغىتىلمىغان Connected, restricting access ئۇلاش، زىيارەت قىلىشنى چەكلەش No internet access. Please click Network Check to specific reasons. ئىنتېرنېت تورىنى زىيارەت قىلغىلى بولمايدۇ. تورنى چېكىپ كونكرېت سەۋەبىنى بىلىپ بېقىڭ. Network Check تور تەكشۈرۈش LAN Disconnected Successfully 有线网络已断开 Wired Device not carried تور سىمى چېتىلمىغان LAN Connected Successfully 有线网络已连接 Connected: ئۇلانغانلىرى: Not Connected ئۇلانمىدى (Limited) (چەكلەنگەن) ListItem Kylin NM تور تەسىس قىلىش قورالى kylin network applet desktop message چىلىن تور قورالى ئۇچۇر كۆرسەتمىسى MainWindow kylin-nm kylin-تور قۇرالى LAN 有线网络 سىملىق تور WLAN 无线局域网 سىمسىز دائىرلىك تور Show MainWindow 打开网络工具 Settings 设置网络项 تەڭشەك Network Connectivity Detection تور ئۇلىنىشىنى تەكشۈرۈش Network tool تور قورالى Network Card تور كارتىسى Not connected to the network تورغا ئۇلانمىغان MultipleDnsWidget DNS server(Drag to sort) DNS مۇلازىمېتىرى (سۆرەلمە تەرتىپ بويىچە تىزىلدى) Click "+" to configure DNS + نى چېكىپ DNS نى سەپلەڭ Settings تەڭشەك NetDetail Kylin NM تور تەسىس قىلىش قورالى kylin network desktop message تور ئەسكەرتمە ئۇچۇرى Detail تەپسىلاتلار IPv4 IPv4 IPv6 IPv6 Security بىخەتەرلىك start check IPv4 address conflict IPv4 ئادرېس توقۇنۇشىنى تەكشۈرۈشنى باشلىدى start check IPv6 address conflict IPv6 ئادرېس توقۇنۇشىنى تەكشۈرۈشنى باشلىدى Close 关闭 Config ئاساسىي تەڭشەك Confirm جەزملەش Cancel ئەمەلدىن قالدۇرۇش Forget this network بۇ تورنى ئۇنتۇپ قاپسىز Delete this network بۇ تورنى ئۆچۈرۈش Add LAN Connect LAN ئۇلىنىشىنى قوشۇش Connect Hidden WLAN يوشۇرۇن WLAN غا ئۇلاش None يوق Auto ماشىنا start check ipv4 address conflict 开始检测 ipv4 地址冲突 start check ipv6 address conflict 开始检测 ipv6 地址冲突 ipv4 address conflict! ipv4地址冲突! ipv6 address conflict! ipv6地址冲突! this wifi no support enterprise type بۇ سىمسىز تور كارخانا تور تىپىدىكىنى قوللىمايدۇ this wifi no support None type بۇسىمسىز تور قۇرۇق تىپتىتكىنى قوللىمايدۇ this wifi no support WPA2 type بۇ سىمسىز تور WPA2تىپىدىكىنى قوللىمايدۇ this wifi no support WPA3 type بۇ سىمسىز تور WPA3تىپىدىكىنى قوللىمايدۇ SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form شەكىل Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form شەكىل Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network مۇشۇ تورنى ئەستە ساقلاش Security بىخەتەرلىك Password ئىم EAP type EAP تۈرى Identity كىملىك Domain تور نامى CA certficate CA كېنىشكا no need for CA certificate CA كىنىشكىسىنىڭ ھاجىتى يوق User certificate ئىشلەتكۈچى كىنىشكىسى User private key ئىشلەتكۈچى شەخسىي ئاچقۇچ User key password ئىشلەتكۈچى ئاچقۇچ پارولى Password options مەخپىي نومۇر تاللانمىسى Required مۇقەررەر تولدۇرۇش Ineer authentication ئىچكى قىسىمنى دەلىللەش Username ئىشلەتكۈچى نامى Ask pwd each query ھەر قېتىم مەخپى نومۇرنى سوراش None يوق WPA&WPA2 Personal WPA&WPA2 شەخسى WPA&WPA2 Enterprise WPA&WPA2 كارخانا WPA3 Personal WPA3 شەخسى Choose from file... ھۆججەتتىن تاللاش... Store passwords only for this user پەقەت بۇ ئىشلەتكۈچىنىڭ مەخپىي نومۇرىنى ساقلايدۇ Store password only for this user پەقەت بۇ ئىشلەتكۈچىنىڭ مەخپىي نومۇرىنى ساقلاش Store passwords for all users بارلىق ئىشلەتكۈچىنىڭ مەخپىي نومۇرىنى ساقلاش Store password for all users بارلىق ئىشلەتكۈچىنىڭ مەخپىي نومۇرىنى ساقلاش Ask this password every time ھەر قېتىم بۇ مەخپىي نومۇرنى سوراش Ask password every time ھەر قېتىم مەخپىي نومۇر سوراش Wifi password length less than 8 مەخپىي نومۇرنىڭ ئۇزۇنلۇقى سەككىزدىن كىچىك بولىدۇ Wifi مەخپىي نومۇر TLS identity is empty ئىمزاسىز سالاھىيەت قۇرۇق CA cert filepath is invalid گۇۋاھنامە ھۆججىتىنىڭ يولى قانۇنسىز CA Client cert filepath is invalid ئابونتلار تېرمىنالىدىكى گۇۋاھنامە ھۆججەت يولى ئىناۋەتسىز Client private key filepath is invalid ئابونتلار تېرمىنالىنىڭ شەخسىي ئاچقۇچلۇق ھۆججەت يولى ئىناۋەتسىز Client private key password is empty ئابونتلار تېرمىنالىنىڭ شەخسىي ئاچقۇچ مەخپىي نومۇرى User name or user password is empty ئابونت نامى ياكى ئابونت مەخپىي نومۇرى قۇرۇق بولىدۇ No PAC file is selected PAC ھۆججىتىنى تاللىمىغان Choose a CA certificate CA كىنىشكىسى تاللاش PAC Files ( *.pac) PAC ھۆججەت ( *pac ) CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) PAC provisioning PAC بىلەن تەمىنلەش Allow automatic PAC provisioning PAC نى ئاپتوماتىك تەڭشەشكە يول قويىدۇ PAC file PAC ھۆججىتى Anonymous نامسىز Authenticated راستلىق دەلىللەش Both ئىككىلىسى CA Files ( *.pem *.der *.p12 *.crt *.cer *.pfx) CA ھۆججەت ( *pem*der.p12*crt *.cer.pfx) Choose a PAC file PAC بىلەن تەمىنلەش PAC Files (*.pac) PAC 文件(*.pac) TabPage Current Device نۆۋەتتىكى تور كارتا Devices Closed! ئۈسكۈنىلەر تاقالدى! Settings تەڭشەك Kylin NM تور تەسىس قىلىش قورالى kylin network applet desktop message چىلىن تور قورالى ئۇچۇر كۆرسەتمىسى connected ئۇلانغان VpnPage Wired Device not carried 未插入网线 WarningDialog Unable to save modifications ساقلاپ تۈزىتىش كىرگۈزگىلى بولمايدۇ Confirm جەزملەش WiFiConfigDialog Dialog دىئالوگ WLAN Authentication كىملىك تەكشۈرۈش WLAN Input WLAN Information Please WLAN ئۇچۇرىنى كىرگۈزۈڭ WLAN ID: سىمسىز رايون تورى ID: WLAN Name: WLAN نامى Password: مەخپىي نومۇر Cancl كانكېر Ok ماقۇل WlanListItem Not connected ئۇلانمىدى Disconnect ئۇلىنىش ئۈزۈلدى Connect ئۇلىنىش Forget بۇ تورنى ئۇنتۇش Property خاسلىق Auto Connect بۇ تورغا ئاپتوماتىك ئۇلاش WlanMoreItem More... 更多... Add Others... باشقا تورغا قوشۇلۇش... WlanPage WLAN سىمسىز دائىرلىك تور No wireless network card detected سىمسىز تور كارتىسى بايقالمىدى Activated WLAN قوزغىتىلدى Other WLAN باشقا More... 更多... WLAN Connected Successfully سىمسىز تور ئۇلىنىش مۇۋەپپەقىيەتلىك بولدى WLAN Disconnected Successfully سىمسىز تور ئۇلىنىشى مۇۋەپپەقىيەتلىك ئۈزۈلدى The routing end rejects the access of the device ئۈسكۈنىنىڭ زىيارىتىنى رەت قىلىش The network access at the routing end is full يول ئۇچىدىكى تور زىيارىتى توشۇپ كەتتى usd set offline mode failed: USD تەسىس قىلىش توردىن قېچىش ئەندىزىسى مەغلۇپ بولدى: Connected: ئۇلانغانلىرى: Not Connected ئۇلانمىدى (Limited) (网络受限) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm يەككە تور ئەسۋابى show kylin-nm wifi page يەككە تورنىڭ سىمسىز تور بەت يۈزىنى كۆرسىتىش show kylin-nm lan page يەككە تورنىڭ تار دائىرىلىك تورىنىڭ بەت يۈزىنى كۆرسىتىش kylin-nm/src/translations/kylin-nm_ms.ts0000664000175000017500000021457315167651420017376 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. Config firewall and security settings ConnectivityPage Network connectivity detection If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. Public network (default) Local area network (intranet) Confirm The network is connected and can access the Internet normally. The network is connected and access to the Internet is restricted. Please enter the local area network (intranet) detection address Format error CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name IPv4Config Address Netmask Default Gateway Connection name is empty or invalid IPv4 address is empty or invalid IPv4 netMask is empty or invalid IPv4 gateway is empty or invalid Address conflict Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Manual Invalid address Invalid subnet mask Required DetailPage Auto Connection SSID: Copied successfully! Copy all Please input SSID: Protocol: Security Type: Hz: Chan: BandWidth: IPv6: IPv4: IPv4 DNS: Mac: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings Tactic Timeout Retry Count order rotate concurrency s times Close Cancel Confirm EnterpriseWlanDialog Connect Enterprise WLAN 连接企业网 Close 关闭 Wi-Fi network requires authentication Access to Wi-Fi network " " requires a password or encryption key. Cancel Connect FirewallDialog Allow your computer to be discovered by other computers and devices on this network? 是否允许你的电脑被此网络上的其他电脑和设备发现? It is recommended that you enable this feature on your home and work networks rather than public networks. 建议你在家庭和工作网络上而非公共网络上启用此功能。 Yse No Allow other devices on this network to discover this computer? It is not recommended to enable this feature on public networks Not allowed (recommended) Allowed Ipv4Page IPv4Config Address Netmask Default Gateway Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Manual IPv4 address is empty or invalid IPv4 netMask is empty or invalid IPv4 gateway is empty or invalid Invalid address Invalid subnet mask Required Address conflict Ipv6Page IPv6Config Address Subnet prefix Length Default Gateway Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Manual Required Invalid address Invalid gateway IPv6 address is empty or invalid IPv6 prefix length is empty or invalid Address conflict JoinHiddenWiFiPage Please enter the network information Network name(SSID) Remember the Network 记住该网络 Show Network List Cancel Join Required Find and Join WLAN LanListItem Not connected Wired Device not carried Disconnect Connect Property Delete LanPage No ethernet device avaliable LAN conflict, unable to connect to the network normally! No wired network card detected Activated LAN Inactivated LAN Connected, restricting access No internet access. Please click Network Check to specific reasons. Network Check LAN Disconnected Successfully 有线网络已断开 Wired Device not carried LAN Connected Successfully 有线网络已连接 Connected: Not Connected (Limited) ListItem Kylin NM kylin network applet desktop message MainWindow kylin-nm LAN 有线网络 WLAN 无线局域网 Show MainWindow 打开网络工具 Settings 设置网络项 Network Connectivity Detection Network tool Network Card Not connected to the network MultipleDnsWidget DNS server(Drag to sort) Click "+" to configure DNS Settings NetDetail Kylin NM kylin network desktop message Detail IPv4 IPv6 Security start check IPv4 address conflict start check IPv6 address conflict Close 关闭 Config Confirm Cancel Forget this network Delete this network Add LAN Connect Connect Hidden WLAN None Auto start check ipv4 address conflict 开始检测 ipv4 地址冲突 start check ipv6 address conflict 开始检测 ipv6 地址冲突 ipv4 address conflict! ipv4地址冲突! ipv6 address conflict! ipv6地址冲突! this wifi no support enterprise type this wifi no support None type this wifi no support WPA2 type this wifi no support WPA3 type SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network Security Password EAP type Identity Domain CA certficate no need for CA certificate User certificate User private key User key password Password options Required Ineer authentication Username Ask pwd each query None WPA&WPA2 Personal WPA&WPA2 Enterprise WPA3 Personal Choose from file... Store passwords only for this user Store password only for this user Store passwords for all users Store password for all users Ask this password every time Ask password every time Wifi password length less than 8 TLS identity is empty CA cert filepath is invalid Client cert filepath is invalid Client private key filepath is invalid Client private key password is empty User name or user password is empty No PAC file is selected Choose a CA certificate PAC Files ( *.pac) CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) PAC provisioning Allow automatic PAC provisioning PAC file Anonymous Authenticated Both CA Files ( *.pem *.der *.p12 *.crt *.cer *.pfx) Choose a PAC file PAC Files (*.pac) PAC 文件(*.pac) TabPage Current Device Devices Closed! Settings Kylin NM kylin network applet desktop message connected VpnPage Wired Device not carried 未插入网线 WarningDialog Unable to save modifications Confirm WiFiConfigDialog Dialog WLAN Authentication Input WLAN Information Please WLAN ID: WLAN Name: Password: Cancl Ok WlanListItem Not connected Disconnect Connect Forget Property Auto Connect WlanMoreItem More... 更多... Add Others... WlanPage WLAN No wireless network card detected Activated WLAN Other WLAN More... 更多... WLAN Connected Successfully WLAN Disconnected Successfully The routing end rejects the access of the device The network access at the routing end is full usd set offline mode failed: Connected: Not Connected (Limited) (网络受限) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm show kylin-nm wifi page show kylin-nm lan page kylin-nm/src/translations/kylin-nm_bo_CN.ts0000664000175000017500000025244415167651420017736 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type དྲ་རྒྱའི་བཀོད་སྒྲིག་ཡིག་ཆའི་རིགས། Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. སྤྱི་སྤྱོད།(འོས་སྦྱོར་བྱས་པ།)དྲ་རྒྱའི་སྒྲིག་ཆས་ཀྱིས་གློག་ཀླད་འདི་མཐོང་མི་ཐུབ། སྤྱིར་བཏང་གི་གནས་ཚུལ་འོག་ཏུ་མི་མང་འདུ་སའི་ནང་གི་དྲ་བ་ལ་འཚམ་པ་སྟེ།དཔེར་ན་གནམ་གྲུ་ཐང་དང་འཚིག་ཇའི་ཁང་སོགས་ལྟ་བུ།. Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. ཆེད་སྤྱོད། དྲ་རྒྱའི་སྒྲིག་ཆས་ཀྱིས་གློག་ཀླད་འདི་མཐོང་ཐུབ། སྤྱིར་བཏང་གི་གནས་ཚུལ་འོག་ཁྱིམ་ཚང་ངམ་ལས་དོན་ཚན་པའི་དྲ་བ་དང་འཚམ་པས།ཁྱེད་ཀྱིས་དྲ་ཐོག་གི་མི་སྒེར་དང་སྒྲིག་ཆས་ལ་ངོས་འཛིན་དང་ཡིད་ཆེས་བྱེད་དགོས།. Config firewall and security settings མེ་འགོག་གྱང་རྩིག་དང་བདེ་འཇགས་བཀོད་སྒྲིག་བྱ་དགོས། ConnectivityPage Network connectivity detection དྲ་རྒྱའི་སྦྲེལ་མཐུད་རང་བཞིན་གྱི་ཞིབ་དཔྱད་ཚད་ལེན། If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. གལ་ཏེ་དྲ་སྦྲེལ་ལ་འཚམས་འདྲི་བྱེད་པར་ཚོད་འཛིན་ཐེབས་པ་དང་། དྲ་རྒྱའི་IPལ་ཞིབ་དཔྱད་ཚད་ལེན་བྱེད་ཐབས་བརྗེས་ནས་ཚོད་ལྟ་བྱེད་དགོས།. Public network (default) སྤྱི་པའི་དྲ་རྒྱ། (ཁས་མ་བླངས་པ། ) Local area network (intranet) ཅུས་ཁོངས་དྲ་བ། (ནང་དྲ། ) Confirm ཐག་ཆོད། The network is connected and can access the Internet normally. དྲ་རྒྱ་སྦྲེལ་མཐུད་བྱས་ཟིན་པས་རྒྱུན་ལྡན་གྱི་དྲ་སྦྲེལ་ལ་འཚམས་འདྲི་བྱས་ཆོག. The network is connected and access to the Internet is restricted. དྲ་རྒྱ་སྦྲེལ་མཐུད་བྱས་ཟིན་པས་དྲ་སྦྲེལ་ལ་འཚམས་འདྲི་བྱས་པ་རེད།. Please enter the local area network (intranet) detection address ཅུས་ཁོངས་ཀྱི་དྲ་རྒྱའི་(ནང་དྲ་)ཞིབ་དཔྱད་ཚད་ལེན་ས་གནས་ནང་འཇུག་བྱེད་རོགས། Format error རྣམ་གཞག་གི་ནོར་འཁྲུལ། CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name འབྲེལ་མཐུད་ཀྱི་མིང་། IPv4Config IPv4ཁུང་ཙི། Address སྡོད་གནས། Netmask དྲ་རྒྱའི་མ་ལག Default Gateway ཁ་ཆད་བཞག་པའི་སྒོ་ཆེན། Connection name is empty or invalid དྲ་རྒྱའི་མིང་ལ་སྟོང་བ་འམ་ཡང་ན་གོ་མི་ཆོད་པ་ཡིན། IPv4 address is empty or invalid Ipv4ཡི་སྡོད་གནས་སྟོང་པའམ་ཁྲིམས་འགལ་ཡིན། IPv4 netMask is empty or invalid IPV4nmasast IPv4 gateway is empty or invalid IPv4ཡི་དྲ་བའི་འགག་སྒོ་ནི་སྟོང་བ་ཡིན་པ་འམ་ཡང་ན་གོ་མི་ཆོད་པ་ཡིན Address conflict ཤག་གནས་གདོང་གཏུག་ Prefs DNS སྔོན་གྲབས་DNS Alternative DNS ཚབ་བྱེད་རང་བཞིན་གྱི་DNS Auto(DHCP) རང་འགུལ་(DHCP) Manual ལག་འགུལ Invalid address རྩིས་འགྲོ་མེད་པའི་ས་གནས། Invalid subnet mask རྩིས་འགྲོ་མེད་པའི་དྲ་བ་འགེབས་སྲུང་བྱེད་པ། Required བླང་བྱ་བཏོན་པ། DetailPage Auto Connection རང་འགུལ་གྱིས་འབྲེལ་མཐུད་བྱེད SSID: SSID: Copied successfully! འདྲ་བཟོ་བྱས་ནས་གྲུབ་འབྲས་ཐོབ་! Copy all ཚང་མ་འདྲ་བཤུས་བྱེད་ Please input SSID: SSID:ནང་འཇུག་གནང་རོགས།: Protocol: གྲོས་ཆོད་ནང་དུ།: Security Type: བདེ་འཇགས་ཀྱི་རིགས་དབྱིབས་ནི།: Hz: དྲ་རྒྱའི་འཕྲིན་ལམ།: Chan: དྲ་བའི་བགྲོད་ལམ།: BandWidth: ཞེང་ཆེ་བ།: IPv6: ས་གནས་དེ་གའི་འབྲེལ་མཐུད་ས་གནས་IPv6ཡོད་པ་སྟེ། IPv4: IPv4ས་གནས། IPv4 DNS: IPV4DSཞབས་ཞུའི་ཡོ་བྱད། Mac: ཨའོ་མོན་ནི།: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings DNSགྱི་ཞབས་ཞུའི་ཡོ་བྱད་མཐོ་རིམ་སྒྲིག་བཀོད། Tactic ཐབས་ཇུས། Timeout དུས་ཚོད་ལས་བརྒལ་བ། Retry Count བསྐྱར་དུ་ཚོད་ལྟ་བྱེད་ཐེངས་གྲངས། order གོ་རིམ། rotate སྐབས་བསྟུན་བྱེད་པ། concurrency འགྲེམས་སྤེལ་ཡང་བྱ། s སྐར་ཆ། times གཉིས་པ། Close ཁ་རྒྱག Cancel དོར་བ། Confirm ཐག་ཆོད། EnterpriseWlanDialog Connect Enterprise WLAN ཁེ་ལས་WLANས སྦྲེལ་མཐུད་བྱེད་པ། Close 关闭 Wi-Fi network requires authentication Wi-Fiཡི་དྲ་རྒྱའི་བླང་བྱར་སྤྲོད་བྱ་རྒྱུའི་བླང་བྱ་བཏོན་ཡོད། Access to Wi-Fi network " Wii-Fiབར་གྱི་དྲ་རྒྱར་འཚམས་འདྲི་གནང་བ་རེད། " requires a password or encryption key. གསང་གྲངས་དང་གསང་བའི་ལྡེ་མིག་དགོས། Cancel དོར་བ། Connect སྦྲེལ་མཐུད་བྱེད་པ། FirewallDialog Allow your computer to be discovered by other computers and devices on this network? ཁྱོད་ཀྱི་གློག་ཀླད་དེ་དྲ་རྒྱའི་སྟེང་གི་གློག་ཀླད་དང་སྒྲིག་ཆས་གཞན་དག་གིས་རྙེད་ཐུབ་བམ།? It is recommended that you enable this feature on your home and work networks rather than public networks. ཁྱེད་ཀྱིས་ཁྱིམ་ཚང་དང་བྱ་བའི་དྲ་རྒྱའི་སྟེང་ནས་སྤྱི་སྤྱོད་མིན་པའི་དྲ་རྒྱའི་སྟེང་ནས་བྱེད་ནུས་འདི་སྤྱོད་རྒྱུའི་གྲོས་འགོ་བཏོན།. Yse དེ་ནི་རེད། No དེ་ལྟར་མ་བྱས་ Allow other devices on this network to discover this computer? དྲ་རྒྱའི་སྟེང་གི་སྒྲིག་ཆས་གཞན་པས་གློག་ཀླད་འདི་རྙེད་དུ་འཇུག་གམ།? It is not recommended to enable this feature on public networks བསམ་འཆར་མེད་།སྤྱི་པའི་དྲ་རྒྱའི་སྟེང་ནས་ནུས་པ་འདི་མགོ་བརྩམས་། Not allowed (recommended) མི་ཆོག་པ་(འོས་སྦྱོར།) Allowed ཆོག་པ་ Ipv4Page IPv4Config IPv4ཁུང་ཙི། Address སྡོད་གནས། Netmask དྲ་རྒྱའི་མ་ལག Default Gateway ཁ་ཆད་བཞག་པའི་སྒོ་ཆེན། Prefs DNS སྔོན་གྲབས་DNS Alternative DNS ཚབ་བྱེད་རང་བཞིན་གྱི་DNS Auto(DHCP) རང་འགུལ་(DHCP) Manual ལག་འགུལ IPv4 address is empty or invalid Ipv4ཡི་སྡོད་གནས་སྟོང་པའམ་ཁྲིམས་འགལ་ཡིན། IPv4 netMask is empty or invalid IPV4nmasast IPv4 gateway is empty or invalid IPv4ཡི་དྲ་བའི་འགག་སྒོ་ནི་སྟོང་བ་ཡིན་པ་འམ་ཡང་ན་གོ་མི་ཆོད་པ་ཡིན Invalid address རྩིས་འགྲོ་མེད་པའི་ས་གནས། Invalid subnet mask རྩིས་འགྲོ་མེད་པའི་དྲ་བ་འགེབས་སྲུང་བྱེད་པ། Required བླང་བྱ་བཏོན་པ། Address conflict ཤག་གནས་གདོང་གཏུག་ Ipv6Page IPv6Config IPv6ཁུང་ཙི། Address སྡོད་གནས། Subnet prefix Length ཡན་ལག་དྲ་རྒྱའི་སྔོན་སྒྲིག་གི་རིང་ཚད། Default Gateway ཁ་ཆད་བཞག་པའི་སྒོ་ཆེན། Prefs DNS སྔོན་གྲབས་DNS Alternative DNS ཚབ་བྱེད་རང་བཞིན་གྱི་DNS Auto(DHCP) རང་འགུལ་(DHCP) Manual ལག་འགུལ Required བླང་བྱ་བཏོན་པ། Invalid address རྩིས་འགྲོ་མེད་པའི་ས་གནས། Invalid gateway རྩིས་འགྲོ་མེད་པའི་དྲ་བའི་འགག་སྒོ། IPv6 address is empty or invalid IPv6གི་སྡོད་གནས་སྟོང་པ་འམ་ཡང་ན་གོ་མི་ཆོད་པར་བརྩི་རྒྱུ། IPv6 prefix length is empty or invalid IPV6གི་སྔོན་གྱི་缀་རིང་ཚད་ནི་སྟོང་བ་ཡིན་པ་འམ་ཡང་ན་གོ་མི་ཆོད་པ་ཡིན། Address conflict ཤག་གནས་གདོང་གཏུག་ JoinHiddenWiFiPage Please enter the network information ཁྱེད་རང་ཞུགས་འདོད་པའི་དྲ་རྒྱའི་ཆ་འཕྲིན་ནང་འཇུག་བྱེད་རོགས། Network name(SSID) དྲ་རྒྱའི་མིང་། (SSID) Remember the Network དྲ་རྒྱ་དེ་སེམས་ལ་འཛིན་དགོས། Show Network List དྲ་རྒྱའི་རེའུ་མིག་གསལ་པོར་མངོན་པ། Cancel དོར་བ། Join དེའི་ནང་དུ་ཞུགས་པ། Required བླང་བྱ་བཏོན་པ། Find and Join WLAN འཚོལ་ཞིབ་བྱས་པ་མ་ཟད་WLANལ་ཞུགས་པ་རེད། LanListItem Not connected འབྲེལ་མཐུད་མི་བྱེད་པ། Wired Device not carried སྐུད་ཡོད་སྒྲིག་ཆས་འཁྱེར་མེད་པ། Disconnect ཆད་པ། Connect སྦྲེལ་མཐུད་བྱེད་པ། Property ངོ་བོ། Delete སུབ་པ། LanPage No ethernet device avaliable ཨེ་ཙི་དྲ་རྒྱའི་སྒྲིག་ཆས་ལ་བཙན་འཛུལ་བྱས་མི་ཆོག། LAN སྐུད་ཡོད་དྲ་བ། conflict, unable to connect to the network normally! གདོང་གཏུག་རྒྱུན་ལྡན་ལྟར་དྲ་རྒྱ་དང་འབྲེལ་མཐུད་བྱེད་ཐབས་བྲལ་བ་རེད།! No wired network card detected སྐུད་ཡོད་དྲ་བའི་གཱ་ལ་ཞིབ་དཔྱད་ཚད་ལེན་མ་བྱས་པ། Activated LAN ངའི་དྲ་རྒྱ། Inactivated LAN དྲ་བ་གཞན་དག Connected, restricting access འབྲེལ་མཐུད་བྱས་ནས་འཚམས་འདྲི་བྱེད་པར་ཚོད་འཛིན་བྱ་དགོས། No internet access. Please click Network Check to specific reasons. དྲ་སྦྲེལ་ལ་འཚམས་འདྲི་བྱེད་ཐབས་མེད། དྲ་རྒྱར་ཞིབ་བཤེར་བྱས་ནས་ཞིབ་ཕྲའི་རྒྱུ་རྐྱེན་ལ་རྒྱུས་ལོན་བྱེད་རོགས། Network Check དྲ་རྒྱའི་ཞིབ་བཤེར། LAN Disconnected Successfully སྐུད་ཡོད་དྲ་བ་ཆད་སོང་། Wired Device not carried སྐུད་ཡོད་སྒྲིག་ཆས་འཁྱེར་མེད་པ། LAN Connected Successfully སྐུད་ཡོད་དྲ་བ་སྦྲེལ་ཡོད། Connected: འབྲེལ་མཐུད་བྱུང་ཡོད།: Not Connected མ་མཐུད་པ། (Limited) (དྲ་བར་ཚོད་འཛིན་ཐེབས་པ་རེད།) ListItem Kylin NM ཅིན་ལིན་ kylin network applet desktop message དྲ་རྒྱའི་ཀུ་ཤུའི་ཅོག་ཙེའི་ཆ་འཕྲིན། MainWindow kylin-nm དྲ་རྒྱའི་ཡོ་བྱད། LAN 有线网络 སྐུད་ཡོད་དྲ་བ། WLAN 无线局域网 སྐུད་མེད་ཁོངས་ཆུང་དྲ་རྒྱ། Show MainWindow རླུང་གཙོ་བོ་མངོན་པར་བྱས་ཡོད། Settings 设置网络项 བཀོད་སྒྲིག་བཅས་བྱ་དགོས། Network Connectivity Detection དྲ་རྒྱའི་སྦྲེལ་མཐུད་རང་བཞིན་གྱི་ཞིབ་དཔྱད་ཚད་ལེན། Network tool དྲ་རྒྱའི་ལག་ཆ་ Network Card དྲ་བྱང་། Not connected to the network དྲ་རྒྱ་དང་སྦྲེལ་མཐུད་མ་བྱས་པ། MultipleDnsWidget DNS server(Drag to sort) DNS ཞབས་ཞུའི་ཡོ་བྱད། (འཐེན་འགུལ་ལ་བརྟེན་ནས་རིམ་སྒྲིག་།) Click "+" to configure DNS "+"མནན་ན་ད་གཟོད་DNSལ་བཀོད་སྒྲིག་བྱེད་ཐུབ། Settings བཀོད་སྒྲིག་བཅས་བྱ་དགོས། NetDetail Kylin NM ཅིན་ལིན་ kylin network desktop message དྲ་རྒྱའི་གསལ་འདེབས་གནས་ཚུལ། Detail ཞིབ་ཕྲའི་གནས་ཚུལ། IPv4 IPv4 IPv6 IPv6 Security བདེ་འཇགས་ཚད། start check IPv4 address conflict IPv4ཡི་ས་གནས་བར་གྱི་འགལ་བར་ཞིབ་བཤེར་བྱེད་མགོ་བརྩམས། start check IPv6 address conflict IPv6གི་ས་གནས་བར་གྱི་འགལ་བར་ཞིབ་བཤེར་བྱེད་མགོ་བརྩམས། Close 关闭 Config བཀོད་སྒྲིག་བཅས་བྱ་དགོས། Confirm ཐག་ཆོད། Cancel དོར་བ། Forget this network དྲ་རྒྱ་འདི་བརྗེད་སོང་། Delete this network དྲ་རྒྱ་དེ་བསུབ་དགོས། Add LAN Connect སྐུད་ཡོད་དྲ་བ་ཁ་སྣོན་བྱ་དགོས། Connect Hidden WLAN ཧའེ་ཏེན་ཝེ་ལན་དང་འབྲེལ་མཐུད་བྱེད་པ། None གཅིག་ཀྱང་མེད། Auto རང་འགུལ start check ipv4 address conflict IPv4ས་གནས་ཀྱི་འགལ་བ་ལ་ཞིབ་བཤེར་བྱེད་འགོ་ཚུགས། start check ipv6 address conflict IPv6གནས་ཡུལ་དང་འགལ་བར་ཞིབ་བཤེར་བྱེད་འགོ་ཚུགས། ipv4 address conflict! ipv4ཐག་གཅོད་གདོང་གཏུག་བྱུང་བ་རེད།! ipv6 address conflict! ipv6ཐག་གཅོད་གདོང་གཏུག་བྱུང་བ་རེད།! this wifi no support enterprise type wifiལ་རྒྱབ་སྐྱོར་མེད་པའི་ཁེ་ལས་ཀྱི་རིགས་དབྱིབས། this wifi no support None type wifiལ་རྒྱབ་སྐྱོར་མི་བྱེད་པར་རིགས་དབྱིབས་གཅིག་ཀྱང་མེད། this wifi no support WPA2 type wifiལ་རྒྱབ་སྐྱོར་མི་བྱེད་པའི་WPA2རིགས་དབྱིབས་ this wifi no support WPA3 type wifiལ་རྒྱབ་སྐྱོར་མི་བྱེད་པའི་WPA3རིགས་དབྱིབས་ SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form གྲུབ་པ། Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form གྲུབ་པ། Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network དྲ་རྒྱ་དེ་སེམས་ལ་འཛིན་དགོས། Security བདེ་འཇགས་ཚད། Password ཕར་འགྲོ་ཚུར་འོང་བྱེད་མཁན། EAP type EAP རིགས་དབྱིབས། Identity ཐོབ་ཐང་། Domain ཁྱབ་ཁོངས། CA certficate CAལག་ཁྱེར། no need for CA certificate CAཡི་ལག་ཁྱེར་མི་དགོས། User certificate སྤྱོད་མཁན་གྱི་ལག་ཁྱེར། User private key སྤྱོད་མཁན་གྱི་སྒེར་གྱི་ལྡེ་མིག User key password སྤྱོད་མཁན་གྱི་ལྡེ་མིག་གི་གསང་ Password options གསང་བའི་ཐོག་ནས་རྣམ་གྲངས་བདམས་པ། Required བླང་བྱ་བཏོན་པ། Ineer authentication དབྱིན་ཆས་ཀྱི་བདེན་དཔང་ར་སྤྲོད་ Username སྤྱོད་མཁན་མིང་།: Ask pwd each query འདྲི་རྩད་རེ་རེར་འདྲི་རྩད་བྱེད་པ། None གཅིག་ཀྱང་མེད། WPA&WPA2 Personal WPA&WPA2མི་སྒེར་གྱི་ངོས་ནས་བཤད་ན། WPA&WPA2 Enterprise WPA&WPA2 ཁེ་ལས། WPA3 Personal WPA3མི་སྒེར་ Choose from file... ཡིག་ཆའི་ནང་ནས་གདམ་ག་རྒྱག་དགོས།... Store passwords only for this user སྤྱོད་མཁན་དེ་ཁོ་ནའི་ཆེད་དུ་གསང་གྲངས་ཉར་ཚགས་བྱས་ཡོད། Store password only for this user སྤྱོད་མཁན་དེ་ཁོ་ནའི་ཆེད་དུ་གསང་གྲངས་ཉར་ཚགས་བྱས་ཡོད། Store passwords for all users སྤྱོད་མཁན་ཚང་མའི་གསང་བ་གསོག་ཉར་བྱེད་དགོས། Store password for all users སྤྱོད་མཁན་ཚང་མའི་གསང་བ་གསོག་ཉར་བྱེད་དགོས། Ask this password every time ཐེངས་རེར་གསང་བ་འདི་འདྲི་རྩད་བྱེད་ཐེངས་རེ་ཡིན། Ask password every time ཐེངས་རེར་གསང་བ་འདི་འདྲི་རྩད་བྱེད་ཐེངས་རེ་ཡིན། Wifi password length less than 8 Wifiལྡེ་མིག་གི་རིང་ཚད་ནི་གནས་བརྒྱད་ལས་དམའ་བ་རེད། TLS identity is empty TLSམིང་བཏགས་པའི་ཐོབ་ཐང་སྟོང་པ་ཡིན། CA cert filepath is invalid CAདཔང་ཡིག་གི་ཡིག་ཆའི་ཐབས་ལམ་ལ་ནུས་པ་མེད། Client cert filepath is invalid སྤྱོད་མཁན་གྱི་དཔང་ཡིག་ཡིག་ཆའི་ཐབས་ལམ་ལ་ནུས་པ་མེད། Client private key filepath is invalid སྤྱོད་མཁན་གྱི་སྒེར་གྱི་ལྡེ་མིག་ཡིག་ཆའི་ཐབས་ལམ་ལ་ནུས་པ་མེད། Client private key password is empty སྤྱོད་མཁན་གྱི་གསང་བའི་གསང་གྲངས་སྟོང་བ་ཡིན། User name or user password is empty སྤྱོད་མཁན་གྱི་མིང་ངམ་གསང་ལྡེ་སྟོང་པ་ཡིན། No PAC file is selected PACཡི་ཡིག་ཆ་བདམས་མེད། Choose a CA certificate CAཡི་དཔང་ཡིག་འདེམས་པ། PAC Files ( *.pac) PACཡིག་ཆ། (pac)། CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA དཔང་ཡིག (*.pem *.der *.p12 *.crt *.cer *.pfx) PAC provisioning PAC གཏན་འབེབས་བྱས་པ། Allow automatic PAC provisioning རང་འགུལ་གྱིས་PACམཚོ་འདོན་བྱས་ཆོག། PAC file PACཡིག་ཆ། Anonymous མིང་མ་བཀོད་པའི་ Authenticated བདེན་དཔང་ར་སྤྲོད་བྱས། Both དེ་གཉིས་ཀ CA Files ( *.pem *.der *.p12 *.crt *.cer *.pfx) CAཡིག་ཆ། (pemm)། **derr..cer P12〕 Choose a PAC file PACཡིག་ཆ་ཞིག་བདམས་པ། PAC Files (*.pac) PACཡིག་ཆ།(*.pac) TabPage Current Device མིག་སྔའི་སྒྲིག་ཆས། Devices Closed! སྒྲིག་ཆས་སྒོ་རྒྱག་པ།! Settings བཀོད་སྒྲིག་བཅས་བྱ་དགོས། Kylin NM ཅིན་ལིན་ kylin network applet desktop message དྲ་རྒྱའི་ཀུ་ཤུའི་ཅོག་ཙེའི་ཆ་འཕྲིན། connected འབྲེལ་མཐུད་བྱེད་ཟིན། VpnPage Wired Device not carried སྐུད་ཡོད་སྒྲིག་ཆས་འཁྱེར་མེད་པ། WarningDialog Unable to save modifications ཉར་ཚགས་དང་བཟོ་བཅོས་རྒྱག་ཐབས་མེད། Confirm ཐག་ཆོད། WiFiConfigDialog Dialog ཁ་བརྡ་བྱེད་པ། WLAN Authentication སྐུད་མེད་བདེན་དཔང་ར་སྤྲོད། Input WLAN Information Please སྐུད་མེད་ཆ་འཕྲིན་ནང་འཇུག་གནང་རོགས། WLAN ID: སྐུད་མེད་ཅུའུ་ཡི་དྲ་རྒྱའི་IDཡིན། WLAN Name: སྐུད་མེད་མིང་།: Password: གསང་བའི་ཨང་གྲངས། Cancl ཁན་ཁེ་ལན། Ok ཐག་ཆོད (_O) WlanListItem Not connected འབྲེལ་མཐུད་མི་བྱེད་པ། Disconnect ཆད་པ། Connect སྦྲེལ་མཐུད་བྱེད་པ། Forget བརྗེད་པ། Property ངོ་བོ། Auto Connect རང་འགུལ་གྱིས་སྦྲེལ་མཐུད་ WlanMoreItem More... 更多... Add Others... གཞན་པ་ཁ་སྣོན་བྱས་ནས་... WlanPage WLAN སྐུད་མེད་ཁོངས་ཆུང་དྲ་རྒྱ། No wireless network card detected སྐུད་མེད་དྲ་རྒྱའི་བྱང་བུ་མ་རྙེད་པ། Activated WLAN ངའི་དྲ་རྒྱ། Other WLAN དྲ་བ་གཞན་དག More... 更多... WLAN Connected Successfully སྐུད་མེད་དྲ་བ་སྦྲེལ་ཡོད། WLAN Disconnected Successfully སྐུད་མེད་དྲ་རྒྱ་ཆད་སོང་། The routing end rejects the access of the device དྲ་རྒྱ་ཞུགས་རྒྱུ་དང་ལེན་མ་བྱས་པར་ཕམ་ཁ་བསྟུད་མར་བྱུང་། The network access at the routing end is full དྲ་རྒྱ་འབྲེལ་མཐུད་བྱས་ནས་བཀང་ཡོད། usd set offline mode failed: USDལས་གནས་ལས་བྲལ་བའི་དཔེ་དབྱིབས་བཀོད་སྒྲིག་བྱས་ནས་ཕམ་ཁ་བྱུང་བ། Connected: འབྲེལ་མཐུད་བྱུང་ཡོད།: Not Connected མ་མཐུད་པ། (Limited) (དྲ་བར་ཚོད་འཛིན་ཐེབས་པ་རེད།) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm དྲ་རྒྱའི་ཡོ་བྱད། show kylin-nm wifi page སྐུད་མེད་དྲ་རྒྱའི་ངོས་མངོན་པར་བྱས་ཡོད། show kylin-nm lan page སྐུད་ཡོད་དྲ་རྒྱའི་ཤོག་ངོས་མངོན་པར་བྱས་ཡོད། kylin-nm/src/translations/kylin-nm_zh_HK.ts0000664000175000017500000021456115167651420017757 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type 網路配置檔類型 Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. 公用(推薦) 網路中的設備不可發現此電腦。 一般情況下適用於公共場所中的網路,如機場或咖啡店等等。 Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. 專用網路中的設備可發現此電腦。 一般情況下適用於家庭或工作單位的網路,您認識並信任網路上的個人和設備。 Config firewall and security settings 配置防火牆和安全設置 ConnectivityPage Network connectivity detection 網路連通性檢測 If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. 如訪問 Internet 受限,請切換網路 IP 連通性檢測方式後再試。 Public network (default) 公網(預設) Local area network (intranet) 區域網(內網) Confirm 確定 The network is connected and can access the Internet normally. 網路已連接,可正常存取 Internet 。 The network is connected and access to the Internet is restricted. 網路已連接,訪問 Internet 受限。 Please enter the local area network (intranet) detection address 請輸入局域網(內網)檢測位址 Format error 格式錯誤 CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name 網路名稱 IPv4Config IPv4 配置 Address IPv4 位址 Netmask 子網掩碼 Default Gateway 默認閘道 Connection name is empty or invalid 連接名稱為空或無效 IPv4 address is empty or invalid Ipv4位址為空或非法 IPv4 netMask is empty or invalid IPv4子網掩碼為空或無效 IPv4 gateway is empty or invalid IPv4 閘道為空或無效 Address conflict 位址衝突 Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) 自動 (DHCP) Manual 手動 Invalid address 無效的IP位址 Invalid subnet mask 無效的子網掩碼 Required 必填 DetailPage Auto Connection 自動連接 SSID: SSID: Copied successfully! 複製成功! Copy all 複製全部 Please input SSID: 請輸入 SSID: Protocol: 協定: Security Type: 安全類型: Hz: 網路頻帶: Chan: 網路通道: BandWidth: 頻寬: IPv6: 本地連結 IPv6 位址: IPv4: IPv4 位址: IPv4 DNS: IPv4 DNS 伺服器: Mac: 物理位址: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings DNS 伺服器高級配置 Tactic 策略 Timeout 超時時間 Retry Count 重試次數 order 順序 rotate 隨機 concurrency 併發 s times Close 關閉 Cancel 取消 Confirm 確定 EnterpriseWlanDialog Connect Enterprise WLAN 连接企业网 Close 关闭 Wi-Fi network requires authentication Wi-Fi 網路要求認證 Access to Wi-Fi network " 訪問Wi-Fi網路 " requires a password or encryption key. 需要密碼或加密金鑰。 Cancel 取消 Connect 連接 FirewallDialog Allow your computer to be discovered by other computers and devices on this network? 是否允许你的电脑被此网络上的其他电脑和设备发现? It is recommended that you enable this feature on your home and work networks rather than public networks. 建议你在家庭和工作网络上而非公共网络上启用此功能。 Yse No Allow other devices on this network to discover this computer? 是否允許此網路上的其他設備發現這台電腦? It is not recommended to enable this feature on public networks 不建議在公共網路上開啟此功能 Not allowed (recommended) 不允許(推薦) Allowed 允許 Ipv4Page IPv4Config IPv4 配置 Address 位址 Netmask 子網掩碼 Default Gateway 默認閘道 Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) 自動 Manual 手動 IPv4 address is empty or invalid Ipv4位址為空或非法 IPv4 netMask is empty or invalid IPv4 netMask 為空或無效 IPv4 gateway is empty or invalid IPv4 閘道為空或無效 Invalid address 無效的IP位址 Invalid subnet mask 無效的子網掩碼 Required 必填 Address conflict 位址衝突 Ipv6Page IPv6Config IPv6 配置 Address 位址 Subnet prefix Length 子網前綴長度 Default Gateway 默認閘道 Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) 自動 Manual 手動 Required 必填 Invalid address 無效的IP位址 Invalid gateway 無效的閘道位址 IPv6 address is empty or invalid IPv6 位址為空或無效 IPv6 prefix length is empty or invalid IPv6 前置綴長度為空或無效 Address conflict 位址衝突 JoinHiddenWiFiPage Please enter the network information 請輸入您想要加入的網路資訊 Network name(SSID) 網路名稱 (SSID) Remember the Network 记住该网络 Show Network List 顯示網路清單 Cancel 取消 Join 加入 Required 必填 Find and Join WLAN 查找並加入無線局域網路 LanListItem Not connected 未連接 Wired Device not carried 未插入網線 Disconnect 斷開 Connect 連接 Property 屬性 Delete 刪除此網路 LanPage No ethernet device avaliable 未檢測到有線設備 LAN 有線網路 conflict, unable to connect to the network normally! 衝突,無法正常連接到網路! No wired network card detected 未檢測到有線網卡 Activated LAN 我的網路 Inactivated LAN 其他網路 Connected, restricting access 連接,限制訪問 No internet access. Please click Network Check to specific reasons. 無法訪問互聯網。 請點擊網路檢查以瞭解具體原因。 Network Check 網路檢查 LAN Disconnected Successfully 有线网络已断开 Wired Device not carried 未插入網線 LAN Connected Successfully 有线网络已连接 Connected: 已連線: Not Connected 未連接 (Limited) (網路受限) ListItem Kylin NM 網路設置工具 kylin network applet desktop message 網路提示消息 MainWindow kylin-nm 網路工具 LAN 有线网络 有線網路 WLAN 无线局域网 無線局域網 Show MainWindow 打开网络工具 Settings 设置网络项 設置網路項 Network Connectivity Detection 網路連通性檢測 Network tool 網路工具 Network Card 網卡 Not connected to the network 未連接網路 MultipleDnsWidget DNS server(Drag to sort) DNS 伺服器高級配置 Click "+" to configure DNS 點擊 「+」配置 DNS Settings 高級設置 NetDetail Kylin NM 網路設置工具 kylin network desktop message 網路提示消息 Detail 詳情 IPv4 IPv4 IPv6 IPv6 Security 安全 start check IPv4 address conflict 開始檢查 IPv4 位址衝突 start check IPv6 address conflict 開始檢查 IPv6 位址衝突 Close 关闭 Config 配置 Confirm 確定 Cancel 取消 Forget this network 忘記此網路 Delete this network 刪除此網路 Add LAN Connect 添加有線網路 Connect Hidden WLAN 連接到隱藏 WLAN None Auto 自動 start check ipv4 address conflict 开始检测 ipv4 地址冲突 start check ipv6 address conflict 开始检测 ipv6 地址冲突 ipv4 address conflict! ipv4地址冲突! ipv6 address conflict! ipv6地址冲突! this wifi no support enterprise type 此 wifi 不支援企業網類型 this wifi no support None type 此 wifi 不支援空類型 this wifi no support WPA2 type 此 wifi 不支援 WPA2 類型 this wifi no support WPA3 type 此 wifi 不支援 WPA3 類型 SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network 記住該網路 Security 安全性 Password 金鑰 EAP type EAP 方法 Identity 匿名身份 Domain CA certficate CA 證書 no need for CA certificate 不需要 CA 證書 User certificate 用戶證書 User private key 使用者私鑰 User key password 用戶金鑰密碼 Password options 密碼選項 Required 必填 Ineer authentication 內部認證 Username 使用者名 Ask pwd each query 每次詢問密碼 None WPA&WPA2 Personal WPA&WPA2 個人 WPA&WPA2 Enterprise WPA&WPA2 企業 WPA3 Personal WPA3 個人 Choose from file... 從檔案選擇... Store passwords only for this user 僅為該使用者存儲密碼 Store password only for this user 僅為該使用者存儲密碼 Store passwords for all users 存儲所有用戶的密碼 Store password for all users 存儲所有用戶的密碼 Ask this password every time 每次詢問這個密碼 Ask password every time 每次詢問這個密碼 Wifi password length less than 8 Wifi密碼長度小於8 TLS identity is empty TLS匿名身份為空 CA cert filepath is invalid CA證書檔路徑非法 Client cert filepath is invalid 用戶端證書檔路徑無效 Client private key filepath is invalid 用戶端私鑰檔案路徑無效 Client private key password is empty 用戶端私鑰密碼為空 User name or user password is empty 使用者名或用戶密碼為空 No PAC file is selected 未選擇 PAC 檔 Choose a CA certificate 選擇一個 CA 證書 PAC Files ( *.pac) PAC 檔案 ( *.pac) CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) PAC provisioning PAC 配置 Allow automatic PAC provisioning 允許自動 PAC 配置 PAC file PAC 檔 Anonymous 匿名 Authenticated 已認證 Both 兩者兼用 CA Files ( *.pem *.der *.p12 *.crt *.cer *.pfx) CA 檔 ( *.pem *.der *.p12 *.crt *.cer *.pfx) Choose a PAC file 選擇一個 PAC 檔 PAC Files (*.pac) PAC 文件(*.pac) TabPage Current Device 當前網卡 Devices Closed! 設備關閉! Settings 網路設置 Kylin NM 網路設置工具 kylin network applet desktop message 網路提示消息 connected 連接 VpnPage Wired Device not carried 未插入网线 WarningDialog Unable to save modifications 無法儲存修改 Confirm 確定 WiFiConfigDialog Dialog 對話 WLAN Authentication WLAN 身份驗證 Input WLAN Information Please 請輸入 WLAN 資訊 WLAN ID: 無線區域網 ID: WLAN Name: WLAN名稱: Password: 密碼: Cancl 坎克爾 Ok 還行 WlanListItem Not connected 未連接 Disconnect 斷開 Connect 連接 Forget 忘記此網路 Property 屬性 Auto Connect 自動加入該網路 WlanMoreItem More... 更多... Add Others... 加入其他網路... WlanPage WLAN 無線局域網 No wireless network card detected 未檢測到無線網卡 Activated WLAN 我的網路 Other WLAN 其他網路 More... 更多... WLAN Connected Successfully 無線網路已連接 WLAN Disconnected Successfully 無線網路已斷開 The routing end rejects the access of the device 路由端拒絕設備的訪問 The network access at the routing end is full 路由端網路訪問已滿 usd set offline mode failed: USD 設定離線模式失敗: Connected: 已連線: Not Connected 未連接 (Limited) (网络受限) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm 麒麟 show kylin-nm wifi page 顯示麒麟-NM WiFi頁面 show kylin-nm lan page 顯示 kylin-nm 局域網頁面 kylin-nm/src/translations/kylin-nm_vi.ts0000664000175000017500000017672715167651420017405 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type Loại hồ sơ mạng Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. Thiết bị công cộng (khuyến nghị) trên mạng không thể phát hiện ra máy tính này. Nói chung, nó phù hợp với các mạng ở những nơi công cộng, chẳng hạn như sân bay hoặc quán cà phê, v.v. Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. Thiết bị riêng trên mạng có thể phát hiện ra máy tính này. Thường áp dụng cho mạng ở nhà hoặc nơi bạn biết và tin tưởng các cá nhân và thiết bị trên mạng. Config firewall and security settings Cấu hình tường lửa và cài đặt bảo mật ConnectivityPage Network connectivity detection Phát hiện kết nối mạng If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. Nếu quyền truy cập Internet bị hạn chế, vui lòng chuyển đổi phương pháp phát hiện kết nối IP mạng và thử lại. Public network (default) Mạng công cộng (mặc định) Local area network (intranet) Mạng cục bộ (mạng nội bộ) Confirm Lưu sửa đổi The network is connected and can access the Internet normally. Mạng được kết nối và có thể truy cập Internet bình thường. The network is connected and access to the Internet is restricted. Mạng được kết nối và quyền truy cập Internet bị hạn chế. Please enter the local area network (intranet) detection address Vui lòng nhập địa chỉ phát hiện mạng cục bộ (mạng nội bộ) Format error Lỗi định dạng CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name Tên kết nối IPv4Config Cấu hình IPv4 Address Địa chỉ Netmask Mặt nạ mạng Default Gateway Gateway mặc định Address conflict Giải quyết xung đột Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Tự động (DHCP) Manual Sách hướng dẫn Invalid address Địa chỉ không hợp lệ Invalid subnet mask Mặt nạ mạng con không hợp lệ Required Bắt buộc DetailPage Auto Connection Kết nối tự động SSID: SSID: Copied successfully! Sao chép thành công! Copy all Sao chép tất cả Please input SSID: Vui lòng nhập SSID: Protocol: Protocol: Security Type: Loại bảo mật: Hz: Hz: Chan: Kênh mạng: BandWidth: Băng thông: IPv6: IPv6: IPv4: Địa chỉ IPv4: IPv4 DNS: Máy chủ DNS IPv4: Mac: Mac: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings Cài đặt nâng cao của máy chủ DNS Tactic Tactic Timeout Thời gian chờ Retry Count Số lần thử lại order Thứ tự phát rotate Xoay concurrency Đồng thời s s times lần Close Thoát Cancel Hủy Confirm Lưu sửa đổi EnterpriseWlanDialog Connect Enterprise WLAN 连接企业网 Close 关闭 Wi-Fi network requires authentication Mạng Wi-Fi yêu cầu xác thực Access to Wi-Fi network " Truy cập vào mạng Wi-Fi " " requires a password or encryption key. " yêu cầu mật khẩu hoặc khóa mã hóa. Cancel Hủy Connect Kết nối FirewallDialog Allow your computer to be discovered by other computers and devices on this network? 是否允许你的电脑被此网络上的其他电脑和设备发现? It is recommended that you enable this feature on your home and work networks rather than public networks. 建议你在家庭和工作网络上而非公共网络上启用此功能。 Yse No Allow other devices on this network to discover this computer? Cho phép các thiết bị khác trên mạng này phát hiện ra máy tính này? It is not recommended to enable this feature on public networks Không nên bật tính năng này trên mạng công cộng Not allowed (recommended) Không được phép (khuyến nghị) Allowed Cho phép Ipv4Page IPv4Config Cấu hình IPv4 Address Địa chỉ Netmask Mặt nạ mạng Default Gateway Gateway mặc định Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Tự động (DHCP) Manual Sách hướng dẫn Invalid address Địa chỉ không hợp lệ Invalid subnet mask Mặt nạ mạng con không hợp lệ Required Bắt buộc điền Address conflict Giải quyết xung đột Ipv6Page IPv6Config Cấu hình IPv6 Address Địa chỉ Subnet prefix Length Độ dài tiền tố mạng con Default Gateway Gateway mặc định Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) Tự động (DHCP) Manual Cẩm nang Required Bắt buộc Invalid address Địa chỉ không hợp lệ Invalid gateway Cổng không hợp lệ Address conflict Giải quyết xung đột JoinHiddenWiFiPage Please enter the network information Nhập thông tin mạng cần kết nối Network name(SSID) Tên mạng (SSID) Remember the Network 记住该网络 Show Network List Hiển thị danh sách mạng Cancel Hủy Join Nối Required Bắt buộc điền Find and Join WLAN Tìm và tham gia WLAN LanListItem Not connected Chưa kết nối Wired Device not carried Thiết bị có dây không được mang theo Disconnect Ngắt kết nối Connect Kết nối Property Thuộc tính Delete Xóa bản sao lưu LanPage No ethernet device avaliable 未检测到有线设备 LAN Mạng có dây conflict, unable to connect to the network normally! xung đột, không thể kết nối mạng bình thường! Activated LAN Mạng của tôi Inactivated LAN Mạng khác LAN Disconnected Successfully 有线网络已断开 Wired Device not carried Chưa cắm cáp mạng LAN Connected Successfully 有线网络已连接 Connected: Đã kết nối: Not Connected Chưa kết nối (Limited) (Mạng bị hạn chế) ListItem Kylin NM Công cụ cài đặt mạng Kylin kylin network applet desktop message Tin nhắn máy tính để bàn applet mạng kylin MainWindow kylin-nm Công cụ mạng LAN 有线网络 LAN WLAN 无线局域网 Mạng WLAN Show MainWindow 打开网络工具 Settings 设置网络项 Mục cài đặt Network Connectivity Detection Phát hiện kết nối mạng Network tool Công cụ mạng Network Card Card mạng Not connected to the network Chưa kết nối mạng MultipleDnsWidget DNS server(Drag to sort) Máy chủ DNS(Kéo để sắp xếp) Click "+" to configure DNS Nhấp vào "+" để định cấu hình DNS Settings Mục cài đặt NetDetail Kylin NM Công cụ cài đặt mạng Kylin kylin network desktop message Tin nhắn máy tính để bàn mạng Kylin Detail Chi tiết IPv4 IPv4 IPv6 IPv6 Security An ninh Close 关闭 Config Cấu hình Confirm Lưu sửa đổi Cancel Hủy Forget this network Quên mạng này Delete this network Xóa mạng này Add LAN Connect Thêm mạng có dây Connect Hidden WLAN Kết nối WLAN ẩn None Sử dùng settings hiện tại của máy in Auto Xe ô tô start check ipv4 address conflict Bắt đầu kiểm tra xung đột địa chỉ IPv4 start check ipv6 address conflict Bắt đầu kiểm tra xung đột địa chỉ IPv6 ipv4 address conflict! ipv4地址冲突! ipv6 address conflict! ipv6地址冲突! this wifi no support enterprise type WiFi này không hỗ trợ mạng doanh nghiệp this wifi no support None type wifi này không hỗ trợ Loại Không có this wifi no support WPA2 type Wifi này không hỗ trợ loại WPA2 this wifi no support WPA3 type wifi này không hỗ trợ loại WPA3 SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network Ghi nhớ mạng lưới Security Đảm bảo an toàn Password Mật khẩu EAP type Xác thực EAP Identity Danh tính ẩn danh Domain Miền CA certficate Chứng nhận CA no need for CA certificate không cần chứng chỉ CA User certificate Chứng chỉ người dùng User private key Khóa riêng của người dùng User key password Mật khẩu khóa riêng tư Password options Tùy chọn mật khẩu Required Bắt buộc Ineer authentication Xác thực Ineer Username Tên người dùng Ask pwd each query Hỏi pwd mỗi truy vấn None Sử dùng settings hiện tại của máy in WPA&WPA2 Personal WPA & WPA2 Cá nhân WPA&WPA2 Enterprise Doanh nghiệp WPA & WPA2 WPA3 Personal WPA3 Cá nhân Choose from file... Chọn từ tệp... Store passwords only for this user Chỉ lưu mật khẩu cho người dùng này Store password only for this user Lưu trữ mật khẩu chỉ cho người dùng này Store passwords for all users Lưu trữ mật khẩu của tất cả người dùng Store password for all users Lưu trữ mật khẩu cho tất cả người dùng Ask this password every time Hỏi mật khẩu này mỗi lần Ask password every time Hỏi mật khẩu mọi lúc Choose a CA certificate Chọn chứng chỉ CA CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Tệp CA (*.pem *.der *.p12 *.crt *.cer *.pfx) PAC provisioning Cấu hình PAC Allow automatic PAC provisioning Cho phép cấu hình PAC tự động PAC file Tệp PAC Anonymous Ẩn danh Authenticated Đã xác thực Both Sử dụng đồng thời cả hai Choose a PAC file Chọn một tệp PAC PAC Files (*.pac) Tệp PAC (*.pac) TabPage Current Device Thiết bị hiện tại Devices Closed! Thiết bị đã đóng! Settings Cài đặt Kylin NM Công cụ cài đặt mạng Kylin kylin network applet desktop message Thông báo nhắc nhở mạng VpnPage Wired Device not carried 未插入网线 WlanListItem Not connected Chưa kết nối Disconnect Ngắt Connect Kết nối Forget Quên Property Tài sản Auto Connect Tự động kết nối mạng này WlanMoreItem More... 更多... Add Others... Thêm người khác... WlanPage WLAN Mạng cục bộ không dây No wireless network card detected Không phát hiện thấy card mạng không dây Activated WLAN Mạng của tôi Other WLAN Mạng khác More... 更多... WLAN Connected Successfully WLAN kết nối thành công WLAN Disconnected Successfully Mạng không dây đã ngắt kết nối Connected: Đã kết nối: Not Connected Chưa kết nối (Limited) (网络受限) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm Kylinnm show kylin-nm wifi page Hiển thị trang WiFi Kylin-NM show kylin-nm lan page Hiển thị trang mạng LAN Kylin-NM kylin-nm/src/translations/kylin-nm_mn.ts0000664000175000017500000025122215167651420017361 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ ᠹᠠᠢᠯ ᠤ᠋ᠨ ᠳᠦᠷᠦᠯ Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. ᠨᠡᠢᠳᠡ ᠵᠢᠨ ᠰᠦᠯᠵᠢᠶᠡᠨ ( ᠳᠠᠨᠢᠯᠴᠠᠭᠤᠯᠬᠤ) ᠳ᠋ᠤ᠌ ᠬᠢ ᠳᠦᠬᠦᠬᠡᠷᠦᠮᠵᠢ ᠲᠤᠰ ᠺᠣᠮᠫᠢᠦ᠋ᠲ᠋ᠧᠷ ᠢ᠋ ᠮᠡᠳᠡᠵᠤ ᠪᠣᠯᠬᠤ ᠥᠬᠡᠢ᠂ ᠶᠡᠷᠦᠳᠡ ᠵᠢᠨ ᠪᠠᠢᠳᠠᠯ ᠳ᠋ᠤ᠌ ᠣᠯᠠᠨ ᠨᠡᠢᠳᠡ ᠵᠢᠨ ᠳᠠᠯᠠᠪᠠᠢ ᠳ᠋ᠤ᠌ ᠬᠢ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠬᠡᠷᠡᠭᠯᠡᠨ᠎ᠡ᠂ ᠵᠢᠰᠢᠶᠡᠯᠡᠪᠡᠯ ᠨᠢᠰᠬᠡᠯ ᠤ᠋ᠨ ᠪᠠᠭᠤᠳᠠᠯ ᠤ᠋ᠨ ᠺᠤᠹᠸ ᠵᠢᠨ ᠦᠷᠦᠬᠡ ᠵᠡᠷᠭᠡ᠃ Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. ᠳᠤᠰᠬᠠᠢ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ᠂ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠳᠦᠬᠦᠬᠡᠷᠦᠮᠵᠢ ᠲᠤᠰ ᠺᠣᠮᠫᠢᠦ᠋ᠲ᠋ᠧᠷ ᠢ᠋ ᠣᠯᠵᠤ ᠮᠡᠳᠡᠪᠡ᠂ ᠶᠡᠷᠦᠳᠡ ᠵᠢᠨ ᠪᠠᠢᠳᠠᠯ ᠳ᠋ᠤ᠌ ᠬᠡᠷᠦᠢ ᠤ᠋ᠨ ᠪᠤᠶᠤ ᠠᠯᠪᠠᠨ ᠪᠠᠢᠭᠤᠯᠭ᠎ᠠ ᠵᠢᠨ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠬᠡᠷᠡᠭᠯᠡᠨ᠎ᠡ᠂ ᠲᠠ ᠳᠠᠨᠢᠬᠤ ᠮᠦᠷᠳᠡᠭᠡᠨ ᠨᠠᠢᠳᠠᠪᠤᠷᠢᠳᠠᠢ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳᠡᠬᠡᠷᠡᠬᠢ ᠬᠤᠪᠢ ᠬᠥᠮᠦᠨ ᠪᠤᠶᠤ ᠳᠦᠬᠦᠬᠡᠷᠦᠮᠵᠢ᠃ Config firewall and security settings ᠭᠠᠯ ᠰᠡᠷᠬᠡᠢᠯᠡᠬᠦ ᠬᠡᠷᠡᠮ ᠪᠤᠯᠤᠨ ᠠᠮᠤᠷ ᠳᠦᠪᠰᠢᠨ ᠤ᠋ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ ConnectivityPage Network connectivity detection ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠨᠡᠪᠳᠡᠷᠡᠬᠦ ᠴᠢᠨᠠᠷ ᠢ᠋ ᠬᠢᠨᠠᠨ ᠬᠡᠮᠵᠢᠬᠦ If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. ᠬᠡᠷᠪᠡ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠠᠢᠯᠴᠢᠯᠠᠵᠤ ᠴᠢᠳᠠᠬᠤ ᠥᠬᠡᠢ ᠪᠣᠯ᠂ ᠨᠸᠲ᠎ᠦ᠋ᠨ IP ᠵᠠᠯᠭᠠᠯᠲᠠ᠎ᠶ᠋ᠢᠨ ᠴᠢᠨᠠᠷ᠎ᠤ᠋ᠨ ᠰᠢᠯᠭᠠᠨ ᠪᠠᠢᠴᠠᠭᠠᠬᠤ ᠬᠡᠯᠪᠡᠷᠢ᠎ᠶ᠋ᠢ ᠰᠣᠯᠢᠭᠠᠳ ᠳᠠᠬᠢᠨ ᠳᠤᠷᠰᠢᠭᠠᠷᠠᠢ᠃ Public network (default) ᠨᠡᠢᠳᠡ ᠵᠢᠨ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ( ᠠᠶᠠᠳᠠᠯ) Local area network (intranet) ᠬᠡᠰᠡᠭ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ( ᠳᠣᠲᠣᠭᠠᠳᠤ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ) Confirm ᠲᠣᠭᠲᠠᠭᠠᠬᠤ The network is connected and can access the Internet normally. ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠨᠢᠬᠡᠨᠳᠡ ᠵᠠᠯᠭᠠᠭᠰᠠᠨ᠂ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠬᠡᠪ ᠤ᠋ᠨ ᠠᠢᠯᠴᠢᠯᠠᠵᠤ ᠪᠤᠯᠤᠨ᠎ᠠ᠃ The network is connected and access to the Internet is restricted. ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠨᠢᠬᠡᠨᠳᠡ ᠵᠠᠯᠭᠠᠪᠠ᠂ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠠᠢᠯᠴᠢᠯᠠᠬᠤ ᠬᠢᠵᠠᠭᠠᠷᠯᠠᠭᠳᠠᠪᠠ᠃ Please enter the local area network (intranet) detection address ᠬᠡᠰᠡᠭ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋( ᠳᠤᠳᠤᠭᠠᠳᠤ ᠰᠦᠯᠵᠢᠶ᠎ᠡ) ᠬᠢᠨᠠᠨ ᠬᠡᠮᠵᠢᠭᠰᠡᠨ ᠬᠠᠶᠢᠭ ᠢ᠋ ᠣᠷᠣᠭᠤᠯᠤᠭᠠᠷᠠᠢ Format error ᠬᠡᠯᠪᠡᠷᠢ ᠨᠢ ᠪᠤᠷᠤᠭᠤ CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠨᠡᠷᠡᠢᠳᠦᠯ IPv4Config IPv4 ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Address ᠬᠠᠶᠢᠭ Netmask ᠬᠤᠪᠢᠶᠠᠷᠢ ᠨᠧᠲ᠎ᠤᠨ ᠳᠠᠯᠳᠠᠯᠠᠯ ᠺᠤᠳ᠋ Default Gateway ᠠᠶᠠᠳᠠᠯ ᠨᠸᠲ ᠪᠤᠭᠤᠮᠳᠠ Connection name is empty or invalid ᠬᠣᠯᠪᠣᠬᠤ ᠨᠡᠷᠡᠶᠢᠳᠦᠯ ᠨᠢ ᠬᠣᠭᠣᠰᠣᠨ ᠪᠤᠶᠤ ᠬᠦᠴᠦᠨ ᠦᠭᠡᠢ ᠃ IPv4 address is empty or invalid Ipv4 ᠬᠠᠶᠢᠭ ᠨᠢ ᠬᠣᠭᠣᠰᠣᠨ ᠪᠤᠶᠤ ᠬᠠᠤᠯᠢ ᠪᠤᠰᠤ ᠃ IPv4 netMask is empty or invalid IPv4 netMaassk ᠨᠢ ᠬᠣᠭᠣᠰᠣᠨ ᠪᠤᠶᠤ ᠬᠦᠴᠦᠨ ᠦᠭᠡᠢ ᠃ IPv4 gateway is empty or invalid IPv4 ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠪᠣᠭᠣᠮᠲᠠ ᠨᠢ ᠬᠣᠭᠣᠰᠣᠨ ᠪᠤᠶᠤ ᠬᠦᠴᠦᠨ ᠦᠭᠡᠢ ᠃ Address conflict ᠬᠠᠶᠢᠭ ᠤ᠋ᠨ ᠮᠦᠷᠬᠦᠯᠳᠦᠬᠡᠨ Prefs DNS ᠳᠡᠷᠢᠬᠦᠨ ᠰᠤᠩᠭᠤᠯᠳᠠ DNS Alternative DNS ᠪᠡᠯᠡᠳᠬᠡᠯ ᠰᠤᠩᠭᠤᠯᠳᠠ DNS Auto(DHCP) ᠠᠦ᠋ᠲ᠋ᠣ᠋ (DHCP) Manual ᠭᠠᠷ ᠵᠢᠡᠷ Invalid address ᠬᠦᠴᠦᠨ ᠦᠬᠡᠢ ᠬᠠᠶᠢᠭ Invalid subnet mask ᠬᠦᠴᠦᠨ ᠦᠬᠡᠢ ᠬᠤᠪᠢᠶᠠᠷᠢ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠬᠠᠯᠬᠠᠪᠴᠢ Required ᠡᠷᠬᠡᠪᠰᠢ ᠳᠠᠭᠯᠠᠬᠤ DetailPage Auto Connection ᠠᠦ᠋ᠲ᠋ᠣ᠋ ᠴᠦᠷᠬᠡᠯᠡᠬᠦ SSID: SSID: Copied successfully! ᠺᠤᠫᠢᠳᠠᠪᠠ! Copy all ᠪᠦᠬᠦᠨ ᠢ᠋ ᠺᠤᠫᠢᠳᠠᠬᠤ Please input SSID: SSID ᠢ᠋/ ᠵᠢ ᠤᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ: Protocol: ᠭᠡᠷ᠎ᠡ: Security Type: ᠠᠮᠤᠷ ᠳᠦᠪᠰᠢᠨ ᠤ᠋ ᠳᠦᠷᠦᠯ ᠵᠦᠢᠯ: Hz: ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠳᠠᠪᠳᠠᠮᠵᠢ ᠵᠢᠨ ᠪᠦᠰᠡ: Chan: ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠨᠡᠪᠳᠡᠷᠡᠬᠦ ᠵᠠᠮ: BandWidth: ᠪᠦᠰᠡ ᠵᠢᠨ ᠦᠷᠭᠡᠨ: IPv6: IPv6 ᠬᠠᠶᠢᠭ: IPv4: IPv4 ᠬᠠᠶᠢᠭ: IPv4 DNS: IPv4 ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ: Mac: ᠹᠢᠽᠢᠺ ᠤ᠋ᠨ ᠬᠠᠶᠢᠭ: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings DNS ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ ᠤ᠋ᠨ ᠳᠡᠭᠡᠳᠦ ᠳᠡᠰ ᠤ᠋ᠨ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Tactic ᠪᠤᠳᠤᠯᠭ᠎ᠠ Timeout ᠴᠠᠭ ᠡᠴᠡ ᠬᠡᠳᠦᠷᠡᠬᠦ Retry Count ᠳᠠᠬᠢᠨ ᠳᠤᠷᠰᠢᠭᠰᠠᠨ ᠤᠳᠠᠭ᠎ᠠ order ᠳᠠᠷᠠᠭᠠᠯᠠᠯ rotate ᠳᠠᠰᠢᠷᠠᠮ concurrency ᠵᠡᠷᠭᠡᠳᠡ ᠢᠯᠡᠬᠡᠬᠦ s ᠰᠸᠺᠦ᠋ᠨ᠋ᠲ times ᠤᠳᠠᠭ᠎ᠠ Close ᠬᠠᠭᠠᠬᠤ Cancel ᠪᠣᠯᠢᠬᠤ Confirm ᠲᠣᠭᠲᠠᠭᠠᠬᠤ EnterpriseWlanDialog Connect Enterprise WLAN ᠠᠵᠤ ᠠᠬᠤᠢᠯᠠᠯ ᠤ᠋ᠨ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠴᠦᠷᠬᠡᠯᠡᠬᠦ Close 关闭 Wi-Fi network requires authentication Wi-Fi ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠬᠡᠷᠡᠴᠢᠯᠡᠯ ᠢ᠋ ᠱᠠᠭᠠᠷᠳᠠᠬᠤ Access to Wi-Fi network " Wi-Fi ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠠᠢᠯᠴᠢᠯᠠᠬᠤ " requires a password or encryption key. ᠨᠢᠭᠤᠴᠠ ᠺᠣᠳ᠋ ᠪᠤᠶᠤ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠢ᠋ ᠱᠠᠭᠠᠷᠳᠠᠨ᠎ᠠ᠃ Cancel ᠪᠣᠯᠢᠬᠤ Connect ᠴᠦᠷᠬᠡᠯᠡᠬᠡ FirewallDialog Allow your computer to be discovered by other computers and devices on this network? 是否允许你的电脑被此网络上的其他电脑和设备发现? It is recommended that you enable this feature on your home and work networks rather than public networks. 建议你在家庭和工作网络上而非公共网络上启用此功能。 Yse No Allow other devices on this network to discover this computer? ᠲᠤᠰ ᠳᠦᠯᠵᠢᠶᠡᠨ ᠳᠡᠭᠡᠷᠡᠬᠢ ᠪᠤᠰᠤᠳ ᠳᠦᠬᠦᠬᠡᠷᠦᠮᠵᠢ ᠡᠨᠡ ᠺᠣᠮᠫᠢᠦ᠋ᠲ᠋ᠧᠷ ᠢ᠋ ᠣᠯᠵᠤ ᠮᠡᠳᠡᠬᠦ ᠵᠢ ᠵᠥᠪᠰᠢᠶᠡᠷᠡᠬᠦ ᠤᠤ? It is not recommended to enable this feature on public networks ᠨᠡᠢᠳᠡ ᠵᠢᠨ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳᠡᠭᠡᠷ᠎ᠡ ᠲᠤᠰ ᠴᠢᠳᠠᠪᠬᠢ ᠵᠢ ᠨᠡᠬᠡᠬᠡᠬᠦ ᠥᠬᠡᠢ ᠪᠠᠢᠬᠤ ᠵᠢ ᠰᠠᠨᠠᠭᠤᠯᠵᠤ ᠪᠠᠢᠨ᠎ᠠ Not allowed (recommended) ᠵᠥᠪᠰᠢᠶᠡᠷᠡᠬᠦ ᠥᠬᠡᠢ ( ᠳᠠᠨᠢᠯᠴᠠᠭᠤᠯᠬᠤ) Allowed ᠵᠥᠪᠰᠢᠶᠡᠷᠡᠬᠦ Ipv4Page IPv4Config IPv4 ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Address ᠬᠠᠶᠢᠭ Netmask ᠬᠤᠪᠢᠶᠠᠷᠢ ᠨᠧᠲ᠎ᠤᠨ ᠳᠠᠯᠳᠠᠯᠠᠯ ᠺᠤᠳ᠋ Default Gateway ᠠᠶᠠᠳᠠᠯ ᠨᠸᠲ ᠪᠤᠭᠤᠮᠳᠠ Prefs DNS ᠳᠡᠷᠢᠬᠦᠨ ᠰᠤᠩᠭᠤᠯᠳᠠ DNS Alternative DNS ᠪᠡᠯᠡᠳᠬᠡᠯ ᠰᠤᠩᠭᠤᠯᠳᠠ DNS Auto(DHCP) ᠠᠦ᠋ᠲ᠋ᠣ᠋ (DHCP) Manual ᠭᠠᠷ ᠵᠢᠡᠷ IPv4 address is empty or invalid Ipv4 ᠬᠠᠶᠢᠭ ᠨᠢ ᠬᠣᠭᠣᠰᠣᠨ ᠪᠤᠶᠤ ᠬᠠᠤᠯᠢ ᠪᠤᠰᠤ ᠃ IPv4 netMask is empty or invalid IPv4 ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠬᠠᠯᠬᠠᠯᠠᠬᠤ ᠨᠣᠮᠧᠷ ᠨᠢ ᠬᠣᠭᠣᠰᠣᠨ ᠪᠤᠶᠤ ᠬᠦᠴᠦᠨ ᠦᠭᠡᠢ ᠃ IPv4 gateway is empty or invalid IPv4 ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠪᠣᠭᠣᠮᠲᠠ ᠨᠢ ᠬᠣᠭᠣᠰᠣᠨ ᠪᠤᠶᠤ ᠬᠦᠴᠦᠨ ᠦᠭᠡᠢ ᠃ Invalid address ᠬᠦᠴᠦᠨ ᠦᠬᠡᠢ ᠬᠠᠶᠢᠭ Invalid subnet mask ᠬᠦᠴᠦᠨ ᠦᠬᠡᠢ ᠬᠤᠪᠢᠶᠠᠷᠢ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠬᠠᠯᠬᠠᠪᠴᠢ Required ᠡᠷᠬᠡᠪᠰᠢ ᠳᠠᠭᠯᠠᠬᠤ Address conflict ᠬᠠᠶᠢᠭ ᠤ᠋ᠨ ᠮᠦᠷᠬᠦᠯᠳᠦᠬᠡᠨ Ipv6Page IPv6Config IPv6 ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Address ᠬᠠᠶᠢᠭ Subnet prefix Length ᠬᠤᠪᠢᠶᠠᠷᠢ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠤᠭᠳᠤᠪᠤᠷᠢ ᠵᠢᠨ ᠤᠷᠳᠤ Default Gateway ᠠᠶᠠᠳᠠᠯ ᠨᠸᠲ ᠪᠤᠭᠤᠮᠳᠠ Prefs DNS ᠳᠡᠷᠢᠬᠦᠨ ᠰᠤᠩᠭᠤᠯᠳᠠ DNS Alternative DNS ᠪᠡᠯᠡᠳᠬᠡᠯ ᠰᠤᠩᠭᠤᠯᠳᠠ DNS Auto(DHCP) ᠠᠦ᠋ᠲ᠋ᠣ᠋ (DHCP) Manual ᠭᠠᠷ ᠵᠢᠡᠷ Required ᠡᠷᠬᠡᠪᠰᠢ ᠳᠠᠭᠯᠠᠬᠤ Invalid address ᠬᠦᠴᠦᠨ ᠦᠬᠡᠢ ᠬᠠᠶᠢᠭ Invalid gateway ᠬᠦᠴᠦᠨ ᠦᠬᠡᠢ ᠨᠧᠲ ᠪᠤᠭᠤᠮᠳᠠ IPv6 address is empty or invalid IPv6 ᠬᠠᠶᠢᠭ ᠨᠢ ᠬᠣᠭᠣᠰᠣᠨ ᠪᠤᠶᠤ ᠬᠦᠴᠦᠨ ᠦᠭᠡᠢ ᠃ IPv6 prefix length is empty or invalid IPv6 ᠡᠮᠦᠨᠡᠬᠢ ᠤᠷᠲᠤ ᠶᠢᠨ ᠬᠡᠮᠵᠢᠶ᠎ᠡ ᠨᠢ ᠬᠣᠭᠣᠰᠣᠨ ᠪᠤᠶᠤ ᠬᠦᠴᠦᠨ ᠦᠭᠡᠢ ᠃ Address conflict ᠬᠠᠶᠢᠭ ᠤ᠋ᠨ ᠮᠦᠷᠬᠦᠯᠳᠦᠬᠡᠨ JoinHiddenWiFiPage Please enter the network information ᠲᠠᠨ ᠤ᠋ ᠣᠷᠣᠬᠤ ᠬᠡᠵᠤ ᠪᠠᠢᠭ᠎ᠠ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠰᠤᠷᠠᠭ ᠵᠠᠩᠬᠢ ᠵᠢ ᠣᠷᠣᠭᠤᠯᠤᠭᠠᠷᠠᠢ Network name(SSID) ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠨᠡᠷ᠎ᠡ (SSID) Remember the Network 记住该网络 Show Network List ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠵᠢᠭᠰᠠᠭᠠᠯᠳᠠ ᠵᠢ ᠢᠯᠡᠷᠡᠬᠦᠯᠬᠦ Cancel ᠪᠣᠯᠢᠬᠤ Join ᠣᠷᠣᠬᠤ Required ᠡᠷᠬᠡᠪᠰᠢ ᠳᠠᠭᠯᠠᠬᠤ Find and Join WLAN ᠤᠳᠠᠰᠤ ᠥᠬᠡᠢ ᠬᠡᠰᠡᠭ ᠤ᠋ᠨ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠡᠷᠢᠵᠤ ᠣᠷᠣᠬᠤ LanListItem Not connected ᠵᠠᠯᠭᠠᠭ᠎ᠠ ᠦᠭᠡᠢ Wired Device not carried ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠤᠳᠠᠰᠤ ᠵᠠᠯᠭᠠᠭ᠎ᠠ ᠦᠬᠡᠢ Disconnect ᠴᠦᠷᠬᠡᠯᠡᠬᠡ ᠵᠢ ᠳᠠᠰᠤᠯᠬᠤ Connect ᠴᠦᠷᠬᠡᠯᠡᠬᠡ Property ᠬᠠᠷᠢᠶᠠᠳᠤ ᠴᠢᠨᠠᠷ Delete ᠤᠰᠠᠳᠬᠠᠠᠬᠤ LanPage No ethernet device avaliable ᠤᠳᠠᠰᠤᠳᠤ ᠳᠦᠬᠦᠬᠡᠷᠦᠮᠵᠢ ᠵᠢ ᠪᠠᠢᠴᠠᠭᠠᠵᠤ ᠤᠯᠤᠭᠰᠠᠨ ᠦᠬᠡᠢ LAN ᠤᠲᠠᠰᠤᠲᠤ ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ conflict, unable to connect to the network normally! ᠮᠦᠷᠬᠦᠯᠳᠦᠬᠡᠨ᠂ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠬᠡᠪ ᠤ᠋ᠨ ᠴᠦᠷᠬᠡᠯᠡᠵᠤ ᠴᠢᠳᠠᠬᠤ ᠥᠬᠡᠢ! No wired network card detected ᠤᠲᠠᠰᠤᠲᠤ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠺᠣᠮᠫᠢᠦᠢᠲ᠋ᠧᠷ ᠢ ᠪᠠᠶᠢᠴᠠᠭᠠᠨ ᠰᠢᠯᠭᠠᠭᠰᠠᠨ ᠦᠭᠡᠶ ᠃ Activated LAN ᠮᠢᠨᠤ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ Inactivated LAN ᠪᠤᠰᠤᠳ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ Connected, restricting access ᠵᠠᠯᠭᠠᠵᠤ ᠂ ᠰᠤᠷᠪᠤᠯᠵᠢᠯᠠᠭ᠎ᠠ ᠬᠢᠬᠦ ᠶᠢ ᠬᠢᠵᠠᠭᠠᠷᠯᠠᠬᠤ ᠬᠡᠷᠡᠭᠲᠡᠶ ᠃ No internet access. Please click Network Check to specific reasons. ᠢᠨᠲ᠋ᠧᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳᠦ ᠠᠢ᠌ᠯᠴᠢᠯᠠᠬᠤ ᠶᠢᠨ ᠠᠷᠭ᠎ᠠ ᠦᠭᠡᠢ ᠃ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠪᠠᠶᠢᠴᠠᠭᠠᠯᠲᠠ ᠶᠢ ᠳᠠᠷᠤᠵᠤ ᠪᠣᠳᠠᠲᠠᠶ ᠰᠢᠯᠲᠠᠭᠠᠨ ᠢ ᠣᠶᠢᠯᠠᠭᠠᠭᠠᠷᠠᠢ ᠃ Network Check ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠪᠠᠶᠢᠴᠠᠭᠠᠯᠲᠠ ᠃ LAN Disconnected Successfully ᠤᠳᠠᠰᠤᠳᠤ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠨᠢᠭᠡᠨᠳᠡ ᠳᠠᠰᠤᠯᠪᠠ Wired Device not carried ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠤᠳᠠᠰᠤ ᠵᠠᠯᠭᠠᠭ᠎ᠠ ᠦᠬᠡᠢ LAN Connected Successfully ᠤᠳᠠᠰᠤᠳᠤ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠨᠢᠭᠡᠨᠳᠡ ᠴᠦᠷᠬᠡᠯᠡᠪᠡ Connected: ᠴᠥᠷᠬᠡᠯᠡᠪᠡ: Not Connected ᠴᠦᠷᠬᠡᠯᠡᠬᠡ ᠥᠬᠡᠢ (Limited) ( ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠬᠢᠵᠠᠭᠠᠷᠯᠠᠭᠳᠠᠪᠠ) ListItem Kylin NM ᠲᠣᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳᠡᠭᠡᠷ᠎ᠡ ᠪᠠᠭᠠᠵᠢ ᠲᠣᠬᠢᠷᠠᠭᠤᠯᠤᠨ᠎ᠠ ᠃ kylin network applet desktop message ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠰᠠᠨᠠᠭᠤᠯᠤᠮᠵᠢ ᠶᠢᠨ ᠮᠡᠳᠡᠭᠡ ᠃ MainWindow kylin-nm ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠪᠠᠭᠠᠵᠢ LAN 有线网络 ᠤᠲᠠᠰᠤᠲᠤ ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ WLAN 无线局域网 ᠤᠲᠠᠰᠤᠭᠤᠢ ᠬᠡᠰᠡᠭ ᠬᠡᠪᠴᠢᠶᠡᠨ᠎ᠦ᠌ ᠲᠣᠣᠷ Show MainWindow ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠪᠠᠭᠠᠵᠢ ᠵᠢ ᠨᠡᠬᠡᠬᠡᠬᠦ Settings 设置网络项 ᠲᠤᠬᠢᠷᠠᠭᠤᠯᠬᠤ Network Connectivity Detection ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠶᠢ ᠵᠠᠯᠭᠠᠵᠤ ᠪᠠᠶᠢᠴᠠᠭᠠᠨ ᠬᠡᠮᠵᠢᠨ᠎ᠡ Network tool ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠪᠠᠭᠠᠵᠢ Network Card ᠰᠦᠯᠵᠢᠶᠡᠨ ᠺᠠᠷᠲ Not connected to the network ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠴᠥᠷᠬᠡᠯᠡᠭᠡ ᠥᠬᠡᠢ MultipleDnsWidget DNS server(Drag to sort) DNS ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ ᠤ᠋ᠨ ᠦᠨᠳᠦᠷ ᠳᠡᠰ ᠤ᠋ᠨ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Click "+" to configure DNS "+" ᠢ᠋/ ᠵᠢ ᠳᠤᠪᠴᠢᠳᠠᠵᠤ᠂ DNS ᠢ᠋/ ᠵᠢ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠬᠤ Settings ᠲᠤᠬᠢᠷᠠᠭᠤᠯᠬᠤ NetDetail Kylin NM ᠲᠣᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳᠡᠭᠡᠷ᠎ᠡ ᠪᠠᠭᠠᠵᠢ ᠲᠣᠬᠢᠷᠠᠭᠤᠯᠤᠨ᠎ᠠ ᠃ kylin network desktop message ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠰᠠᠨᠠᠭᠤᠯᠤᠮᠵᠢ ᠵᠢᠨ ᠮᠡᠳᠡᠭᠡ Detail ᠨᠠᠷᠢᠨ ᠪᠠᠢᠳᠠᠯ IPv4 IPv4 IPv6 IPv6 Security ᠠᠮᠤᠷ ᠳᠦᠪᠰᠢᠨ start check IPv4 address conflict IPv4 ᠬᠠᠶᠢᠭ ᠤᠨ ᠮᠥᠷᠭᠥᠯᠳᠥᠭᠡᠨ ᠢ ᠡᠬᠢᠯᠡᠨ ᠪᠠᠶᠢᠴᠠᠭᠠᠵᠤ ᠡᠬᠢᠯᠡᠪᠡ ᠃ start check IPv6 address conflict IPv6 ᠬᠠᠶᠢᠭ ᠤᠨ ᠮᠥᠷᠭᠥᠯᠳᠥᠭᠡᠨ ᠢ ᠡᠬᠢᠯᠡᠨ ᠪᠠᠶᠢᠴᠠᠭᠠᠵᠤ ᠡᠬᠢᠯᠡᠪᠡ ᠃ Close 关闭 Config ᠦᠨᠳᠦᠰᠦᠨ ᠲᠣᠬᠢᠷᠠᠭᠤᠯᠤᠯᠲᠠ Confirm ᠲᠣᠭᠲᠠᠭᠠᠬᠤ Cancel ᠪᠣᠯᠢᠬᠤ Forget this network ᠲᠤᠰ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠮᠠᠷᠳᠠᠬᠤ Delete this network ᠲᠤᠰ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠬᠠᠰᠤᠬᠤ Add LAN Connect ᠤᠳᠠᠰᠤᠳᠤ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠨᠡᠮᠡᠬᠦ Connect Hidden WLAN ᠨᠢᠭᠤᠴᠠᠯᠠᠭᠰᠠᠨ WLAN ᠲᠤ᠌/ ᠳ᠋ᠤ᠌ ᠴᠦᠷᠬᠡᠯᠡᠬᠦ None ᠦᠬᠡᠢ Auto ᠳᠠᠭᠠᠯᠲᠠ ᠰᠢᠰᠲ᠋ᠧᠮ start check ipv4 address conflict IPv4 ᠬᠠᠶᠢᠭ ᠤ᠋ᠨ ᠮᠦᠷᠬᠦᠯᠳᠦᠬᠡᠨ ᠢ᠋ ᠪᠠᠢᠴᠠᠭᠠᠵᠤ ᠡᠬᠢᠯᠡᠪᠡ start check ipv6 address conflict IPv6 ᠬᠠᠶᠢᠭ ᠤ᠋ᠨ ᠮᠦᠷᠬᠦᠯᠳᠦᠬᠡᠨ ᠢ᠋ ᠪᠠᠢᠴᠠᠭᠠᠵᠤ ᠡᠬᠢᠯᠡᠪᠡ ipv4 address conflict! ipv4 ᠬᠠᠶᠢᠭ ᠮᠦᠷᠬᠦᠯᠳᠦᠬᠡᠨ ᠲᠠᠢ! ipv6 address conflict! ipv6 ᠬᠠᠶᠢᠭ ᠮᠦᠷᠬᠦᠯᠳᠦᠬᠡᠨ ᠲᠠᠢ! this wifi no support enterprise type ᠲᠤᠰ wifi ᠠᠵᠤ ᠠᠬᠤᠢᠯᠠᠯ ᠤ᠋ᠨ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠲᠦᠷᠦᠯ ᠢ᠋ ᠳᠡᠮᠵᠢᠬᠦ ᠦᠬᠡᠢ this wifi no support None type ᠲᠤᠰ wifi ᠬᠤᠭᠤᠰᠤᠨ ᠬᠡᠯᠪᠡᠷᠢ ᠵᠢ ᠳᠡᠮᠵᠢᠬᠦ ᠦᠬᠡᠢ this wifi no support WPA2 type ᠲᠤᠰ wifiWPA2 ᠳᠦᠷᠦᠯ ᠢ᠋ ᠳᠡᠮᠵᠢᠬᠦ ᠦᠬᠡᠢ this wifi no support WPA3 type ᠲᠤᠰ wifiWPA3 ᠳᠦᠷᠦᠯ ᠢ᠋ ᠳᠡᠮᠵᠢᠬᠦ ᠦᠬᠡᠢ SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form ᠹᠤᠤᠮ Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form ᠹᠤᠤᠮ Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network ᠲᠤᠰ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠴᠡᠬᠡᠵᠢᠯᠡᠬᠦ Security ᠠᠮᠤᠷ ᠳᠦᠪᠰᠢᠨ Password ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ EAP type EAP ᠠᠷᠭ᠎ᠠ Identity ᠨᠡᠷ᠎ᠡ ᠪᠤᠷᠤᠭᠤᠯᠤᠭᠰᠠᠨ ᠪᠡᠶ᠎ᠡ ᠵᠢᠨ ᠭᠠᠷᠤᠯ Domain ᠳ᠋ᠤᠮᠠᠢᠨ ᠄ CA certficate CA ᠦᠨᠡᠮᠯᠡᠯ no need for CA certificate CA ᠦᠨᠡᠮᠯᠡᠯ ᠬᠡᠷᠡᠭᠰᠡᠬᠦ ᠦᠬᠡᠢ User certificate ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠦᠨᠡᠮᠯᠡᠯ User private key ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ User key password ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠤ᠋ᠨ ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ Password options ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ ᠤ᠋ᠨ ᠰᠤᠩᠭᠤᠭᠳᠠᠬᠤᠨ Required ᠡᠷᠬᠡᠪᠰᠢ ᠳᠠᠭᠯᠠᠬᠤ Ineer authentication ᠳᠤᠳᠤᠭᠠᠳᠤ ᠬᠡᠷᠡᠴᠢᠯᠡᠯ Username ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠡᠷ᠎ᠡ Ask pwd each query ᠤᠳᠠᠭ᠎ᠠ ᠪᠦᠷᠢ ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ ᠢ᠋ ᠯᠠᠪᠯᠠᠬᠤ None ᠦᠬᠡᠢ WPA&WPA2 Personal WPA&WPA2 ᠬᠤᠪᠢ ᠬᠦᠮᠦᠨ WPA&WPA2 Enterprise WPA&WPA2 ᠠᠵᠤ ᠠᠬᠤᠢᠯᠠᠯ WPA3 Personal WPA3 ᠬᠥᠮᠥᠨ ᠃ Choose from file... ᠹᠠᠢᠯ ᠡᠴᠡ ᠰᠤᠩᠭᠤᠬᠤ··· Store passwords only for this user ᠵᠥᠪᠬᠡᠨ ᠲᠤᠰ ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠺᠣᠳ᠋ ᠢ᠋ ᠬᠠᠳᠠᠭᠠᠯᠠᠬᠤ Store password only for this user ᠵᠥᠪᠬᠡᠨ ᠲᠤᠰ ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠺᠣᠳ᠋ ᠢ᠋ ᠬᠠᠳᠠᠭᠠᠯᠠᠬᠤ Store passwords for all users ᠪᠦᠬᠦᠢᠯᠡ ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ ᠢ᠋ ᠬᠠᠳᠠᠭᠠᠯᠠᠬᠤ Store password for all users ᠪᠦᠬᠦᠢᠯᠡ ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ ᠢ᠋ ᠬᠠᠳᠠᠭᠠᠯᠠᠬᠤ Ask this password every time ᠤᠳᠠᠭ᠎ᠠ ᠪᠦᠷᠢ ᠲᠤᠰ ᠨᠢᠭᠤᠴᠠ ᠺᠣᠳ᠋ ᠢ᠋ ᠠᠰᠠᠭᠤᠨ ᠯᠠᠪᠯᠠᠬᠤ Ask password every time ᠤᠳᠠᠭ᠎ᠠ ᠪᠦᠷᠢ ᠠᠰᠠᠭᠤᠨ ᠯᠠᠪᠯᠠᠬᠤ Wifi password length less than 8 ᠸᠢᠹᠢ ᠨᠢᠭᠤᠴᠠ ᠨᠣᠮᠧᠷ ᠤᠨ ᠤᠷᠲᠤ ᠨᠢ 8 ᠡᠴᠡ ᠪᠠᠭ᠎ᠠ ᠃ TLS identity is empty TLS ᠨᠡᠷ᠎ᠡ ᠨᠢ ᠬᠣᠭᠣᠰᠣᠨ ᠃ CA cert filepath is invalid CA ᠦᠨᠡᠮᠯᠡᠯ ᠦᠨ ᠪᠢᠴᠢᠭ᠌ ᠮᠠᠲ᠋ᠧᠷᠢᠶᠠᠯ ᠤᠨ ᠠᠷᠭ᠎ᠠ ᠵᠠᠮ ᠬᠠᠤᠯᠢ ᠪᠤᠰᠤ ᠃ Client cert filepath is invalid ᠵᠣᠴᠢᠨ ᠡᠷᠦᠬᠡ ᠶᠢᠨ ᠦᠵᠦᠭᠦᠷ ᠦᠨ ᠦᠨᠡᠮᠯᠡᠯ ᠦᠨ ᠪᠢᠴᠢᠭ ᠮᠠᠲ᠋ᠧᠷᠢᠶᠠᠯ ᠤᠨ ᠠᠷᠭ᠎ᠠ ᠵᠠᠮ ᠬᠦᠴᠦᠨ ᠦᠭᠡᠶ ᠃ Client private key filepath is invalid ᠵᠣᠴᠢᠨ ᠡᠷᠦᠬᠡ ᠶᠢᠨ ᠬᠤᠪᠢ ᠶᠢᠨ ᠬᠥᠬᠢᠳᠡᠬᠦ ᠪᠢᠴᠢᠭ᠌ ᠮᠠᠲ᠋ᠧᠷᠢᠶᠠᠯ ᠤᠨ ᠠᠷᠭ᠎ᠠ ᠵᠠᠮ ᠬᠦᠴᠦᠨ ᠦᠭᠡᠢ ᠃ Client private key password is empty ᠵᠣᠴᠢᠨ ᠡᠷᠦᠬᠡ ᠶᠢᠨ ᠬᠤᠪᠢ ᠶᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠨᠣᠮᠧᠷ ᠨᠢ ᠬᠣᠭᠣᠰᠣᠨ ᠃ User name or user password is empty ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠶᠢᠨ ᠨᠡᠷ᠎ᠡ ᠪᠤᠶᠤ ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠶᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠨᠣᠮᠧᠷ ᠨᠢ ᠬᠣᠭᠣᠰᠣᠨ ᠃ No PAC file is selected PAC ᠪᠢᠴᠢᠭ᠌ ᠮᠠᠲ᠋ᠧᠷᠢᠶᠠᠯ ᠢ ᠰᠣᠩᠭᠣᠭᠰᠠᠨ ᠦᠭᠡᠢ ᠃ Choose a CA certificate CA ᠦᠨᠡᠮᠯᠡᠯ ᠢ᠋ ᠰᠤᠩᠭᠤᠬᠤ PAC Files ( *.pac) PAC ᠪᠢᠴᠢᠭ᠌ ᠮᠠᠲ᠋ᠧᠷᠢᠶᠠᠯ ( *.pac ) CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA ᠬᠡᠷᠡᠴᠢᠯᠡᠯ (*.pem *.der *.p12 *.crt *.cer *.pfx) PAC provisioning PAC ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Allow automatic PAC provisioning ᠠᠦ᠋ᠲ᠋ᠣ᠋ PAC ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ ᠵᠢ ᠵᠥᠪᠰᠢᠶᠡᠷᠡᠬᠦ PAC file PAC ᠹᠠᠢᠯ Anonymous ᠨᠡᠷ᠎ᠡ ᠪᠤᠷᠤᠭᠤᠯᠠᠵᠤ ᠨᠡᠪᠳᠡᠷᠡᠬᠦ Authenticated ᠭᠡᠷᠡᠴᠢᠯᠡᠬᠦ Both ᠬᠣᠶᠠᠭᠤᠯᠠ ᠵᠢ ᠠᠭᠤᠰᠤᠯᠴᠠᠭᠤᠯᠵᠤ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ CA Files ( *.pem *.der *.p12 *.crt *.cer *.pfx) CA ᠪᠢᠴᠢᠭ ᠮᠠᠲ᠋ᠧᠷᠢᠶᠠᠯ ( *.pem*.der.p12*.crt*.cer**.pfx) Choose a PAC file ᠨᠢᠭᠡ PAC ᠹᠠᠢᠯ ᠰᠣᠩᠭᠣᠬᠤ PAC Files (*.pac) PAC ᠹᠠᠢᠯ (*.pac) TabPage Current Device ᠣᠳᠣᠬᠠᠨ᠎ᠤ ᠲᠥᠬᠥᠭᠡᠷᠦᠮᠵᠢ Devices Closed! ᠳᠦᠬᠦᠬᠡᠷᠦᠮᠵᠢ ᠬᠠᠭᠠᠭᠳᠠᠪᠠ! Settings ᠲᠤᠬᠢᠷᠠᠭᠤᠯᠬᠤ Kylin NM ᠲᠣᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳᠡᠭᠡᠷ᠎ᠡ ᠪᠠᠭᠠᠵᠢ ᠲᠣᠬᠢᠷᠠᠭᠤᠯᠤᠨ᠎ᠠ ᠃ kylin network applet desktop message ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠰᠠᠨᠠᠭᠤᠯᠤᠮᠵᠢ ᠶᠢᠨ ᠮᠡᠳᠡᠭᠡ ᠃ connected ᠴᠦᠷᠬᠡᠯᠡᠪᠡ VpnPage Wired Device not carried 未插入网线 WarningDialog Unable to save modifications ᠵᠠᠰᠠᠪᠤᠷᠢ ᠣᠷᠣᠭᠤᠯᠬᠤ ᠶᠢᠨ ᠠᠷᠭ᠎ᠠ ᠦᠭᠡᠶ ᠃ Confirm ᠲᠣᠭᠲᠠᠭᠠᠬᠤ WiFiConfigDialog Dialog ᠶᠠᠷᠢᠯᠴᠠᠭ᠎ᠠ ᠃ WLAN Authentication WLAN ᠬᠡᠷᠡᠴᠢᠯᠡᠯ Input WLAN Information Please WLAN ᠰᠤᠷᠠᠭ ᠵᠠᠩᠬᠢ ᠵᠢ ᠤᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ WLAN ID: ᠷᠠᠳᠢᠣ᠋ ᠬᠡᠰᠡᠭ ᠭᠠᠵᠠᠷ ᠤᠨ ᠲᠣᠤᠷ ID WLAN Name: WLAN ᠨᠡᠷᠡᠢᠳᠦᠯ: Password: ᠨᠢᠭᠤᠴᠠ ᠨᠣᠮᠧᠷ ᠄ Cancl ᠦᠬᠡᠢᠰᠬᠡᠬᠦ Ok ᠵᠥᠪᠰᠢᠶᠡᠷᠡᠪᠡ WlanListItem Not connected ᠵᠠᠯᠭᠠᠭ᠎ᠠ ᠦᠭᠡᠢ Disconnect ᠴᠦᠷᠬᠡᠯᠡᠬᠡ ᠵᠢ ᠳᠠᠰᠤᠯᠬᠤ Connect ᠴᠦᠷᠬᠡᠯᠡᠬᠡ Forget ᠲᠤᠰ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠮᠠᠷᠳᠠᠬᠤ Property ᠬᠠᠷᠢᠶᠠᠳᠤ ᠴᠢᠨᠠᠷ Auto Connect ᠲᠤᠰ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠠᠦ᠋ᠲ᠋ᠤ᠋ ᠪᠡᠷ ᠵᠠᠯᠭᠠᠬᠤ WlanMoreItem More... 更多... Add Others... ᠪᠤᠰᠤᠳ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠵᠠᠯᠭᠠᠬᠤ··· WlanPage WLAN ᠤᠲᠠᠰᠤᠭᠤᠢ ᠬᠡᠰᠡᠭ ᠬᠡᠪᠴᠢᠶᠡᠨ᠎ᠦ᠌ ᠲᠣᠣᠷ No wireless network card detected ᠤᠳᠠᠰᠤ ᠦᠬᠡᠢ ᠨᠧᠲ ᠺᠠᠷᠲ᠎ᠢ ᠬᠢᠨᠠᠨ ᠬᠡᠮᠵᠢᠵᠤ ᠤᠯᠤᠭᠰᠠᠨ ᠦᠬᠡᠢ Activated WLAN ᠮᠢᠨᠤ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ Other WLAN ᠪᠤᠰᠤᠳ ᠰᠦᠯᠵᠢᠶ᠎ᠡ More... 更多... WLAN Connected Successfully ᠤᠳᠠᠰᠤ ᠦᠬᠡᠢ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠴᠦᠷᠬᠡᠯᠡᠪᠡ WLAN Disconnected Successfully ᠤᠳᠠᠰᠤ ᠦᠬᠡᠢ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠳᠠᠰᠤᠯᠪᠠ The routing end rejects the access of the device ᠵᠠᠮ ᠢᠶᠠᠷ ᠲᠥᠬᠥᠭᠡᠷᠦᠮᠵᠢ ᠶᠢᠨ ᠠᠶᠢᠯᠴᠢᠯᠠᠯᠲᠠ ᠶᠢ ᠲᠡᠪᠴᠢᠵᠡᠢ ᠃ The network access at the routing end is full ᠵᠠᠮ ᠤᠨ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠡᠴᠡ ᠠᠶᠢᠯᠴᠢᠯᠠᠯᠲᠠ ᠨᠢᠭᠡᠨᠲᠡ ᠳᠦᠭᠦᠷᠴᠡᠶ ᠃ usd set offline mode failed: USD ᠤᠲᠠᠰᠤᠨ ᠤ ᠵᠠᠭᠪᠤᠷ ᠲᠣᠬᠢᠷᠠᠭᠤᠯᠵᠤ ᠢᠯᠠᠭᠳᠠᠪᠠ ᠄ Connected: ᠴᠥᠷᠬᠡᠯᠡᠪᠡ: Not Connected ᠴᠦᠷᠬᠡᠯᠡᠬᠡ ᠥᠬᠡᠢ (Limited) ( ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠬᠢᠵᠠᠭᠠᠷᠯᠠᠭᠳᠠᠪᠠ) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm ᠴᠢ ᠯᠢᠨ show kylin-nm wifi page ᠴᠢ ᠯᠢᠨ nmwifi ᠨᠢᠭᠤᠷ᠎ᠢ᠋ ᠢᠯᠡᠷᠡᠭᠦᠯᠬᠦ show kylin-nm lan page ᠴᠢ ᠯᠢᠨ nm ᠬᠡᠰᠡᠭ ᠬᠡᠪᠴᠢᠶᠡᠨ᠎ᠦ᠌ ᠨᠧᠲ ᠨᠢᠭᠤᠷ᠎ᠢ᠋ ᠢᠯᠡᠷᠡᠭᠦᠯᠬᠦ kylin-nm/src/translations/kylin-nm_zh_CN.ts0000664000175000017500000021505415167651420017753 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type 网络配置文件类型 Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. 公用(推荐) 网络中的设备不可发现此电脑。一般情况下适用于公共场所中的网络,如机场或咖啡店等等。 Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. 专用 网络中的设备可发现此电脑。一般情况下适用于家庭或工作单位的网络,您认识并信任网络上的个人和设备。 Config firewall and security settings 配置防火墙和安全设置 ConnectivityPage Network connectivity detection 网络连通性检测 If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. 如访问 Internet 受限,请切换网络 IP 连通性检测方式后再试。 Public network (default) 公网(默认) Local area network (intranet) 局域网(内网) Confirm 确定 The network is connected and can access the Internet normally. 网络已连接,可正常访问 Internet 。 The network is connected and access to the Internet is restricted. 网络已连接,访问 Internet 受限。 Please enter the local area network (intranet) detection address 请输入局域网(内网)检测地址 Format error 格式错误 CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name 网络名称 IPv4Config IPv4 配置 Address IPv4 地址 Netmask 子网掩码 Default Gateway 默认网关 Connection name is empty or invalid 网络名称为空或无效 IPv4 address is empty or invalid Ipv4地址为空或非法 IPv4 netMask is empty or invalid IPv4子网掩码为空或无效 IPv4 gateway is empty or invalid IPv4网关为空或无效 Address conflict 地址冲突 Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) 自动 (DHCP) Manual 手动 Invalid address 无效的IP地址 Invalid subnet mask 无效的子网掩码 Required 必填 DetailPage Auto Connection 自动连接 SSID: SSID: Copied successfully! 复制成功! Copy all 复制全部 Please input SSID: 请输入 SSID: Protocol: 协议: Security Type: 安全类型: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv6: 本地链接 IPv6 地址: IPv4: IPv4 地址: IPv4 DNS: IPv4 DNS 服务器: Mac: 物理地址: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings DNS 服务器高级配置 Tactic 策略 Timeout 超时时间 Retry Count 重试次数 order 顺序 rotate 随机 concurrency 并发 s times Close 关闭 Cancel 取消 Confirm 确定 EnterpriseWlanDialog Connect Enterprise WLAN 连接企业网 Close 关闭 Wi-Fi network requires authentication Wi-Fi 网络要求认证 Access to Wi-Fi network " 访问 Wi-Fi 网络 " requires a password or encryption key. 需要密码或加密密钥。 Cancel 取消 Connect 连接 FirewallDialog Allow your computer to be discovered by other computers and devices on this network? 是否允许你的电脑被此网络上的其他电脑和设备发现? It is recommended that you enable this feature on your home and work networks rather than public networks. 建议你在家庭和工作网络上而非公共网络上启用此功能。 Yse No Allow other devices on this network to discover this computer? 是否允许此网络上的其他设备发现这台电脑? It is not recommended to enable this feature on public networks 不建议在公共网络上开启此功能 Not allowed (recommended) 不允许(推荐) Allowed 允许 Ipv4Page IPv4Config IPv4 配置 Address 地址 Netmask 子网掩码 Default Gateway 默认网关 Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) 自动 Manual 手动 IPv4 address is empty or invalid Ipv4地址为空或非法 IPv4 netMask is empty or invalid IPv4 gateway is empty or invalid Invalid address 无效的IP地址 Invalid subnet mask 无效的子网掩码 Required 必填 Address conflict 地址冲突 Ipv6Page IPv6Config IPv6 配置 Address 地址 Subnet prefix Length 子网前缀长度 Default Gateway 默认网关 Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) 自动 Manual 手动 Required 必填 Invalid address 无效的IP地址 Invalid gateway 无效的网关地址 IPv6 address is empty or invalid IPv6地址为空或无效 IPv6 prefix length is empty or invalid IPv6子网前缀长度为空或无效 Address conflict 地址冲突 JoinHiddenWiFiPage Please enter the network information 请输入您想要加入的网络信息 Network name(SSID) 网络名 (SSID) Remember the Network 记住该网络 Show Network List 显示网络列表 Cancel 取消 Join 加入 Required 必填 Find and Join WLAN 查找并加入无线局域网络 LanListItem Not connected 未连接 Wired Device not carried 未插入网线 Disconnect 断开 Connect 连接 Property 属性 Delete 删除此网络 LanPage No ethernet device avaliable 未检测到有线设备 LAN 有线网络 conflict, unable to connect to the network normally! 冲突,无法正常连接到网络! No wired network card detected Activated LAN 我的网络 Inactivated LAN 其他网络 Connected, no internet access 已连接,无互联网 Connected, restricting access 已连接,网络受限 No internet access. Please click Network Check to specific reasons. 无法访问互联网。请点击网络检测,查看具体原因。 Network Check 网络检测 LAN Disconnected Successfully 有线网络已断开 Wired Device not carried 未插入网线 LAN Connected Successfully 有线网络已连接 Connected: 已连接: Not Connected 未连接 (Limited) (网络受限) ListItem Kylin NM 网络设置工具 kylin network applet desktop message 网络提示消息 MainWindow kylin-nm 网络工具 LAN 有线网络 有线网络 WLAN 无线局域网 无线局域网 Show MainWindow 打开网络工具 Settings 设置网络项 设置网络项 Network Connectivity Detection 网络连通性检测 Network tool 网络工具 Network Card 网卡 Not connected to the network 未连接网络 MultipleDnsWidget DNS server(Drag to sort) DNS 服务器高级配置 Click "+" to configure DNS 点击 “+”配置 DNS Settings 高级设置 NetDetail Kylin NM 网络设置工具 kylin network desktop message 网络提示消息 Detail 详情 IPv4 IPv4 IPv6 IPv6 Security 安全 start check IPv4 address conflict 开始检测 IPv4 地址冲突 start check IPv6 address conflict 开始检测 IPv6 地址冲突 Close 关闭 Config 配置 Confirm 确定 Cancel 取消 Forget this network 忘记此网络 Delete this network 删除此网络 Add LAN Connect 添加有线网络 Connect Hidden WLAN 连接到隐藏 WLAN None Auto 自动 start check ipv4 address conflict 开始检测 ipv4 地址冲突 start check ipv6 address conflict 开始检测 ipv6 地址冲突 ipv4 address conflict! ipv4地址冲突! ipv6 address conflict! ipv6地址冲突! this wifi no support enterprise type 此 wifi 不支持企业网类型 this wifi no support None type 此 wifi 不支持空类型 this wifi no support WPA2 type 此 wifi 不支持 WPA2 类型 this wifi no support WPA3 type 此 wifi 不支持 WPA3 类型 SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network 记住该网络 Security 安全性 Password 密钥 EAP type EAP 方法 Identity 匿名身份 Domain CA certficate CA 证书 no need for CA certificate 不需要 CA 证书 User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Password options 密码选项 Required 必填 Ineer authentication 内部认证 Username 用户名 Ask pwd each query 每次询问密码 None WPA&WPA2 Personal WPA&WPA2 个人 WPA&WPA2 Enterprise WPA&WPA2 企业 WPA3 Personal WPA3 个人 Choose from file... 从文件选择... Store passwords only for this user 仅为该用户存储密码 Store password only for this user 仅为该用户存储密码 Store passwords for all users 存储所有用户的密码 Store password for all users 存储所有用户的密码 Ask this password every time 每次询问这个密码 Ask password every time 每次询问这个密码 Wifi password length less than 8 wifi密钥长度低于八位 TLS identity is empty TLS匿名身份为空 CA cert filepath is invalid CA证书文件路径非法 Client cert filepath is invalid 用户证书文件路径无效 Client private key filepath is invalid 用户私钥文件路径无效 Client private key password is empty 用户密钥密码为空 User name or user password is empty 用户名或密钥为空 No PAC file is selected 未选择PAC文件 Choose a CA certificate 选择一个 CA 证书 PAC Files ( *.pac) CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) PAC provisioning PAC 配置 Allow automatic PAC provisioning 允许自动 PAC 配置 PAC file PAC 文件 Anonymous 匿名 Authenticated 已认证 Both 两者兼用 CA Files ( *.pem *.der *.p12 *.crt *.cer *.pfx) Choose a PAC file 选择一个 PAC 文件 PAC Files (*.pac) PAC 文件(*.pac) TabPage Current Device 当前网卡 Devices Closed! 设备关闭! Settings 网络设置 Kylin NM 网络设置工具 kylin network applet desktop message 网络提示消息 connected VpnPage Wired Device not carried 未插入网线 WarningDialog Unable to save modifications 无法保存修改 Confirm 确定 WiFiConfigDialog Dialog WLAN Authentication Input WLAN Information Please WLAN ID: WLAN Name: Password: Cancl Ok WlanListItem Not connected 未连接 Disconnect 断开 Connect 连接 Forget 忘记此网络 Property 属性 Auto Connect 自动加入该网络 WlanMoreItem More... 更多... Add Others... 加入其他网络... WlanPage WLAN 无线局域网 No wireless network card detected 未检测到无线网卡 Activated WLAN 我的网络 Other WLAN 其他网络 More... 更多... WLAN Connected Successfully 无线网络已连接 WLAN Disconnected Successfully 无线网络已断开 The routing end rejects the access of the device 网络拒绝加入,连接失败 The network access at the routing end is full 网络接入已满 usd set offline mode failed: Connected: 已连接: Not Connected 未连接 (Limited) (网络受限) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm show kylin-nm wifi page show kylin-nm lan page kylin-nm/src/translations/kylin-nm_zh_Hant.ts0000664000175000017500000021455615167651420020353 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type 網路配置檔類型 Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. 公用(推薦) 網路中的設備不可發現此電腦。 一般情況下適用於公共場所中的網路,如機場或咖啡店等等。 Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. 專用網路中的設備可發現此電腦。 一般情況下適用於家庭或工作單位的網路,您認識並信任網路上的個人和設備。 Config firewall and security settings 配置防火牆和安全設置 ConnectivityPage Network connectivity detection 網路連通性檢測 If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. 如訪問 Internet 受限,請切換網路 IP 連通性檢測方式後再試。 Public network (default) 公網(預設) Local area network (intranet) 區域網(內網) Confirm 確定 The network is connected and can access the Internet normally. 網路已連接,可正常存取 Internet 。 The network is connected and access to the Internet is restricted. 網路已連接,訪問 Internet 受限。 Please enter the local area network (intranet) detection address 請輸入局域網(內網)檢測位址 Format error 格式錯誤 CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name 網路名稱 IPv4Config IPv4 配置 Address IPv4 位址 Netmask 子網掩碼 Default Gateway 默認閘道 Connection name is empty or invalid 連接名稱為空或無效 IPv4 address is empty or invalid Ipv4位址為空或非法 IPv4 netMask is empty or invalid IPv4 netMask 為空或無效 IPv4 gateway is empty or invalid IPv4 閘道為空或無效 Address conflict 位址衝突 Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) 自動 (DHCP) Manual 手動 Invalid address 無效的IP位址 Invalid subnet mask 無效的子網掩碼 Required 必填 DetailPage Auto Connection 自動連接 SSID: SSID: Copied successfully! 複製成功! Copy all 複製全部 Please input SSID: 請輸入 SSID: Protocol: 協定: Security Type: 安全類型: Hz: 網路頻帶: Chan: 網路通道: BandWidth: 頻寬: IPv6: 本地連結 IPv6 位址: IPv4: IPv4 位址: IPv4 DNS: IPv4 DNS 伺服器: Mac: 物理位址: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings DNS 伺服器高級配置 Tactic 策略 Timeout 超時時間 Retry Count 重試次數 order 順序 rotate 隨機 concurrency 併發 s times Close 關閉 Cancel 取消 Confirm 確定 EnterpriseWlanDialog Connect Enterprise WLAN 连接企业网 Close 关闭 Wi-Fi network requires authentication Wi-Fi 網路要求認證 Access to Wi-Fi network " 訪問Wi-Fi網路 " requires a password or encryption key. 需要密碼或加密金鑰。 Cancel 取消 Connect 連接 FirewallDialog Allow your computer to be discovered by other computers and devices on this network? 是否允许你的电脑被此网络上的其他电脑和设备发现? It is recommended that you enable this feature on your home and work networks rather than public networks. 建议你在家庭和工作网络上而非公共网络上启用此功能。 Yse No Allow other devices on this network to discover this computer? 是否允許此網路上的其他設備發現這台電腦? It is not recommended to enable this feature on public networks 不建議在公共網路上開啟此功能 Not allowed (recommended) 不允許(推薦) Allowed 允許 Ipv4Page IPv4Config IPv4 配置 Address 位址 Netmask 子網掩碼 Default Gateway 默認閘道 Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) 自動 Manual 手動 IPv4 address is empty or invalid Ipv4位址為空或非法 IPv4 netMask is empty or invalid IPv4 netMask 為空或無效 IPv4 gateway is empty or invalid IPv4 閘道為空或無效 Invalid address 無效的IP位址 Invalid subnet mask 無效的子網掩碼 Required 必填 Address conflict 位址衝突 Ipv6Page IPv6Config IPv6 配置 Address 位址 Subnet prefix Length 子網前綴長度 Default Gateway 默認閘道 Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) 自動 Manual 手動 Required 必填 Invalid address 無效的IP位址 Invalid gateway 無效的閘道位址 IPv6 address is empty or invalid IPv6 位址為空或無效 IPv6 prefix length is empty or invalid IPv6 前置綴長度為空或無效 Address conflict 位址衝突 JoinHiddenWiFiPage Please enter the network information 請輸入您想要加入的網路資訊 Network name(SSID) 網路名稱 (SSID) Remember the Network 记住该网络 Show Network List 顯示網路清單 Cancel 取消 Join 加入 Required 必填 Find and Join WLAN 查找並加入無線局域網路 LanListItem Not connected 未連接 Wired Device not carried 未插入網線 Disconnect 斷開 Connect 連接 Property 屬性 Delete 刪除此網路 LanPage No ethernet device avaliable 未檢測到有線設備 LAN 有線網路 conflict, unable to connect to the network normally! 衝突,無法正常連接到網路! No wired network card detected 未檢測到有線網卡 Activated LAN 我的網路 Inactivated LAN 其他網路 Connected, restricting access 連接,限制訪問 No internet access. Please click Network Check to specific reasons. 無法訪問互聯網。 請點擊網路檢查以瞭解具體原因。 Network Check 網路檢查 LAN Disconnected Successfully 有线网络已断开 Wired Device not carried 未插入網線 LAN Connected Successfully 有线网络已连接 Connected: 已連線: Not Connected 未連接 (Limited) (網路受限) ListItem Kylin NM 網路設置工具 kylin network applet desktop message 網路提示消息 MainWindow kylin-nm 網路工具 LAN 有线网络 有線網路 WLAN 无线局域网 無線局域網 Show MainWindow 打开网络工具 Settings 设置网络项 設置網路項 Network Connectivity Detection 網路連通性檢測 Network tool 網路工具 Network Card 網卡 Not connected to the network 未連接網路 MultipleDnsWidget DNS server(Drag to sort) DNS 伺服器高級配置 Click "+" to configure DNS 點擊 「+」配置 DNS Settings 高級設置 NetDetail Kylin NM 網路設置工具 kylin network desktop message 網路提示消息 Detail 詳情 IPv4 IPv4 IPv6 IPv6 Security 安全 start check IPv4 address conflict 開始檢查 IPv4 位址衝突 start check IPv6 address conflict 開始檢查 IPv6 位址衝突 Close 关闭 Config 配置 Confirm 確定 Cancel 取消 Forget this network 忘記此網路 Delete this network 刪除此網路 Add LAN Connect 添加有線網路 Connect Hidden WLAN 連接到隱藏 WLAN None Auto 自動 start check ipv4 address conflict 开始检测 ipv4 地址冲突 start check ipv6 address conflict 开始检测 ipv6 地址冲突 ipv4 address conflict! ipv4地址冲突! ipv6 address conflict! ipv6地址冲突! this wifi no support enterprise type 此 wifi 不支援企業網類型 this wifi no support None type 此 wifi 不支援空類型 this wifi no support WPA2 type 此 wifi 不支援 WPA2 類型 this wifi no support WPA3 type 此 wifi 不支援 WPA3 類型 SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network 記住該網路 Security 安全性 Password 金鑰 EAP type EAP 方法 Identity 匿名身份 Domain CA certficate CA 證書 no need for CA certificate 不需要 CA 證書 User certificate 用戶證書 User private key 使用者私鑰 User key password 用戶金鑰密碼 Password options 密碼選項 Required 必填 Ineer authentication 內部認證 Username 使用者名 Ask pwd each query 每次詢問密碼 None WPA&WPA2 Personal WPA&WPA2 個人 WPA&WPA2 Enterprise WPA&WPA2 企業 WPA3 Personal WPA3 個人 Choose from file... 從檔案選擇... Store passwords only for this user 僅為該使用者存儲密碼 Store password only for this user 僅為該使用者存儲密碼 Store passwords for all users 存儲所有用戶的密碼 Store password for all users 存儲所有用戶的密碼 Ask this password every time 每次詢問這個密碼 Ask password every time 每次詢問這個密碼 Wifi password length less than 8 Wifi密碼長度小於8 TLS identity is empty TLS匿名身份為空 CA cert filepath is invalid CA證書檔路徑非法 Client cert filepath is invalid 用戶端證書檔路徑無效 Client private key filepath is invalid 用戶端私鑰檔案路徑無效 Client private key password is empty 用戶端私鑰密碼為空 User name or user password is empty 使用者名或用戶密碼為空 No PAC file is selected 未選擇 PAC 檔 Choose a CA certificate 選擇一個 CA 證書 PAC Files ( *.pac) PAC 檔案 ( *.pac) CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) PAC provisioning PAC 配置 Allow automatic PAC provisioning 允許自動 PAC 配置 PAC file PAC 檔 Anonymous 匿名 Authenticated 已認證 Both 兩者兼用 CA Files ( *.pem *.der *.p12 *.crt *.cer *.pfx) CA 檔 ( *.pem *.der *.p12 *.crt *.cer *.pfx) Choose a PAC file 選擇一個 PAC 檔 PAC Files (*.pac) PAC 文件(*.pac) TabPage Current Device 當前網卡 Devices Closed! 設備關閉! Settings 網路設置 Kylin NM 網路設置工具 kylin network applet desktop message 網路提示消息 connected 連接 VpnPage Wired Device not carried 未插入网线 WarningDialog Unable to save modifications 無法儲存修改 Confirm 確定 WiFiConfigDialog Dialog 對話 WLAN Authentication WLAN 身份驗證 Input WLAN Information Please 請輸入 WLAN 資訊 WLAN ID: 無線區域網 ID: WLAN Name: WLAN名稱: Password: 密碼: Cancl 坎克爾 Ok 還行 WlanListItem Not connected 未連接 Disconnect 斷開 Connect 連接 Forget 忘記此網路 Property 屬性 Auto Connect 自動加入該網路 WlanMoreItem More... 更多... Add Others... 加入其他網路... WlanPage WLAN 無線局域網 No wireless network card detected 未檢測到無線網卡 Activated WLAN 我的網路 Other WLAN 其他網路 More... 更多... WLAN Connected Successfully 無線網路已連接 WLAN Disconnected Successfully 無線網路已斷開 The routing end rejects the access of the device 路由端拒絕設備的訪問 The network access at the routing end is full 路由端網路訪問已滿 usd set offline mode failed: USD 設定離線模式失敗: Connected: 已連線: Not Connected 未連接 (Limited) (网络受限) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm 麒麟 show kylin-nm wifi page 顯示麒麟-NM WiFi頁面 show kylin-nm lan page 顯示 kylin-nm 局域網頁面 kylin-nm/src/translations/kylin-nm_ky.ts0000664000175000017500000022535015167651420017375 0ustar fengfeng ConfForm Manual 手动 Cancel 取消 kylin-nm 网络工具 kylin network applet desktop message 网络提示消息 Will check the IP address conflict 正在检测ip地址冲突 IPv4 address conflict, Please change IP ip地址冲突,请更改ip IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} ConfigPage Network profile type تور تۉزۉلمۅ ۅجۅت تۉرۉ Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. توردوعۇ جالپى ئشتەتىلە تۇرعان (كەڭەش) زاپجاستار بۇل كومپىيۇتەردى بايقىيالمايدۇ. اداتتاعىچا جاساپ ايتقاندا، ال ، جالپى ئشتەتىلە تۇرعان ۇچۇرلار تورۇنا شاي گەلەت مىسالى، اەروپورت كۅرۉنۉشتۅرۉ قافە قاتارلۇۇلار. Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. توردوعۇ اتايىن زاپجاستار بۇل كومپىيۇتەردى بايقىيالايدۇ. دەمەيدە توردوعۇ سىز تۉشۉنۅتۇرعان جانا ىشەنەتۇرعان جەكە جانا زاپجاستار، ۉي بۉلۅۅ كۅرۉنۉشتۅرۉ قىزمات تورۇنا شاي گەلەت . Config firewall and security settings وتتام جانا قووپسۇزدۇق تەڭشەگىن سەپتەش ConnectivityPage Network connectivity detection تور جالعانىشتى تەكشەرىش If access to the Internet is restricted, please switch the network IP connectivity detection method and try again. ەگەر تور عو كىرۉۉ چەكتەمەگە ۇچۇراسا، تور IP جالعانىشتى تەكشەرىش ىڭعايىن الماشتىرىڭ، اندان قايرا سىناڭ. Public network (default) جالپى ئشتەتىلە تۇرعان تور (ويۇنداقى ) Local area network (intranet) تار گۅۅلۅمدۉ تور (intranet) Confirm البەتتە. The network is connected and can access the Internet normally. تور ۇلاندى، ئنتىرنەت تور ىنى نورماال زىيارات جاساعالى بولوت . The network is connected and access to the Internet is restricted. تور ۇلاندى، ئنتىرنەت تور ىغا بولعون زىيارات چەكتەمەگە ۇچۇرادى. Please enter the local area network (intranet) detection address تار گۅۅلۅمدۉ تور (intranet) تەكشەرىش دايىن وردۇن كىرگىزىڭ Format error فورمات قاتالىعى CopyButton Copied successfully 复制成功 Copied successfully! 复制成功! Copy all 复制全部 CreatNetPage Connection Name تور ناامى IPv4Config IPv4 اتقارماق بۇيرۇعۇ Address دايىن وردۇ Netmask بۅلۉمچۅ تور جاشىرىن نومۇرۇ Default Gateway العاچىنداعى تور ۅتكۅلۉ Connection name is empty or invalid IPv4 address is empty or invalid IPv4 netMask is empty or invalid IPv4 gateway is empty or invalid Address conflict توقۇنۇشتۇ بىر تاراپ قىلۇۇ جاسوو ،اتقارۇۇ Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) اپتوماتتىك(DHCP) Manual قولدونمو Invalid address ەسەپ ەمەس IPدايىن وردۇ Invalid subnet mask ەسەپ ەمەس بۅلۉمچۅ تور جاشىرىن نومۇرۇ Required زارىل DetailPage Auto Connection اپتوماتتىك ۇلوو SSID: Copied successfully! جەڭىشتۉۉ گۅچۉرۉلگۅن! Copy all باردىعىن گۅچۉرۉش Please input SSID: SSID نى كىرگىزىڭ: Protocol: گەلىشىم : Security Type: قووپسۇزدۇق تۉرۉ: Hz: تور جىشتىق القاعى : Chan: تور جولۇ: BandWidth: كەڭ قۇر: IPv6: IPv4: IPv4 DNS: Mac: فىزىكالىق ادىرەس: DlgHideWifi Cancel 取消 Connect 连接 None DlgHideWifiEapFast Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPeap Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapPwd Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTTLS Domain Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiEapTls Identity 匿名身份 Domain User certificate 用户证书 User private key 用户私钥 User key password 用户密钥密码 Cancel 取消 Connect 连接 None DlgHideWifiLeap Username 用户名 Password 密钥 Cancel 取消 Connect 连接 None DlgHideWifiWep Cancel 取消 Connect 连接 None DlgHideWifiWpa Password 密钥 Cancel 取消 Connect 连接 None DnsSettingWidget DNS Server Advanced Settings DNS سان قاينارى جوعورۇ چەكتۉۉ تەڭشەگى Tactic ىقما Timeout ۇباقىت ەۋگەنىي Retry Count قايرا سانوو order قاتار تارتىبى rotate بۇرمالوو concurrency جانداش تارقاتۇۇ s times دوور Close جابۇۇ Cancel ارعادان قالتىرىش Confirm البەتتە. EnterpriseWlanDialog Connect Enterprise WLAN 连接企业网 Close 关闭 Wi-Fi network requires authentication Wi-Fi تورۇ اتۇۇلدۇق دالىلدۅۅگۅ اجات Access to Wi-Fi network " Wi-Fi تورۇنا ۇلوو " requires a password or encryption key. جاشىرۇۇن نومۇر كۅرۉنۉشتۅرۉ سىيفىرلاشتىرىلعان اچقىچ كەرەك. Cancel ارعادان قالتىرىش Connect ۇلانۇۇ FirewallDialog Allow your computer to be discovered by other computers and devices on this network? 是否允许你的电脑被此网络上的其他电脑和设备发现? It is recommended that you enable this feature on your home and work networks rather than public networks. 建议你在家庭和工作网络上而非公共网络上启用此功能。 Yse No Allow other devices on this network to discover this computer? بۇلل توردوعۇ باشقا جابدۇۇلار. بۇلل كومپىيۇتەردى اچىلىش. جول قويوبۇ؟ It is not recommended to enable this feature on public networks جالپى ئشتەتىلە تۇرعان توردو بۇل قۇرباتىن قوزعوتۇۇ كەڭەش قىلىنبايت Not allowed (recommended) جول قويۇلبايت (كەڭەش جاسالات) Allowed جول قويۇلات Ipv4Page IPv4Config IPv4 اتقارماق بۇيرۇعۇ Address دايىن وردۇ Netmask بۅلۉمچۅ تور جاشىرىن نومۇرۇ Default Gateway العاچىنداعى تور ۅتكۅلۉ Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) اپتوماتتىك(DHCP) Manual قولدونمو IPv4 address is empty or invalid IPv4 netMask is empty or invalid IPv4 gateway is empty or invalid Invalid address ەسەپ ەمەس IPدايىن وردۇ Invalid subnet mask ەسەپ ەمەس بۅلۉمچۅ تور جاشىرىن نومۇرۇ Required زارىل Address conflict توقۇنۇشتۇ بىر تاراپ قىلۇۇ جاسوو ،اتقارۇۇ Ipv6Page IPv6Config IPv6 اتقارماق بۇيرۇعۇ Address دايىن وردۇ Subnet prefix Length بۅلۉمچۅ تور الدى قوشۇمچا ۇزۇندۇق Default Gateway العاچىنداعى تور ۅتكۅلۉ Prefs DNS 首选 DNS Alternative DNS 备选 DNS Auto(DHCP) اپتوماتتىك(DHCP) Manual قولدونمو Required زارىل Invalid address ەسەپ ەمەس IPدايىن وردۇ Invalid gateway ەسەپ ەمەس تور ۅتكۅلۉ دايىن وردۇ IPv6 address is empty or invalid IPv6 prefix length is empty or invalid Address conflict توقۇنۇشتۇ بىر تاراپ قىلۇۇ جاسوو ،اتقارۇۇ JoinHiddenWiFiPage Please enter the network information تور ۇچۇردۇ كىرگىزىڭ Network name(SSID) تور ناامى (SSID) Remember the Network 记住该网络 Show Network List تور تىزىمدىگىن كۅرسۅتۉۉ Cancel ارعادان قالتىرىش Join قوشۇلۇۇ Required زارىل Find and Join WLAN WLAN نى تابۇۇ جانا قوشۇۇ LanListItem Not connected ۇلانباعان Wired Device not carried تور سىمى چېتىلمىغان Disconnect ۇلانۇۇسۇن ۉزۉپ اتۇۇ Connect ۇلانۇۇ Property قاسىيەتىن Delete ۅچۉر LanPage No ethernet device avaliable LAN conflict, unable to connect to the network normally! توقۇنۇسۇ، تورعو نورماال ۇلاعالى بولبودۇ! No wired network card detected Activated LAN وق Inactivated LAN اقتىۋدەشتىرىلگەن ەمەس. Connected, restricting access No internet access. Please click Network Check to specific reasons. Network Check LAN Disconnected Successfully 有线网络已断开 Wired Device not carried تور سىمى چېتىلمىغان LAN Connected Successfully 有线网络已连接 Connected: شىلتەمەلەر: Not Connected ۇلانبادى (Limited) ( چەكتەلگەن) ListItem Kylin NM kylin network applet desktop message 0 تور قۇرالى ۇچۇر جولجورۇعۇ MainWindow kylin-nm kylin-تور قۇرالى LAN 有线网络 WLAN 无线局域网 تار گۅۅلۅمدۉ سەمىز تور Show MainWindow 打开网络工具 Settings 设置网络项 تور تەڭشەگى Network Connectivity Detection تور جالعانىشتى تەكشەرىش Network tool تور قۇرالى Network Card تور كارتوچكاسى Not connected to the network تورعو ۇلانباعان MultipleDnsWidget DNS server(Drag to sort) DNS سان قاينارى ( سۉيرۅپ تارتىپ بويۇنچا تىزىلدى) Click "+" to configure DNS + نى چەگىپ DNS نى بەزەڭ Settings تور تەڭشەگى NetDetail Kylin NM kylin network desktop message تور ەسكەرتمە ۇچۇرۇ Detail ىچكەلەي ، قۇنت قويۇپ مازمۇنۇ IPv4 IPv6 Security قووپسۇزدۇق start check IPv4 address conflict start check IPv6 address conflict Close 关闭 Config نەگىزگى تەڭشەك Confirm البەتتە. Cancel ارعادان قالتىرىش Forget this network بۇل توردۇ ۇنتۇپ ۇياتسىز. Delete this network بۇل توردۇ ۅچۉرۉۉ Add LAN Connect LAN جالعانىشتى قوشۇۇ Connect Hidden WLAN جاشىرىن WLAN عا ۇلوو None جوق Auto اپتوماتتىك start check ipv4 address conflict 开始检测 ipv4 地址冲突 start check ipv6 address conflict 开始检测 ipv6 地址冲突 ipv4 address conflict! ipv4地址冲突! ipv6 address conflict! ipv6地址冲突! this wifi no support enterprise type بۇل سەمىز تور كەرحانا تور اداتتا. قولدوبويت this wifi no support None type بۇسىمسىز تور كۅڭدۅي كىكستارتەر قولدوبويت this wifi no support WPA2 type بۇل سەمىز تور WPA2 اداتتا. قولدوبويت this wifi no support WPA3 type بۇل سەمىز تور WPA3 اداتتا. قولدوبويت SSID: SSID: Protocol: 协议: Hz: 网络频带: Chan: 网络通道: BandWidth: 带宽: IPv4: IPv4地址: IPv4 DNS: IPv4 DNS服务器: IPv6: 本地链接IPv6地址: Mac: 物理地址: OldMainWindow kylin-nm 网络工具 Show MainWindow 打开网络工具 Not connected 未连接 OneConnForm Form تۉر Connect 连接 Disconnect 断开 Cancel 取消 Forget 忘记此网络 None OneLancForm Form تۉر Connect 连接 Disconnect 断开 Cancel 取消 Not connected 未连接 SecurityPage Remember the Network ۇشۇل توردۇ دىلدە ساقتوو Security قووپسۇزدۇق Password جاشىرۇۇن نومۇردۇ ۅزگۅرتۉش EAP type EAP تۉرۉ Identity كۉبۅلۉك Domain تور ناامى CA certficate CA كەنەشكە no need for CA certificate CA كەنشكەسىنىن تالابى جوق User certificate ىشتەتۉۉچۉ كەنىشكەسى User private key ىشتەتۉۉچۉ جەكەلىك اچقىچ User key password ىشتەتۉۉچۉ اچقىچ پارولۇ Password options جاشىرۇۇن نومۇر تاندالماسى Required زارىل Ineer authentication ىچكى بۅلۅگۉن دالىلدۅ Username كەرەكتۅۅچۉ ناامى Ask pwd each query ار بىر ىرەت سىرلۇۇ نومۇردۇ سۇروو None جوق WPA&WPA2 Personal WPA&WPA2 جەكەلىك WPA&WPA2 Enterprise WPA&WPA2 كەرحانا WPA3 Personal WPA3 جەكەلىك Choose from file... ۅجۅتتۉن تانداش ... Store passwords only for this user جالاڭ عانا بۇل ىشتەتكۉۉچۉنۉن جاشىرۇۇن نومۇرۇن ساقتايت Store password only for this user جالاڭ عانا بۇل ىشتەتكۉۉچۉنۉن جاشىرۇۇن نومۇرۇن ساقتوو Store passwords for all users باردىق ىشتەتكۉۉچۉنۉن جاشىرۇۇن نومۇرۇن ساقتوو Store password for all users باردىق ىشتەتكۉۉچۉنۉن جاشىرۇۇن نومۇرۇن ساقتوو Ask this password every time ار بىر ىرەت بۇل جاشىرۇۇن نومۇردۇ سۇروو Ask password every time ار بىر ىرەت جاشىرۇۇن نومۇر سۇروو Wifi password length less than 8 TLS identity is empty CA cert filepath is invalid Client cert filepath is invalid Client private key filepath is invalid Client private key password is empty User name or user password is empty No PAC file is selected Choose a CA certificate CA كەنىشكەسى تانداش PAC Files ( *.pac) CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) PAC provisioning PAC مەنەن قامدوو Allow automatic PAC provisioning PAC نى اپتوماتتىك قوشۇشقا جول قويوت PAC file PAC ۅجۅتۉۉ Anonymous اتى جوق Authenticated راستلىق دالىلدۅ Both ار بىر ەكۅۅ CA Files ( *.pem *.der *.p12 *.crt *.cer *.pfx) Choose a PAC file PAC مەنەن قامدوو PAC Files (*.pac) PAC 文件(*.pac) TabPage Current Device گەزەكتەكى تور كارتوچكا Devices Closed! زاپجاستار تاقالدى! Settings تور تەڭشەگى Kylin NM kylin network applet desktop message 0 تور قۇرالى ۇچۇر جولجورۇعۇ connected جالعانعان VpnPage Wired Device not carried 未插入网线 WarningDialog Unable to save modifications Confirm البەتتە. WiFiConfigDialog Dialog دىيالوگ WLAN Authentication Input WLAN Information Please WLAN ID: WLAN Name: Password: Cancl Ok ماقۇل WlanListItem Not connected ۇلانباعان Disconnect ۇلانۇۇسۇن ۉزۉپ اتۇۇ Connect ۇلانۇۇ Forget بۇل توردۇ ۇنۇتۇلۇۇ Property قاسىيەتىن Auto Connect بۇل تورعو اپتوماتتىك ۇلوو WlanMoreItem More... 更多... Add Others... باشقا تورعو قوشۇلۇۇ... WlanPage WLAN تار گۅۅلۅمدۉ سەمىز تور No wireless network card detected سەمىز تور كارتوچكاسى بايقالبادى Activated WLAN قوزعوتۇلدۇ Other WLAN باشقا More... 更多... WLAN Connected Successfully سەمىز تور ۇلانۇۇ جەڭىشتۉۉ بولدۇ WLAN Disconnected Successfully سەمىز تور ۇلانۇۇسۇ جەڭىشتۉۉ ۉزۉلدۉ The routing end rejects the access of the device The network access at the routing end is full usd set offline mode failed: Connected: شىلتەمەلەر: Not Connected ۇلانبادى (Limited) (网络受限) WpaWifiDialog EAP type EAP方法 Username 用户名 Password 密钥 Ask pwd each query 每次询问密码 Cancel 取消 Connect 连接 None Choose from file... 从文件选择... Choose a CA certificate 选择一个CA证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) Identity 匿名身份 Domain no need for CA certificate 不需要CA证书 main kylinnm جەكە تور اسپاپ show kylin-nm wifi page جەكە تور دۇن سەمىز تور بەت بەتىن كۅرسۅتۉۉ show kylin-nm lan page جەكە توردۇن تار گۅۅلۅمدۉ توردۇن بەت بەتىن كۅرسۅتۉۉ kylin-nm/src/main.cpp0000664000175000017500000001766415167651420013502 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include #include "qt-single-application.h" #include #include #include #include #if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)) #include "xatom-helper.h" #endif #define LOG_IDENT "ukui_kylin_nm" const QString QT_TRANSLATE_FILE = "/usr/share/qt6/translations/qt_zh_CN.qm"; void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); QByteArray currentDateTime = QDateTime::currentDateTime().toString().toLocal8Bit(); bool showDebug = true; QString logFilePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + "/.config/ukui/kylin-nm.log"; //若不需要自动创建日志文件,请放开此注释 // if (!QFile::exists(logFilePath)) { // showDebug = false; // } FILE *log_file = nullptr; if (showDebug) { log_file = fopen(logFilePath.toLocal8Bit().constData(), "a+"); } const char *file = context.file ? context.file : ""; const char *function = context.function ? context.function : ""; switch (type) { case QtDebugMsg: if (!log_file) { break; } fprintf(log_file, "Debug: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); break; case QtInfoMsg: fprintf(log_file? log_file: stdout, "Info: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); break; case QtWarningMsg: fprintf(log_file? log_file: stderr, "Warning: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); break; case QtCriticalMsg: fprintf(log_file? log_file: stderr, "Critical: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); break; case QtFatalMsg: fprintf(log_file? log_file: stderr, "Fatal: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); break; } if (log_file) fclose(log_file); } QString displayFromPid(uint pid) { QFile environFile(QStringLiteral("/proc/%1/environ").arg(QString::number(pid))); if (environFile.open(QIODevice::ReadOnly | QIODevice::Text)) { const QByteArray DISPLAY = KWindowSystem::isPlatformWayland() ? QByteArrayLiteral("WAYLAND_DISPLAY") : QByteArrayLiteral("DISPLAY"); const auto lines = environFile.readAll().split('\0'); for (const QByteArray &line : lines) { const int equalsIdx = line.indexOf('='); if (equalsIdx <= 0) { continue; } const QByteArray key = line.left(equalsIdx); if (key == DISPLAY) { const QByteArray value = line.mid(equalsIdx + 1); return value; } } } return {}; } int main(int argc, char *argv[]) { initUkuiLog4qt("kylin-nm"); #if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)) QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); #endif // QApplication a(argc, argv); QString id = QString("kylin-nm"+ QLatin1String(getenv("DISPLAY"))); QtSingleApplication a(id, argc, argv); QApplication::setQuitOnLastWindowClosed(false); QCommandLineParser parser; parser.setApplicationDescription(QCoreApplication::translate("main", "kylinnm")); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption swOption(QStringLiteral("sw"),QCoreApplication::translate("main", "show kylin-nm wifi page")); QCommandLineOption snOption(QStringLiteral("sn"),QCoreApplication::translate("main", "show kylin-nm lan page")); parser.addOptions({swOption,snOption}); parser.process(a); QString display; QString sessionType; if(QString(getenv("XDG_SESSION_TYPE")) == "wayland") { sessionType = "wayland"; display = getenv("WAYLAND_DISPLAY"); } else { sessionType = "x11"; display = getenv("DISPLAY"); } qDebug() << sessionType << display; qApp->setProperty("sessionType", sessionType); QDBusInterface interface("com.kylin.network", "/com/kylin/network", "com.kylin.network", QDBusConnection::sessionBus()); if (a.isRunning()) { if(interface.isValid()) { if (parser.isSet(swOption)) { interface.call(QStringLiteral("showKylinNM"), 1); } else if (parser.isSet(snOption)) { interface.call(QStringLiteral("showKylinNM"), 0); } else { interface.call(QStringLiteral("showKylinNM"), 2); } } return 0; } QThread *thread = new QThread(); KyNetworkResourceManager *p_networkResource = KyNetworkResourceManager::getInstance(); p_networkResource->moveToThread(thread); QObject::connect(thread, &QThread::started, p_networkResource, &KyNetworkResourceManager::onInitNetwork); QObject::connect(&a,&QtSingleApplication::aboutToQuit, thread, &QThread::quit); QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater); thread->start(); // Internationalization QString locale = QLocale::system().name(); QTranslator trans_global; qDebug() << "QLocale " << QLocale(); if (trans_global.load(QLocale(), "kylin-nm", "_", "/usr/share/kylin-nm/kylin-nm/")) { a.installTranslator(&trans_global); qDebug()<<"Translations load success"; } else { qWarning() << "Translations load fail"; } QTranslator qtBaseTranslator; if (qtBaseTranslator.load(QLocale(), "qt", "_", "/usr/share/qt6/translations/")) { a.installTranslator(&qtBaseTranslator); qDebug()<<"QtBase Translations load success"; } else { qWarning() << "QtBase Translations load fail"; } QTranslator sdkTranslator; if (sdkTranslator.load(QLocale(), "gui", "_", ":/translations/")) { a.installTranslator(&sdkTranslator); qDebug()<<"SDK Translations load success"; } else { qWarning() << "SDK Translations load fail"; } while (!p_networkResource->NetworkManagerIsInited()) { ::usleep(1000); } MainWindow w(display, nullptr); a.setActivationWindow(&w); w.setProperty("useStyleWindowManager", false); //禁用拖动 a.setWindowIcon(QIcon::fromTheme("kylin-network")); //设置窗口无边框,阴影 // MotifWmHints window_hints; // window_hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS; // window_hints.functions = MWM_FUNC_ALL; // window_hints.decorations = MWM_DECOR_BORDER; // XAtomHelper::getInstance()->setWindowMotifHint(w.winId(), window_hints); // w.setWindowFlags(Qt::CustomizeWindowHint | Qt::FramelessWindowHint /*| Qt::X11BypassWindowManagerHint*/); DbusAdaptor adaptor(display, &w); Q_UNUSED(adaptor); return a.exec(); } kylin-nm/src/kylin-nm.desktop0000664000175000017500000000104415167646234015173 0ustar fengfeng[Desktop Entry] Encoding=UTF-8 Name=Kylin NM Name[zh_CN]=麒麟网络设置工具 Name[zh_HK]=麒麟網路設置工具 Name[zh_TW]=麒麟網路設置工具 Icon=gnome-dev-ethernet Comment=Beautiful Network Config Applet Comment[zh_CN]=麒麟网络设置工具,提供查看和简单设置功能,拥有美观的界面和舒适的操作. Keywords=applet;nm;network;network-manager; Exec=/usr/bin/kylin-nm StartupNotify=false Terminal=false Type=Application OnlyShowIn=UKUI X-UKUI-AutoRestart=true NoDisplay=true X-UKUI-Autostart-Phase=Application kylin-nm/src/translate_generation.sh0000775000175000017500000000056615167651420016612 0ustar fengfeng#!/bin/bash export PATH="/usr/lib/qt6/bin:$PATH" ts_list=(`ls translations/*.ts`) source /etc/os-release version=(`echo $ID`) for ts in "${ts_list[@]}" do printf "\nprocess ${ts}\n" if [ "$version" == "fedora" ] || [ "$version" == "opensuse-leap" ] || [ "$version" == "opensuse-tumbleweed" ];then lrelease-qt5 "${ts}" else lrelease "${ts}" fi done kylin-nm/src/src.pro0000664000175000017500000000551715167651420013355 0ustar fengfeng#------------------------------------------------- # # Project created by QtCreator 2018-10-19T15:29:47 # #------------------------------------------------- QT += core gui dbus concurrent network svg greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = kylin-nm TEMPLATE = app CONFIG += c++14 qt warn_on link_pkgconfig no_keywords #CONFIG += release PKGCONFIG +=gio-2.0 glib-2.0 gio-unix-2.0 libnm libnma libsecret-1 gtk+-3.0 gsettings-qt6 libcap kysdk-applications PKGCONFIG +=kysdk-sysinfo KF6WindowSystem INCLUDEPATH += /usr/include/KF6/NetworkManagerQt LIBS += -L/usr/lib/ -lX11 -lKF6NetworkManagerQt -lukui-log4qt -lkysdk-ukuiwindowhelper #LIBS += -lkysec CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } target.path = /usr/bin target.source += $$TARGET desktop.path = /etc/xdg/autostart/ desktop.files = kylin-nm.desktop qm_files.path = /usr/share/kylin-nm/kylin-nm/ qm_files.files = translations/*.qm ts_files.path = /usr/share/kylin-nm/kylin-nm/ ts_files.files = translations/*.ts INSTALLS += target \ desktop \ qm_files \ ts_files # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 # QMAKE_CXXFLAGS += -Wno-unused-parameter QMAKE_CPPFLAGS *= $(shell dpkg-buildflags --get CPPFLAGS) QMAKE_CFLAGS *= $(shell dpkg-buildflags --get CFLAGS) QMAKE_CXXFLAGS *= $(shell dpkg-buildflags --get CXXFLAGS) QMAKE_LFLAGS *= $(shell dpkg-buildflags --get LDFLAGS) include(singleapplication/qt-single-application.pri) include(backend/backend.pri) include(frontend/frontend.pri) RESOURCES += \ ../nmqrc.qrc SOURCES += \ main.cpp unix { UI_DIR = .ui MOC_DIR = .moc OBJECTS_DIR = .obj } # DISTFILES += \ # org.ukui.kylin-nm.switch.gschema.xml TRANSLATIONS += \ translations/kylin-nm_zh_Hant.ts \ translations/kylin-nm_zh_HK.ts \ translations/kylin-nm_zh_CN.ts \ translations/kylin-nm_ug.ts \ translations/kylin-nm_tr.ts \ translations/kylin-nm_mn.ts \ translations/kylin-nm_ky.ts \ translations/kylin-nm_kk.ts \ translations/kylin-nm_fr.ts \ translations/kylin-nm_es.ts \ translations/kylin-nm_de.ts \ translations/kylin-nm_bo.ts\ translations/kylin-nm_bo_CN.ts kylin-nm/src/singleapplication/0000775000175000017500000000000015167651420015541 5ustar fengfengkylin-nm/src/singleapplication/qt-single-application.cpp0000664000175000017500000003033515167651420022455 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ** ****************************************************************************/ #include "qt-single-application.h" #include "qt-local-peer.h" #include #include #include #include #include #include #include #include "../mainwindow.h" /*! \class QtSingleApplication qtsingleapplication.h \brief The QtSingleApplication class provides an API to detect and communicate with running instances of an application. This class allows you to create applications where only one instance should be running at a time. I.e., if the user tries to launch another instance, the already running instance will be activated instead. Another usecase is a client-server system, where the first started instance will assume the role of server, and the later instances will act as clients of that server. By default, the full path of the executable file is used to determine whether two processes are instances of the same application. You can also provide an explicit identifier string that will be compared instead. The application should create the QtSingleApplication object early in the startup phase, and call isRunning() to find out if another instance of this application is already running. If isRunning() returns false, it means that no other instance is running, and this instance has assumed the role as the running instance. In this case, the application should continue with the initialization of the application user interface before entering the event loop with exec(), as normal. The messageReceived() signal will be emitted when the running application receives messages from another instance of the same application. When a message is received it might be helpful to the user to raise the application so that it becomes visible. To facilitate this, QtSingleApplication provides the setActivationWindow() function and the activateWindow() slot. If isRunning() returns true, another instance is already running. It may be alerted to the fact that another instance has started by using the sendMessage() function. Also data such as startup parameters (e.g. the name of the file the user wanted this new instance to open) can be passed to the running instance with this function. Then, the application should terminate (or enter client mode). If isRunning() returns true, but sendMessage() fails, that is an indication that the running instance is frozen. Here's an example that shows how to convert an existing application to use QtSingleApplication. It is very simple and does not make use of all QtSingleApplication's functionality (see the examples for that). \code // Original int main(int argc, char **argv) { QApplication app(argc, argv); MyMainWidget mmw; mmw.show(); return app.exec(); } // Single instance int main(int argc, char **argv) { QtSingleApplication app(argc, argv); if (app.isRunning()) return !app.sendMessage(someDataString); MyMainWidget mmw; app.setActivationWindow(&mmw); mmw.show(); return app.exec(); } \endcode Once this QtSingleApplication instance is destroyed (normally when the process exits or crashes), when the user next attempts to run the application this instance will not, of course, be encountered. The next instance to call isRunning() or sendMessage() will assume the role as the new running instance. For console (non-GUI) applications, QtSingleCoreApplication may be used instead of this class, to avoid the dependency on the QtGui library. \sa QtSingleCoreApplication */ void QtSingleApplication::sysInit(const QString &appId) { m_activateWindow = 0; m_peer = new QtLocalPeer(this, appId); connect(m_peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::messageReceived); } /*! Creates a QtSingleApplication object. The application identifier will be QCoreApplication::applicationFilePath(). \a argc, \a argv, and \a GUIenabled are passed on to the QAppliation constructor. If you are creating a console application (i.e. setting \a GUIenabled to false), you may consider using QtSingleCoreApplication instead. */ QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled) : QApplication(argc, argv, GUIenabled) { sysInit(); } /*! Creates a QtSingleApplication object with the application identifier \a appId. \a argc and \a argv are passed on to the QAppliation constructor. */ QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv) : QApplication(argc, argv) { sysInit(appId); } #if QT_VERSION < 0x050000 /*! Creates a QtSingleApplication object. The application identifier will be QCoreApplication::applicationFilePath(). \a argc, \a argv, and \a type are passed on to the QAppliation constructor. */ QtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type) : QApplication(argc, argv, type) { sysInit(); } # if defined(Q_WS_X11) /*! Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier will be QCoreApplication::applicationFilePath(). \a dpy, \a visual, and \a cmap are passed on to the QApplication constructor. */ QtSingleApplication::QtSingleApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE cmap) : QApplication(dpy, visual, cmap) { sysInit(); } /*! Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier will be QCoreApplication::applicationFilePath(). \a dpy, \a argc, \a argv, \a visual, and \a cmap are passed on to the QApplication constructor. */ QtSingleApplication::QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) : QApplication(dpy, argc, argv, visual, cmap) { sysInit(); } /*! Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier will be \a appId. \a dpy, \a argc, \a argv, \a visual, and \a cmap are passed on to the QApplication constructor. */ QtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) : QApplication(dpy, argc, argv, visual, cmap) { sysInit(appId); } # endif // Q_WS_X11 #endif // QT_VERSION < 0x050000 /*! Returns true if another instance of this application is running; otherwise false. This function does not find instances of this application that are being run by a different user (on Windows: that are running in another session). \sa sendMessage() */ bool QtSingleApplication::isRunning() { return m_peer->isClient(); } /*! Tries to send the text \a message to the currently running instance. The QtSingleApplication object in the running instance will emit the messageReceived() signal when it receives the message. This function returns true if the message has been sent to, and processed by, the current instance. If there is no instance currently running, or if the running instance fails to process the message within \a timeout milliseconds, this function return false. \sa isRunning(), messageReceived() */ bool QtSingleApplication::sendMessage(const QString &message, int timeout) { return m_peer->sendMessage(message, timeout); } /*! Returns the application identifier. Two processes with the same identifier will be regarded as instances of the same application. */ QString QtSingleApplication::id() const { return m_peer->applicationId(); } /*! Sets the activation window of this application to \a aw. The activation window is the widget that will be activated by activateWindow(). This is typically the application's main window. If \a activateOnMessage is true (the default), the window will be activated automatically every time a message is received, just prior to the messageReceived() signal being emitted. \sa activateWindow(), messageReceived() */ void QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage) { m_activateWindow = aw; if (activateOnMessage) connect(m_peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow); else disconnect(m_peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow); } /*! Returns the applications activation window if one has been set by calling setActivationWindow(), otherwise returns 0. \sa setActivationWindow() */ QWidget* QtSingleApplication::activationWindow() const { return m_activateWindow; } /*! De-minimizes, raises, and activates this application's activation window. This function does nothing if no activation window has been set. This is a convenience function to show the user that this application instance has been activated when he has tried to start another instance. This function should typically be called in response to the messageReceived() signal. By default, that will happen automatically, if an activation window has been set. \sa setActivationWindow(), messageReceived(), initialize() */ void QtSingleApplication::activateWindow() { if (m_activateWindow) { if(this->applicationState() & Qt::ApplicationInactive) { MainWindow* w=qobject_cast(m_activateWindow); w->showMainwindow(); m_activateWindow->setWindowState(m_activateWindow->windowState() & ~Qt::WindowMinimized); m_activateWindow->raise(); m_activateWindow->showNormal(); m_activateWindow->activateWindow(); } else { m_activateWindow->setWindowState(m_activateWindow->windowState() & Qt::WindowMinimized); m_activateWindow->hide(); } } } /*! \fn void QtSingleApplication::messageReceived(const QString& message) This signal is emitted when the current instance receives a \a message from another instance of this application. \sa sendMessage(), setActivationWindow(), activateWindow() */ /*! \fn void QtSingleApplication::initialize(bool dummy = true) \obsolete */ kylin-nm/src/singleapplication/qt-locked-file-unix.cpp0000664000175000017500000000662115167646234022042 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include #include #include #include #include "qt-locked-file.h" bool QtLockedFile::lock(LockMode mode, bool block) { if(!isOpen()) { qWarning("QtLockedFile::lock(): file is not opened"); return false; } if(mode == NoLock) return unlock(); if(mode == m_lock_mode) return true; if(m_lock_mode != NoLock) unlock(); struct flock fl; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK; int cmd = block ? F_SETLKW : F_SETLK; int ret = fcntl(handle(), cmd, &fl); if(ret == -1) { if(errno != EINTR && errno != EAGAIN) qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); return false; } m_lock_mode = mode; return true; } bool QtLockedFile::unlock() { if(!isOpen()) { qWarning("QtLockedFile::unlock(): file is not opened"); return false; } if(!isLocked()) return true; struct flock fl; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_type = F_UNLCK; int ret = fcntl(handle(), F_SETLKW, &fl); if(ret == -1) { qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); return false; } m_lock_mode = NoLock; return true; } QtLockedFile::~QtLockedFile() { if(isOpen()) unlock(); } kylin-nm/src/singleapplication/qt-single-application.pri0000664000175000017500000000131115167646234022464 0ustar fengfengINCLUDEPATH += $$PWD DEPENDPATH += $$PWD QT *= network greaterThan(QT_MAJOR_VERSION, 4): QT *= widgets qtsingleapplication-uselib:!qtsingleapplication-buildlib { LIBS += -L$$QTSINGLEAPPLICATION_LIBDIR -l$$QTSINGLEAPPLICATION_LIBNAME } else { SOURCES += HEADERS += } win32 { contains(TEMPLATE, lib):contains(CONFIG, shared):DEFINES += QT_QTSINGLEAPPLICATION_EXPORT else:qtsingleapplication-uselib:DEFINES += QT_QTSINGLEAPPLICATION_IMPORT } HEADERS += \ $$PWD/qt-local-peer.h \ $$PWD/qt-locked-file.h \ $$PWD/qt-single-application.h SOURCES += \ $$PWD/qt-local-peer.cpp \ $$PWD/qt-locked-file-unix.cpp \ $$PWD/qt-single-application.cpp \ $$PWD/qt-locked-file.cpp kylin-nm/src/singleapplication/qt-single-application.h0000664000175000017500000000772715167646234022142 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ** ****************************************************************************/ #ifndef QTSINGLEAPPLICATION_H #define QTSINGLEAPPLICATION_H #include class QtLocalPeer; #if defined(Q_OS_WIN) # if !defined(QT_QTSINGLEAPPLICATION_EXPORT) && !defined(QT_QTSINGLEAPPLICATION_IMPORT) # define QT_QTSINGLEAPPLICATION_EXPORT # elif defined(QT_QTSINGLEAPPLICATION_IMPORT) # if defined(QT_QTSINGLEAPPLICATION_EXPORT) # undef QT_QTSINGLEAPPLICATION_EXPORT # endif # define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllimport) # elif defined(QT_QTSINGLEAPPLICATION_EXPORT) # undef QT_QTSINGLEAPPLICATION_EXPORT # define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllexport) # endif #else # define QT_QTSINGLEAPPLICATION_EXPORT #endif class QT_QTSINGLEAPPLICATION_EXPORT QtSingleApplication : public QApplication { Q_OBJECT public: QtSingleApplication(int &argc, char **argv, bool GUIenabled = true); QtSingleApplication(const QString &id, int &argc, char **argv); #if QT_VERSION < 0x050000 QtSingleApplication(int &argc, char **argv, Type type); # if defined(Q_WS_X11) QtSingleApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0); QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); # endif // Q_WS_X11 #endif // QT_VERSION < 0x050000 bool isRunning(); QString id() const; void setActivationWindow(QWidget* aw, bool activateOnMessage = true); QWidget* activationWindow() const; // Obsolete: void initialize(bool dummy = true) { isRunning(); Q_UNUSED(dummy) } public Q_SLOTS: bool sendMessage(const QString &message, int timeout = 5000); void activateWindow(); Q_SIGNALS: void messageReceived(const QString &message); private: void sysInit(const QString &appId = QString()); QtLocalPeer *m_peer; QWidget *m_activateWindow; }; #endif // QTSINGLEAPPLICATION_H kylin-nm/src/singleapplication/qt-local-peer.cpp0000664000175000017500000001612015167651420020712 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ** ****************************************************************************/ #include "qt-local-peer.h" #include "qregularexpression.h" #include #include #include #if defined(Q_OS_UNIX) #include #include #include #endif namespace QtLP_Private { #include "qt-locked-file.cpp" #include "qt-locked-file-unix.cpp" } const char* QtLocalPeer::ack = "ack"; QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId) : QObject(parent), id(appId) { QString prefix = id; if(id.isEmpty()) { id = QCoreApplication::applicationFilePath(); #if defined(Q_OS_WIN) id = id.toLower(); #endif prefix = id.section(QLatin1Char('/'), -1); //完整路径按‘/’分隔后取最后一个字段 } prefix.remove(QRegularExpression("[^a-zA-Z]")); //去掉名称中的非字母 prefix.truncate(6); //取前六位 QByteArray idc = id.toUtf8(); quint16 idNum = qChecksum(idc.constData(), idc.size()); socketName = QLatin1String("qtsingleapp-") + prefix + QLatin1Char('-') + QString::number(idNum, 16); #if defined(Q_OS_WIN) if(!pProcessIdToSessionId) { QLibrary lib("kernel32"); pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId"); } if(pProcessIdToSessionId) { DWORD sessionId = 0; pProcessIdToSessionId(GetCurrentProcessId(), &sessionId); socketName += QLatin1Char('-') + QString::number(sessionId, 16); } #else socketName += QLatin1Char('-') + QString::number(::getuid(), 16); #endif server = new QLocalServer(this); QString lockName = QDir(QDir::tempPath()).absolutePath() + QLatin1Char('/') + socketName + QLatin1String("-lockfile"); //tmp目录下的锁文件 lockFile.setFileName(lockName); lockFile.open(QIODevice::ReadWrite); } bool QtLocalPeer::isClient() { if(lockFile.isLocked()) return false; if(!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false)) return true; //由于文件锁的存在,仅当本进程第一次启动时能执行到此并使server进行监听和关联槽函数 bool res = server->listen(socketName); #if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0)) // ### Workaround if(!res && server->serverError() == QAbstractSocket::AddressInUseError) { QFile::remove(QDir::cleanPath(QDir::tempPath()) + QLatin1Char('/') + socketName); res = server->listen(socketName); } #endif if(!res) qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString())); QObject::connect(server, &QLocalServer::newConnection, this, &QtLocalPeer::receiveConnection); return false; } bool QtLocalPeer::sendMessage(const QString &message, int timeout) { if(!isClient()) return false; QLocalSocket socket; bool connOk = false; for(int i = 0; i < 2; i++) { // Try twice, in case the other instance is just starting up socket.connectToServer(socketName); connOk = socket.waitForConnected(timeout / 2); if(connOk || i) break; int ms = 250; #if defined(Q_OS_WIN) Sleep(DWORD(ms)); #else struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; nanosleep(&ts, NULL); #endif } if(!connOk) return false; QByteArray uMsg(message.toUtf8()); QDataStream ds(&socket); ds.writeBytes(uMsg.constData(), uMsg.size()); bool res = socket.waitForBytesWritten(timeout); if(res) { res &= socket.waitForReadyRead(timeout); // wait for ack if(res) res &= (socket.read(qstrlen(ack)) == ack); } return res; } /** * @brief QtLocalPeer::receiveConnection 当新进程启动时,会尝试连接此进程server,server接收到newConnection信号并触发此槽函数 */ void QtLocalPeer::receiveConnection() { QLocalSocket* socket = server->nextPendingConnection(); //获取新进程的socket if(!socket) return; while(true) { if(socket->state() == QLocalSocket::UnconnectedState) { qWarning("QtLocalPeer: Peer disconnected"); delete socket; return; } if(socket->bytesAvailable() >= qint64(sizeof(quint32))) break; socket->waitForReadyRead(); } QDataStream ds(socket); QByteArray uMsg; quint32 remaining; ds >> remaining; uMsg.resize(remaining); int got = 0; char* uMsgBuf = uMsg.data(); do { got = ds.readRawData(uMsgBuf, remaining); remaining -= got; uMsgBuf += got; } while(remaining && got >= 0 && socket->waitForReadyRead(2000)); if(got < 0) { qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); delete socket; return; } QString message(QString::fromUtf8(uMsg)); socket->write(ack, qstrlen(ack)); socket->waitForBytesWritten(1000); socket->waitForDisconnected(1000); // make sure client reads ack delete socket; Q_EMIT messageReceived(message); //获取新进程的启动信息并作为信号发送给前端 } kylin-nm/src/singleapplication/qt-locked-file.cpp0000664000175000017500000001401415167646234021054 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qt-locked-file.h" /*! \class QtLockedFile \brief The QtLockedFile class extends QFile with advisory locking functions. A file may be locked in read or write mode. Multiple instances of \e QtLockedFile, created in multiple processes running on the same machine, may have a file locked in read mode. Exactly one instance may have it locked in write mode. A read and a write lock cannot exist simultaneously on the same file. The file locks are advisory. This means that nothing prevents another process from manipulating a locked file using QFile or file system functions offered by the OS. Serialization is only guaranteed if all processes that access the file use QLockedFile. Also, while holding a lock on a file, a process must not open the same file again (through any API), or locks can be unexpectedly lost. The lock provided by an instance of \e QtLockedFile is released whenever the program terminates. This is true even when the program crashes and no destructors are called. */ /*! \enum QtLockedFile::LockMode This enum describes the available lock modes. \value ReadLock A read lock. \value WriteLock A write lock. \value NoLock Neither a read lock nor a write lock. */ /*! Constructs an unlocked \e QtLockedFile object. This constructor behaves in the same way as \e QFile::QFile(). \sa QFile::QFile() */ QtLockedFile::QtLockedFile() : QFile() { #ifdef Q_OS_WIN wmutex = 0; rmutex = 0; #endif m_lock_mode = NoLock; } /*! Constructs an unlocked QtLockedFile object with file \a name. This constructor behaves in the same way as \e QFile::QFile(const QString&). \sa QFile::QFile() */ QtLockedFile::QtLockedFile(const QString &name) : QFile(name) { #ifdef Q_OS_WIN wmutex = 0; rmutex = 0; #endif m_lock_mode = NoLock; } /*! Opens the file in OpenMode \a mode. This is identical to QFile::open(), with the one exception that the Truncate mode flag is disallowed. Truncation would conflict with the advisory file locking, since the file would be modified before the write lock is obtained. If truncation is required, use resize(0) after obtaining the write lock. Returns true if successful; otherwise false. \sa QFile::open(), QFile::resize() */ bool QtLockedFile::open(OpenMode mode) { if(mode & QIODevice::Truncate) { qWarning("QtLockedFile::open(): Truncate mode not allowed."); return false; } return QFile::open(mode); } /*! Returns \e true if this object has a in read or write lock; otherwise returns \e false. \sa lockMode() */ bool QtLockedFile::isLocked() const { return m_lock_mode != NoLock; } /*! Returns the type of lock currently held by this object, or \e QtLockedFile::NoLock. \sa isLocked() */ QtLockedFile::LockMode QtLockedFile::lockMode() const { return m_lock_mode; } /*! \fn bool QtLockedFile::lock(LockMode mode, bool block = true) Obtains a lock of type \a mode. The file must be opened before it can be locked. If \a block is true, this function will block until the lock is aquired. If \a block is false, this function returns \e false immediately if the lock cannot be aquired. If this object already has a lock of type \a mode, this function returns \e true immediately. If this object has a lock of a different type than \a mode, the lock is first released and then a new lock is obtained. This function returns \e true if, after it executes, the file is locked by this object, and \e false otherwise. \sa unlock(), isLocked(), lockMode() */ /*! \fn bool QtLockedFile::unlock() Releases a lock. If the object has no lock, this function returns immediately. This function returns \e true if, after it executes, the file is not locked by this object, and \e false otherwise. \sa lock(), isLocked(), lockMode() */ /*! \fn QtLockedFile::~QtLockedFile() Destroys the \e QtLockedFile object. If any locks were held, they are released. */ kylin-nm/src/singleapplication/qt-locked-file.h0000664000175000017500000000636015167646234020526 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QTLOCKEDFILE_H #define QTLOCKEDFILE_H #include #ifdef Q_OS_WIN #include #endif #if defined(Q_OS_WIN) # if !defined(QT_QTLOCKEDFILE_EXPORT) && !defined(QT_QTLOCKEDFILE_IMPORT) # define QT_QTLOCKEDFILE_EXPORT # elif defined(QT_QTLOCKEDFILE_IMPORT) # if defined(QT_QTLOCKEDFILE_EXPORT) # undef QT_QTLOCKEDFILE_EXPORT # endif # define QT_QTLOCKEDFILE_EXPORT __declspec(dllimport) # elif defined(QT_QTLOCKEDFILE_EXPORT) # undef QT_QTLOCKEDFILE_EXPORT # define QT_QTLOCKEDFILE_EXPORT __declspec(dllexport) # endif #else # define QT_QTLOCKEDFILE_EXPORT #endif namespace QtLP_Private { class QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile { public: enum LockMode { NoLock = 0, ReadLock, WriteLock }; QtLockedFile(); QtLockedFile(const QString &name); ~QtLockedFile(); bool open(OpenMode mode); bool lock(LockMode mode, bool block = true); bool unlock(); bool isLocked() const; LockMode lockMode() const; private: #ifdef Q_OS_WIN Qt::HANDLE wmutex; Qt::HANDLE rmutex; QVector rmutexes; QString mutexname; Qt::HANDLE getMutexHandle(int idx, bool doCreate); bool waitMutex(Qt::HANDLE mutex, bool doBlock); #endif LockMode m_lock_mode; }; } #endif kylin-nm/src/singleapplication/qt-local-peer.h0000664000175000017500000000527215167646234020374 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ** ****************************************************************************/ #ifndef QTLOCALPEER_H #define QTLOCALPEER_H #include #include #include #include "qt-locked-file.h" class QtLocalPeer : public QObject { Q_OBJECT public: QtLocalPeer(QObject *parent = 0, const QString &appId = QString()); bool isClient(); bool sendMessage(const QString &message, int timeout); QString applicationId() const { return id; } Q_SIGNALS: void messageReceived(const QString &message); protected Q_SLOTS: void receiveConnection(); protected: QString id; QString socketName; QLocalServer* server; QtLP_Private::QtLockedFile lockFile; private: static const char* ack; }; #endif // QTLOCALPEER_H kylin-nm/src/common/0000775000175000017500000000000015167646234013333 5ustar fengfengkylin-nm/src/common/common.pri0000664000175000017500000000014615167646234015340 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/common.h \ $$PWD/test.h SOURCES += DISTFILES += kylin-nm/src/common/common.h0000664000175000017500000000061415167646234014775 0ustar fengfeng#ifndef COMMON_H #define COMMON_H namespace KYLIN_NM { enum KySecuType { NONE = 0, WPA_AND_WPA2_PERSONAL, WPA_AND_WPA2_ENTERPRISE, WPA3_PERSONAL, WPA_AND_WPA3, }; enum KyKeyMgmt { Unknown = -1, Wep, Ieee8021x, WpaNone, WpaPsk, WpaEap, SAE }; } using namespace KYLIN_NM; #endif // COMMON_H kylin-nm/src/frontend/0000775000175000017500000000000015167651420013653 5ustar fengfengkylin-nm/src/frontend/enterprise-wlan/0000775000175000017500000000000015167651420016772 5ustar fengfengkylin-nm/src/frontend/enterprise-wlan/enterprise-wlan.pri0000664000175000017500000000020515167646234022631 0ustar fengfengINCLUDEPATH += $$PWD FORMS += \ HEADERS += \ $$PWD/enterprisewlandialog.h \ SOURCES += \ $$PWD/enterprisewlandialog.cpp \ kylin-nm/src/frontend/enterprise-wlan/enterprisewlandialog.cpp0000664000175000017500000003025615167651420023726 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "enterprisewlandialog.h" #include #include #include #include #include #include "kwindowsystem.h" #include "kwindowsystem_export.h" #define MAIN_SIZE_EXPAND 480,580 #define MAIN_SIZE_NARROW 480,484 #define SCROAREA_WIDTH 480 #define MAIN_LAYOUT_MARGINS 0,0,0,0 #define CENTER_LAYOUT_MARGINS 24, 16, 24, 8 #define BUTTON_LAYOUT_MARGINS 24, 24, 24, 24 #define MAIN_LAYOUT_SPACING 0 #define BUTTON_SPACING 16 #define LABEL_MIN_WIDTH 146 #define MEDIUM_WEIGHT_VALUE 57 #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" EnterpriseWlanDialog::EnterpriseWlanDialog(KyWirelessNetItem &wirelessNetItem, QString device, QWidget *parent) : KDialog(parent) { this->setWindowIcon(QIcon::fromTheme("kylin-network")); KX11Extras::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager); m_wirelessNetItem = wirelessNetItem; m_deviceName = device; m_connectOperation = new KyWirelessConnectOperation(); m_resource = new KyWirelessNetResource(); initUI(); initData(); centerToScreen(); } EnterpriseWlanDialog::~EnterpriseWlanDialog() { if (m_securityPage) { delete m_securityPage; m_securityPage = nullptr; } if (m_connectOperation) { delete m_connectOperation; m_connectOperation = nullptr; } } void EnterpriseWlanDialog::closeEvent(QCloseEvent *event) { Q_EMIT this->enterpriseWlanDialogClose(false); return QWidget::closeEvent(event); } void EnterpriseWlanDialog::paintEvent(QPaintEvent *event) { QPalette pal = qApp->palette(); QPainter painter(this); QColor color; if (this->isActiveWindow()) { color = pal.color(QPalette::Base); } else { color = pal.color(QPalette::Window); } painter.setBrush(color); painter.drawRect(this->rect()); painter.fillRect(rect(), QBrush(color)); return QWidget::paintEvent(event); } void EnterpriseWlanDialog::initUI() { m_mainLayout = new QVBoxLayout(this); m_mainLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); m_mainLayout->setSpacing(MAIN_LAYOUT_SPACING); m_centerWidget = new QWidget(this); QVBoxLayout *centerLayout = new QVBoxLayout(m_centerWidget); centerLayout->setContentsMargins(CENTER_LAYOUT_MARGINS); centerLayout->setSpacing(MAIN_LAYOUT_SPACING); m_descriptionLabel = new QLabel(this); m_descriptionLabel->setText(tr("Wi-Fi network requires authentication")); //Wi-Fi网络要求认证 QFont font = m_descriptionLabel->font(); font.setWeight(QFont::Medium); m_descriptionLabel->setFont(font); m_ssidLabel = new QLabel(this); QString str = tr("Access to Wi-Fi network \""); //访问Wi-Fi网络 str.append(m_wirelessNetItem.m_NetSsid); str.append(tr("\" requires a password or encryption key.")); //需要密码或加密秘钥 m_ssidLabel->setText(str); m_ssidLabel->setWordWrap(true); m_securityPage = new SecurityPage(false, this); m_securityPage->setSecurity(KySecuType::WPA_AND_WPA2_ENTERPRISE); // m_securityPage->setSecurityVisible(false); centerLayout->addWidget(m_descriptionLabel); centerLayout->addSpacing(8); centerLayout->addWidget(m_ssidLabel); centerLayout->addSpacing(BUTTON_SPACING); centerLayout->addWidget(m_securityPage); centerLayout->addStretch(); m_enterWlanScrollArea = new QScrollArea(this); m_enterWlanScrollArea->setFrameShape(QFrame::NoFrame); m_enterWlanScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_centerWidget->setFixedWidth(SCROAREA_WIDTH); m_enterWlanScrollArea->setFixedWidth(SCROAREA_WIDTH); m_enterWlanScrollArea->setWidget(m_centerWidget); m_enterWlanScrollArea->setWidgetResizable(true); m_enterWlanScrollArea->setBackgroundRole(QPalette::Base); m_bottomDivider = new Divider(false, this); QWidget *bottomWidget = new QWidget(this); QHBoxLayout *btnLayout = new QHBoxLayout(bottomWidget); btnLayout->setContentsMargins(BUTTON_LAYOUT_MARGINS); btnLayout->setSpacing(BUTTON_SPACING); m_cancelBtn = new QPushButton(this); m_connectBtn = new QPushButton(this); m_cancelBtn->setText(tr("Cancel")); m_connectBtn->setText(tr("Connect")); m_connectBtn->setEnabled(false); m_cancelBtn->setProperty("useButtonPalette", true); m_cancelBtn->setProperty("isImportant", false); m_connectBtn->setProperty("useButtonPalette", false); m_connectBtn->setProperty("isImportant", true); btnLayout->addStretch(); btnLayout->addWidget(m_cancelBtn); btnLayout->addWidget(m_connectBtn); m_mainLayout->addWidget(m_enterWlanScrollArea); m_mainLayout->addWidget(m_bottomDivider); m_mainLayout->addWidget(bottomWidget); this->mainWidget()->setLayout(m_mainLayout); this->setFixedSize(MAIN_SIZE_EXPAND); this->setWindowTitle(m_wirelessNetItem.m_NetSsid); initConnections(); } void EnterpriseWlanDialog::centerToScreen() { QRect desk_rect; QScreen *currentScreen = QGuiApplication::screenAt(QCursor::pos()); if (currentScreen) { desk_rect = currentScreen->geometry(); } else { desk_rect=QGuiApplication::primaryScreen()->geometry(); } int desk_x = desk_rect.width(); int desk_y = desk_rect.height(); int x = this->width(); int y = this->height(); this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); } void EnterpriseWlanDialog::initConnections() { connect(m_closeBtn, &QPushButton::clicked, this, &EnterpriseWlanDialog::close); connect(m_cancelBtn, &QPushButton::clicked, this, &EnterpriseWlanDialog::close); connect(m_connectBtn, &QPushButton::clicked, this, &EnterpriseWlanDialog::onBtnConnectClicked); connect(m_securityPage, &SecurityPage::eapTypeChanged, this, &EnterpriseWlanDialog::onEapTypeChanged); connect(m_securityPage, &SecurityPage::setSecuPageState, this, [ = ](bool status) { m_connectBtn->setEnabled(status); }); #if 0 connect(qApp, &QApplication::paletteChanged, this, &EnterpriseWlanDialog::onPaletteChanged); const QByteArray id(THEME_SCHAME); if(QGSettings::isSchemaInstalled(id)){ QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); connect(fontSetting, &QGSettings::changed,[=](QString key) { if ("themeColor" == key) { onPaletteChanged(); } }); } #endif } #if 0 void EnterpriseWlanDialog::onPaletteChanged() { QPalette pal = qApp->palette(); QGSettings * styleGsettings = nullptr; const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { styleGsettings = new QGSettings(style_id); QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = lightPalette(this); } } pal.setColor(QPalette::Window, pal.base().color()); this->setPalette(pal); setFramePalette(m_securityPage, pal); if (styleGsettings != nullptr) { delete styleGsettings; styleGsettings = nullptr; } } #endif void EnterpriseWlanDialog::initData() { if (m_wirelessNetItem.m_isConfigured) { KyEapMethodType type; m_connectOperation->getEnterpiseEapMethod(m_wirelessNetItem.m_connectUuid, type); if (type) { onEapTypeChanged(type); } else { qWarning() << "Get eap type failed!" << Q_FUNC_INFO << __LINE__; } } } void EnterpriseWlanDialog::onBtnConnectClicked() { qDebug() << "Clicked connectBtn, will connect enterprise WLAN, ssid = " << m_wirelessNetItem.m_NetSsid << "." << Q_FUNC_INFO << __LINE__; KySecuType secuType; KyEapMethodType eapType; m_securityPage->getSecuType(secuType, eapType); KyWirelessConnectSetting connetSetting; connetSetting.setConnectName(m_wirelessNetItem.m_NetSsid); connetSetting.setIfaceName(m_deviceName); connetSetting.isAutoConnect = m_securityPage->getAutoConnectState(); //ZJP_TODO 自动连接选项 connetSetting.m_type = KyKeyMgmt::WpaEap; connetSetting.m_ssid = m_wirelessNetItem.m_NetSsid; connetSetting.m_secretFlag = NetworkManager::Setting::SecretFlagType::None; connetSetting.dumpInfo(); if (eapType == KyEapMethodType::TLS) { m_info.tlsInfo.devIfaceName = m_deviceName; m_securityPage->updateTlsChange(m_info.tlsInfo); m_connectOperation->addAndActiveWirelessEnterPriseTlsConnect(m_info.tlsInfo, connetSetting, m_deviceName, false); } else if (eapType == KyEapMethodType::PEAP) { m_securityPage->updatePeapChange(m_info.peapInfo); m_connectOperation->addAndActiveWirelessEnterPrisePeapConnect(m_info.peapInfo, connetSetting, m_deviceName, false); } else if (eapType == KyEapMethodType::TTLS) { m_securityPage->updateTtlsChange(m_info.ttlsInfo); m_connectOperation->addAndActiveWirelessEnterPriseTtlsConnect(m_info.ttlsInfo, connetSetting, m_deviceName, false); } else if (eapType == KyEapMethodType::LEAP) { m_securityPage->updateLeapChange(m_info.leapInfo); m_connectOperation->addAndActiveWirelessEnterPriseLeapConnect(m_info.leapInfo, connetSetting, m_deviceName, false); } else if (eapType == KyEapMethodType::PWD) { m_securityPage->updatePwdChange(m_info.pwdInfo); m_connectOperation->addAndActiveWirelessEnterPrisePwdConnect(m_info.pwdInfo, connetSetting, m_deviceName, false); } else if (eapType == KyEapMethodType::FAST) { m_securityPage->updateFastChange(m_info.fastInfo); m_connectOperation->addAndActiveWirelessEnterPriseFastConnect(m_info.fastInfo, connetSetting, m_deviceName, false); } else { qWarning() << "Connect enterprise wlan failed!(Unknown eap type)" << Q_FUNC_INFO << __LINE__; } close(); } void EnterpriseWlanDialog::onEapTypeChanged(const KyEapMethodType &type) { switch (type) { case KyEapMethodType::TLS: if (!m_wirelessNetItem.m_connectUuid.isEmpty()) { m_resource->getEnterPriseInfoTls(m_wirelessNetItem.m_connectUuid, m_info.tlsInfo); } this->setFixedSize(MAIN_SIZE_EXPAND); break; case KyEapMethodType::PEAP: if (m_wirelessNetItem.m_connectUuid.isEmpty()) { m_resource->getEnterPriseInfoPeap(m_wirelessNetItem.m_connectUuid, m_info.peapInfo); } this->setFixedSize(MAIN_SIZE_NARROW); break; case KyEapMethodType::TTLS: if (!m_wirelessNetItem.m_connectUuid.isEmpty()) { m_resource->getEnterPriseInfoTtls(m_wirelessNetItem.m_connectUuid, m_info.ttlsInfo); } this->setFixedSize(MAIN_SIZE_NARROW); break; case KyEapMethodType::LEAP: if (!m_wirelessNetItem.m_connectUuid.isEmpty()) { m_resource->getEnterPriseInfoLeap(m_wirelessNetItem.m_connectUuid, m_info.leapInfo); } this->setFixedSize(MAIN_SIZE_NARROW); break; case KyEapMethodType::PWD: if (!m_wirelessNetItem.m_connectUuid.isEmpty()) { m_resource->getEnterPriseInfoPwd(m_wirelessNetItem.m_connectUuid, m_info.pwdInfo); } this->setFixedSize(MAIN_SIZE_NARROW); break; case KyEapMethodType::FAST: if (!m_wirelessNetItem.m_connectUuid.isEmpty()) { m_resource->getEnterPriseInfoFast(m_wirelessNetItem.m_connectUuid, m_info.fastInfo); } this->setFixedSize(MAIN_SIZE_EXPAND); break; default: break; } } kylin-nm/src/frontend/enterprise-wlan/enterprisewlandialog.h0000664000175000017500000000546015167651420023372 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef ENTERPRISEWLANDIALOG_H #define ENTERPRISEWLANDIALOG_H #include #include #include #include #include "securitypage.h" #include "divider.h" #include "kywirelessnetitem.h" #include "coninfo.h" #include using namespace kdk; class EnterpriseWlanDialog : public KDialog { Q_OBJECT public: EnterpriseWlanDialog(KyWirelessNetItem &wirelessNetItem, QString device, QWidget *parent = nullptr); ~EnterpriseWlanDialog(); protected: void closeEvent(QCloseEvent *event); void paintEvent(QPaintEvent *event); private: void initUI(); //初始化UI界面 void centerToScreen(); void initConnections(); void initData(); private: KyWirelessNetItem m_wirelessNetItem; ConInfo m_info; QString m_deviceName; KyWirelessConnectOperation *m_connectOperation = nullptr; KyWirelessNetResource *m_resource = nullptr; /* 弹窗布局 * Connect Enterprise WLAN············X * SSID··························[SSID] * -----------SecurityPage------------- * | | * ------------------------------------ * ····················CANCEL···CONNECT */ QVBoxLayout *m_mainLayout = nullptr; QHBoxLayout *m_titleLayout = nullptr; QLabel *m_titleLabel = nullptr; QPushButton *m_closeBtn = nullptr; QWidget *m_centerWidget = nullptr; QLabel *m_descriptionLabel = nullptr; QLabel *m_ssidLabel = nullptr; SecurityPage *m_securityPage = nullptr; QScrollArea *m_enterWlanScrollArea = nullptr; Divider *m_bottomDivider = nullptr; QPushButton *m_cancelBtn = nullptr; QPushButton *m_connectBtn = nullptr; private Q_SLOTS: void onBtnConnectClicked(); void onEapTypeChanged(const KyEapMethodType &type); Q_SIGNALS: void enterpriseWlanDialogClose(bool); }; #endif // ENTERPRISEWLANDIALOG_H kylin-nm/src/frontend/mainwindow.cpp0000664000175000017500000016762215167651420016551 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "mainwindow.h" #include "customstyle.h" #include #include #include #include #include #include #include #include #include #include #include #include "kylinnetworkdeviceresource.h" #include "../backend/dbus-interface/kylinagentinterface.h" #include "ukuistylehelper/ukuistylehelper.h" #include "windowmanager/windowmanager.h" #include "kysdk/kysdk-system/libkysysinfo.h" #include "kylinutil.h" #define MAINWINDOW_WIDTH 420 #define MAINWINDOW_HEIGHT 476 #define LAYOUT_MARGINS 0,0,0,0 #define LOADING_TRAYICON_TIMER_MS 60 #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" #define PANEL_SETTINGS "org.ukui.panel.settings" #define PANEL_SIZE_KEY "panelsize" #define PANEL_POSITION_KEY "panelposition" #define PANEL_TYPE_KEY "paneltype" #define UKUI_SETTINGS_ISLAND_POSITION_KEY "settingsislandposition" #define UKUI_TOPBAR_SIZE_KEY "topbarsize" #define UKUI_PANEL_LENGTH_KEY "panellength" const QString v10Sp1 = "V10SP1"; const QString intel = "V10SP1-edu"; #define LANPAGE 0 #define WLANPAGE 1 #define AUTOSELET 2 #define SINGLE_TAB_WIDTH 194 #define MARGIN 8 #define PANEL_TOP 1 #define PANEL_LEFT 2 #define PANEL_RIGHT 3 #define PANEL_BOTTOM 0 #define KEY_PRODUCT_FEATURES "PRODUCT_FEATURES" #define MW_EXCELLENT_SIGNAL 80 #define MW_GOOD_SIGNAL 55 #define MW_OK_SIGNAL 30 #define MW_LOW_SIGNAL 5 #define MW_NONE_SIGNAL 0 #define EXCELLENT_SIGNAL_ICON "network-wireless-signal-excellent-symbolic" #define GOOD_SIGNAL_ICON "network-wireless-signal-good-symbolic" #define OK_SIGNAL_ICON "network-wireless-signal-ok-symbolic" #define LOW_SIGNAL_ICON "network-wireless-signal-weak-symbolic" #define NONE_SIGNAL_ICON "network-wireless-signal-none-symbolic" #define EXCELLENT_SIGNAL_LIMIT_ICON "ukui-network-wireless-signal-excellent-error-symbolic" #define GOOD_SIGNAL_LIMIT_ICON "ukui-network-wireless-signal-good-error-symbolic" #define OK_SIGNAL_LIMIT_ICON "ukui-network-wireless-signal-ok-error-symbolic" #define LOW_SIGNAL_LIMIT_ICON "ukui-network-wireless-signal-weak-error-symbolic" #define NONE_SIGNAL_LIMIT_ICON "ukui-network-wireless-signal-none-error-symbolic" #define EXCELLENT_SIGNAL_INTRANET_ICON "ukui-network-wireless-signal-excellent-intranet-symbolic" #define GOOD_SIGNAL_INTRANET_ICON "ukui-network-wireless-signal-good-intranet-symbolic" #define OK_SIGNAL_INTRANET_ICON "ukui-network-wireless-signal-ok-intranet-symbolic" #define LOW_SIGNAL_INTRANET_ICON "ukui-network-wireless-signal-weak-intranet-symbolic" #define NONE_SIGNAL_INTRANET_ICON "ukui-network-wireless-signal-none-intranet-symbolic" #define DBUSSERVICE_UKCC "org.ukui.ukcc.session" #define DBUSPATH_UKCC "/" #define DBUSINTERFACE_UKCC "org.ukui.ukcc.session.interface" #include #include MainWindow::MainWindow(QString display, QWidget *parent) : QMainWindow(parent), m_display(display) { QDir dir(CONFIG_FILE_DIR); if (!dir.exists()) { dir.mkdir(CONFIG_FILE_DIR); } QString filename = CONFIG_FILE_PATH; QSettings m_pConfSetting(filename, QSettings::IniFormat); if (!m_pConfSetting.contains(AUTO_FIRE_WALL_PERMIITTED)) { m_pConfSetting.setValue(AUTO_FIRE_WALL_PERMIITTED, true); } if (!m_pConfSetting.contains(FIRE_WALL_PERMISSION_SHOW)) { m_pConfSetting.setValue(FIRE_WALL_PERMISSION_SHOW, true); } firstlyStart(); //去除窗管标题栏,传入参数为QWidget* //此方法只需要调用一次,多次调用时,除首次调用窗口正常外,其余次数调用窗口setGeometry接口失效 //kf6 qt6 崩溃 by mq //kdk::UkuiStyleHelper::self()->removeHeader(this); } /** * @brief MainWindow::showMainwindow show主窗口,同时也作为dbus接口提供给外部组件调用 */ void MainWindow::showMainwindow() { if (!m_loadFinished) { m_secondaryStartTimer->stop(); secondaryStart(); } /** * 设置主界面跳过任务栏和分页器的属性,隐藏再次展示有可能辉冲刷掉该属性,需要展示时重新设置 */ #if 0 QString platform = QGuiApplication::platformName(); if(!platform.startsWith(QLatin1String("wayland"),Qt::CaseInsensitive)) { const KWindowInfo info(this->winId(), NET::WMState); if (!info.hasState(NET::SkipTaskbar) || !info.hasState(NET::SkipPager)) { KX11Extras::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager); } } #endif this->showByWaylandHelper(); // this->raise(); // this->activateWindow(); Q_EMIT this->mainWindowVisibleChanged(true); #ifdef WITHKYSEC if (!kysec_is_disabled() && kysec_get_3adm_status() && (getuid() || geteuid())){ if (nullptr != m_wlanWidget) { m_wlanWidget->hideSetting(); } if (nullptr != m_lanWidget) { m_lanWidget->hideSetting(); } } else { if (nullptr != m_wlanWidget) { m_wlanWidget->showSetting(); } if (nullptr != m_lanWidget) { m_lanWidget->showSetting(); } } #endif } /** * @brief MainWindow::hideMainwindow 隐藏主页面时要进行的操作,后续可以添加到此函数 */ void MainWindow::hideMainwindow() { this->hide(); Q_EMIT this->mainWindowVisibleChanged(false); } /** * @brief MainWindow::setWiredDefaultDevice 设置有线设备默认网卡 */ void MainWindow::setWiredDefaultDevice(QString deviceName) { // m_lanWidget->updateDefaultDevice(deviceName); } /** * @brief MainWindow::hideMainwindow 设置无线设备默认网卡 */ void MainWindow::setWirelessDefaultDevice(QString deviceName) { // m_wlanWidget->updateDefaultDevice(deviceName); } /** * @brief MainWindow::firstlyStart 一级启动,执行重要且不耗时的启动操作 */ void MainWindow::firstlyStart() { this->setAttribute(Qt::WA_NativeWindow); initWindowProperties(); initTransparency(); registerTrayIcon(); initPanelGSettings(); initUI(); initDbusConnnect(); initWindowTheme(); initTrayIcon(); // initPlatform(); installEventFilter(this); m_secondaryStartTimer = new QTimer(this); connect(m_secondaryStartTimer, &QTimer::timeout, this, [ = ]() { m_secondaryStartTimer->stop(); secondaryStart();//满足条件后执行比较耗时的二级启动 }); m_secondaryStartTimer->start(5 * 1000); m_createPagePtrMap.clear(); m_networkMode = new NetworkMode(this); m_networkMode->initWiredNetworkMode(); m_networkMode->initWirelessNetworkMode(); //加载key ring kylinAgentInit(); } /** * @brief MainWindow::secondaryStart 二级启动,可以将较耗时的初始化操作放到此处执行 */ void MainWindow::secondaryStart() { if (m_loadFinished) return; m_loadFinished = true; } /** * @brief MainWindow::initWindowProperties 初始化平台信息 */ void MainWindow::initPlatform() { char* projectName = kdk_system_get_projectName(); QString strProjectName(projectName); free(projectName); projectName = NULL; if(v10Sp1.compare(strProjectName,Qt::CaseInsensitive) == 0) { unsigned int feature = kdk_system_get_productFeatures(); if (feature == 3) { m_isShowInCenter = true; } } else if (intel.compare(strProjectName,Qt::CaseInsensitive) == 0) { m_isShowInCenter = true; } qDebug() << "projectName" << projectName << m_isShowInCenter; } /** * @brief MainWindow::initWindowProperties 初始化一些窗口属性 */ void MainWindow::initWindowProperties() { this->windowHandle(); this->setWindowTitle(tr("kylin-nm")); this->setWindowIcon(QIcon::fromTheme("kylin-network", QIcon(":/res/x/setup.png"))); this->setFixedSize(MAINWINDOW_WIDTH, MAINWINDOW_HEIGHT); // //绘制毛玻璃特效 this->setAttribute(Qt::WA_TranslucentBackground, true); //透明 this->setFocusPolicy(Qt::NoFocus); QString platform = QGuiApplication::platformName(); if(!platform.startsWith(QLatin1String("wayland"),Qt::CaseInsensitive)) { QPainterPath path; auto rect = this->rect(); // path.addRoundedRect(rect, 12, 12); path.addRect(rect); KWindowEffects::enableBlurBehind(this->windowHandle(), true, QRegion(path.toFillPolygon().toPolygon())); //背景模糊 } } /** * @brief MainWindow::registerTrayIcon 注册托盘图标 */ void MainWindow::registerTrayIcon() { m_registerCount++; //qt6 kf6环境isSystemTrayAvailable返回flase v101没有这个逻辑 m_trayIcon = new QSystemTrayIcon(); if (nullptr == m_trayIcon) { qWarning()<< "分配空间trayIcon失败"; return ; } m_trayIcon->setIcon(QIcon::fromTheme("network-wired-signal-excellent-symbolic")); m_trayIcon->setToolTip(QString(tr("kylin-nm"))); qWarning()<< "isSystemTrayAvailable is "< 10) { m_trayIcon = new QSystemTrayIcon(); if (nullptr == m_trayIcon) { qWarning()<< "分配空间trayIcon失败"; return ; } m_trayIcon->setIcon(QIcon::fromTheme("network-wired-signal-excellent-symbolic")); m_trayIcon->setToolTip(QString(tr("kylin-nm"))); } else { if (m_registerCount <= 10) { QTimer::singleShot(m_intervalTime,[this] { registerTrayIcon(); }); } } */ } void MainWindow::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); // 反锯齿; painter.setPen(Qt::transparent); // auto rect = this->rect(); // painter.drawRoundedRect(rect, 12, 12); //窗口圆角 } bool MainWindow::eventFilter(QObject *watched, QEvent *event) { if (watched == this) { //失焦退出 if (event->type() == QEvent::ActivationChange) { if (QApplication::activeWindow() != this) { hideMainwindow(); return true; } } } return QObject::eventFilter(watched, event); } void MainWindow::initTransparency() { if(QGSettings::isSchemaInstalled(TRANSPARENCY_GSETTINGS)) { m_transGsettings = new QGSettings(TRANSPARENCY_GSETTINGS); if(m_transGsettings->keys().contains(QString("transparency"))) { m_transparency=m_transGsettings->get("transparency").toDouble() + 0.15; m_transparency = (m_transparency > 1) ? 1 : m_transparency; connect(m_transGsettings, &QGSettings::changed, this, &MainWindow::onTransChanged); } } } void MainWindow::onTransChanged() { m_transparency = m_transGsettings->get("transparency").toDouble() + 0.15; m_transparency = (m_transparency > 1) ? 1 : m_transparency; paintWithTrans(); } void MainWindow::paintWithTrans() { QPalette pal = m_centralWidget->palette(); QColor color = this->palette().base().color(); color.setAlphaF(m_transparency); pal.setColor(QPalette::Base, color); m_centralWidget->setPalette(pal); QPalette tabPal = m_centralWidget->tabBar()->palette(); tabPal.setColor(QPalette::Base, color); QColor inactiveColor = this->palette().window().color(); inactiveColor.setAlphaF(0.86 *m_transparency); tabPal.setColor(QPalette::Window, inactiveColor); m_centralWidget->tabBar()->setPalette(tabPal); } /** * @brief MainWindow::initPanelGSettings 获取任务栏位置和大小 */ void MainWindow::initPanelGSettings() { const QByteArray id(PANEL_SETTINGS); if (QGSettings::isSchemaInstalled(id)) { if (m_panelGSettings == nullptr) { m_panelGSettings = new QGSettings(id); } if (m_panelGSettings->keys().contains(PANEL_POSITION_KEY)) { m_panelPosition = m_panelGSettings->get(PANEL_POSITION_KEY).toInt(); } if (m_panelGSettings->keys().contains(PANEL_SIZE_KEY)) { m_panelSize = m_panelGSettings->get(PANEL_SIZE_KEY).toInt(); } if (m_panelGSettings->keys().contains(PANEL_TYPE_KEY)) { m_panelType = m_panelGSettings->get(PANEL_TYPE_KEY).toInt(); } else { m_panelType = 0; } if (m_panelGSettings->keys().contains(UKUI_SETTINGS_ISLAND_POSITION_KEY)) { m_settingsIslandPosition = m_panelGSettings->get(UKUI_SETTINGS_ISLAND_POSITION_KEY).toInt(); } if (m_panelGSettings->keys().contains(UKUI_TOPBAR_SIZE_KEY)) { m_topbarSize = m_panelGSettings->get(UKUI_TOPBAR_SIZE_KEY).toInt(); } connect(m_panelGSettings, &QGSettings::changed, this, [&] (const QString &key) { if (key == PANEL_SIZE_KEY) { m_panelSize = m_panelGSettings->get(PANEL_SIZE_KEY).toInt(); } else if(key == PANEL_POSITION_KEY) { m_panelPosition = m_panelGSettings->get(PANEL_SIZE_KEY).toInt(); } else if (key == PANEL_TYPE_KEY) { m_panelType = m_panelGSettings->get(PANEL_TYPE_KEY).toInt(); qDebug() << "切换任务栏类型"; // updateGeometry(); } else if (key == UKUI_SETTINGS_ISLAND_POSITION_KEY) { m_settingsIslandPosition = m_panelGSettings->get(UKUI_SETTINGS_ISLAND_POSITION_KEY).toInt(); qDebug() << "任务栏宽度切换" << m_settingsIslandPosition; // updateGeometry(); } else if (key == UKUI_TOPBAR_SIZE_KEY) { m_topbarSize = m_panelGSettings->get(UKUI_TOPBAR_SIZE_KEY).toInt(); // updateGeometry(); } resetWindowPosition(); }); } } /** * @brief MainWindow::initUI 初始化窗口内控件 */ void MainWindow::initUI() { setThemePalette(); m_centralWidget = new QTabWidget(this); this->setCentralWidget(m_centralWidget); m_centralWidget->tabBar()->setFixedWidth(this->width()+1); // m_centralWidget->tabBar()->setProperty("setRadius", 12); // m_centralWidget->tabBar()->setStyleSheet("QTabBar::tab{min-height:40px}"); m_lanWidget = new LanPage(m_centralWidget); m_wlanWidget = new WlanPage(m_centralWidget); connect(this, &MainWindow::mainWindowVisibleChanged, m_wlanWidget, &WlanPage::onMainWindowVisibleChanged); // m_centralWidget->addTab(m_lanWidget, QIcon::fromTheme("network-wired-connected-symbolic", QIcon::fromTheme("network-wired-symbolic", QIcon(":/res/l/network-online.svg"))), tr("LAN")); // m_centralWidget->addTab(m_wlanWidget, QIcon::fromTheme("network-wireless-signal-excellent-symbolic", QIcon(":/res/x/wifi-list-bg.svg")), tr("WLAN")); m_centralWidget->addTab(m_lanWidget, tr("")); m_centralWidget->addTab(m_wlanWidget,tr("")); m_tabBarLayout = new QHBoxLayout(this); m_tabBarLayout->setContentsMargins(LAYOUT_MARGINS); m_lanLabel = new QLabel(tr("LAN")); m_lanLabel->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter); m_wlanLabel = new QLabel(tr("WLAN")); m_wlanLabel->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter); m_tabBarLayout->addWidget(m_lanLabel); m_tabBarLayout->addWidget(m_wlanLabel); m_centralWidget->tabBar()->setLayout(m_tabBarLayout); m_centralWidget->tabBar()->setProperty("useTabbarSeparateLine", false); // 去掉中间的分割线 m_centralWidget->setAttribute(Qt::WA_TranslucentBackground, true); // 背景透明 解决切换黑屏问题 connect(m_centralWidget, &QTabWidget::currentChanged, m_wlanWidget, &WlanPage::onWlanPageVisibleChanged); paintWithTrans(); } /** * @brief MainWindow::initTrayIcon 初始化托盘图标和托盘右键菜单 */ void MainWindow::initTrayIcon() { loadIcons.append(QIcon::fromTheme("ukui-loading-0-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); iconTimer = new QTimer(this); connect(iconTimer, &QTimer::timeout, this, &MainWindow::onSetTrayIconLoading); m_trayIconMenu = new QMenu(); // m_showMainwindowAction = new QAction(tr("Show MainWindow"),this); m_showSettingsAction = new QAction(tr("Settings"),this); m_showConnectivityPageAction = new QAction(tr("Network Connectivity Detection"), this); m_showSettingsAction->setIcon(QIcon::fromTheme("document-page-setup-symbolic", QIcon(":/res/x/setup.png")) ); m_showConnectivityPageAction->setIcon(QIcon::fromTheme("gnome-netstatus-txrx")); // m_trayIconMenu->addAction(m_showMainwindowAction); m_trayIconMenu->addAction(m_showSettingsAction); m_trayIcon->setContextMenu(m_trayIconMenu); iconStatus = IconActiveType::LAN_CONNECTED; onRefreshTrayIcon(); connect(m_trayIcon, &QSystemTrayIcon::activated, this, &MainWindow::onTrayIconActivated); // connect(m_showMainwindowAction, &QAction::triggered, this, &MainWindow::onShowMainwindowActionTriggled); connect(m_showSettingsAction, &QAction::triggered, this, &MainWindow::onShowSettingsActionTriggled); connect(m_showConnectivityPageAction, &QAction::triggered, [=]() { if (m_connectivityPage != nullptr) { KX11Extras::forceActiveWindow(m_connectivityPage->winId()); //KWindowSystem::raiseWindow(m_connectivityPage->winId());//mqtest qt6移除待sdk说明 return; } QString uri = getConnectivityCheckSpareUriByGDbus(); m_connectivityPage = new ConnectivityPage(uri, this); connect(m_connectivityPage, &ConnectivityPage::pageClose, [&](){ m_connectivityPage = nullptr; }); m_connectivityPage->show(); }); m_trayIcon->show(); } void MainWindow::initDbusConnnect() { connect(m_lanWidget, &LanPage::deviceStatusChanged, this, &MainWindow::deviceStatusChanged); connect(m_lanWidget, &LanPage::deviceNameChanged, this, &MainWindow::deviceNameChanged); connect(m_wlanWidget, &WlanPage::wirelessDeviceStatusChanged, this, &MainWindow::wirelessDeviceStatusChanged); connect(m_wlanWidget, &WlanPage::deviceNameChanged, this, &MainWindow::deviceNameChanged); connect(m_wlanWidget, &WlanPage::wirelessSwitchBtnChanged, this, &MainWindow::wirelessSwitchBtnChanged); connect(m_wlanWidget, &WlanPage::activateFailed, this, &MainWindow::activateFailed); connect(m_wlanWidget, &WlanPage::deactivateFailed, this, &MainWindow::deactivateFailed); connect(m_lanWidget, &LanPage::activateFailed, this, &MainWindow::activateFailed); connect(m_lanWidget, &LanPage::deactivateFailed, this, &MainWindow::deactivateFailed); connect(m_lanWidget, &LanPage::lanAdd, this, &MainWindow::lanAdd); connect(m_lanWidget, &LanPage::lanRemove, this, &MainWindow::lanRemove); connect(m_lanWidget, &LanPage::lanUpdate, this, &MainWindow::lanUpdate); connect(m_lanWidget, &LanPage::lanActiveConnectionStateChanged, this, &MainWindow::lanActiveConnectionStateChanged); connect(m_lanWidget, &LanPage::lanConnectChanged, this, &MainWindow::onLanConnectStatusToChangeTrayIcon); connect(m_wlanWidget, &WlanPage::wlanAdd, this, &MainWindow::wlanAdd); connect(m_wlanWidget, &WlanPage::wlanRemove, this, &MainWindow::wlanRemove); connect(m_wlanWidget, &WlanPage::wlanActiveConnectionStateChanged, this, &MainWindow::wlanactiveConnectionStateChanged); connect(m_wlanWidget, &WlanPage::wlanConnectChanged, this, &MainWindow::onWlanConnectStatusToChangeTrayIcon); connect(m_wlanWidget, &WlanPage::hotspotDeactivated, this, &MainWindow::hotspotDeactivated); connect(m_wlanWidget, &WlanPage::hotspotActivated, this, &MainWindow::hotspotActivated); connect(m_wlanWidget, &WlanPage::secuTypeChange, this, &MainWindow::secuTypeChange); connect(m_wlanWidget, &WlanPage::signalStrengthChange, this, &MainWindow::signalStrengthChange); connect(m_wlanWidget, &WlanPage::timeToUpdate , this, &MainWindow::timeToUpdate); connect(m_wlanWidget, &WlanPage::timeToUpdate , this, &MainWindow::onTimeUpdateTrayIcon); connect(m_wlanWidget, &WlanPage::showMainWindow, this, &MainWindow::onShowMainWindow); connect(m_wlanWidget, &WlanPage::connectivityChanged, this, &MainWindow::onConnectivityChanged); connect(m_wlanWidget, &WlanPage::connectivityCheckSpareUriChanged, this, &MainWindow::onConnectivityCheckSpareUriChanged); connect(m_lanWidget, &LanPage::lanConnectChanged, this, &MainWindow::onRefreshTrayIconTooltip); connect(m_lanWidget, &LanPage::deviceStatusChanged, this, &MainWindow::onRefreshTrayIconTooltip); connect(m_wlanWidget, &WlanPage::wlanConnectChanged, this, &MainWindow::onRefreshTrayIconTooltip); connect(m_wlanWidget, &WlanPage::wirelessDeviceStatusChanged, this, &MainWindow::onRefreshTrayIconTooltip); connect(m_lanWidget, &LanPage::wiredMainSwitchBtnChanged, this, &MainWindow::wiredMainSwitchBtnChanged); //模式切换 QDBusConnection::sessionBus().connect(QString("com.kylin.statusmanager.interfacer"), QString("/"), QString("com.kylin.statusmanager.interface"), QString("mode_change_signal"), this, SLOT(onTabletModeChanged(bool))); connect(KX11Extras::self(), &KX11Extras::activeWindowChanged, this,[&](WId activeWindowId){ if (activeWindowId != this->winId() && activeWindowId != 0) { qDebug() << "tray recieve KWindowSystem activeWindowChanged" << activeWindowId << this->windowHandle(); hideMainwindow(); } }); QDBusConnection::sessionBus().connect(QString("com.kylin.network"), QString("/com/kylin/network"), QString("com.kylin.network"), QString("showKylinNMSignal"), this, SLOT(onShowKylinNMSlot(QString,int))); QDBusConnection::sessionBus().connect(QString("com.kylin.network"), QString("/com/kylin/network"), QString("com.kylin.network"), QString("showPropertyWidgetSignal"), this, SLOT(onShowPropertyWidgetSlot(QString,QString,QString))); QDBusConnection::sessionBus().connect(QString("com.kylin.network"), QString("/com/kylin/network"), QString("com.kylin.network"), QString("showCreateWiredConnectWidgetSignal"), this, SLOT(onShowCreateWiredConnectWidgetSlot(QString,QString))); QDBusConnection::sessionBus().connect(QString("com.kylin.network"), QString("/com/kylin/network"), QString("com.kylin.network"), QString("showAddOtherWlanWidgetSignal"), this, SLOT(onShowAddOtherWlanWidgetSlot(QString,QString))); } /** * @brief MainWindow::resetWindowPosition 重新计算窗口位置 */ void MainWindow::resetWindowPosition() { if (m_isShowInCenter) { QRect availableGeometry = qApp->primaryScreen()->availableGeometry(); QRect rect((availableGeometry.width() - this->width())/2, (availableGeometry.height() - this->height())/2, this->width(), this->height()); kdk::WindowManager::setGeometry(this->windowHandle(), rect); return; } #define MARGIN 8 #define PANEL_TOP 1 #define PANEL_LEFT 2 #define PANEL_RIGHT 3 //#define PANEL_BOTTOM 4 #if 0 //弃用接口 GetPrimaryScreenGeometry if (!m_positionInterface) { m_positionInterface = new QDBusInterface("org.ukui.panel", "/panel/position", "org.ukui.panel", QDBusConnection::sessionBus()); } QRect rect; QDBusReply reply = m_positionInterface->call("GetPrimaryScreenGeometry"); //reply获取的参数共5个,分别是 主屏可用区域的起点x坐标,主屏可用区域的起点y坐标,主屏可用区域的宽度,主屏可用区域高度,任务栏位置 if (!m_positionInterface->isValid() || !reply.isValid() || reply.value().size() < 5) { qCritical() << QDBusConnection::sessionBus().lastError().message(); kdk::WindowManager::setGeometry(this->windowHandle(), QRect(0, 0, this->width(), this->height())); return; } QVariantList position_list = reply.value(); int position = position_list.at(4).toInt(); switch(position){ case PANEL_TOP: //任务栏位于上方 rect = QRect(position_list.at(0).toInt() + position_list.at(2).toInt() - this->width() - MARGIN, position_list.at(1).toInt() + MARGIN, this->width(), this->height()); break; //任务栏位于左边 case PANEL_LEFT: rect = QRect(position_list.at(0).toInt() + MARGIN, position_list.at(1).toInt() + reply.value().at(3).toInt() - this->height() - MARGIN, this->width(), this->height()); break; //任务栏位于右边 case PANEL_RIGHT: rect = QRect(position_list.at(0).toInt() + position_list.at(2).toInt() - this->width() - MARGIN, position_list.at(1).toInt() + reply.value().at(3).toInt() - this->height() - MARGIN, this->width(), this->height()); break; //任务栏位于下方 default: rect = QRect(position_list.at(0).toInt() + position_list.at(2).toInt() - this->width() - MARGIN, position_list.at(1).toInt() + reply.value().at(3).toInt() - this->height() - MARGIN, this->width(), this->height()); break; } kdk::WindowManager::setGeometry(this->windowHandle(), rect); #endif QRect availableGeo = QGuiApplication::screenAt(QCursor::pos())->geometry(); int x, y; switch(m_panelPosition){ case PANEL_TOP: x = availableGeo.x() + availableGeo.width() - this->width() - MARGIN; y = availableGeo.y() + m_panelSize + MARGIN; break; case PANEL_LEFT: x = availableGeo.x() + m_panelSize + MARGIN; y = availableGeo.y() + availableGeo.height() - this->height() - MARGIN; break; case PANEL_RIGHT: x = availableGeo.x() + availableGeo.width() - m_panelSize - this->width() - MARGIN; y = availableGeo.y() + availableGeo.height() - this->height() - MARGIN; break; default: x = availableGeo.x() + availableGeo.width() - this->width() - MARGIN; y = availableGeo.y() + availableGeo.height() - m_panelSize - this->height() - MARGIN; break; } kdk::WindowManager::setGeometry(this->windowHandle(), QRect(x, y, this->width(), this->height())); qDebug() << " Position of ukui-panel is " << m_panelPosition << "; Position of mainwindow is " << this->geometry() << "." << Q_FUNC_INFO << __LINE__; } /** * @brief MainWindow::resetTrayIconTool 重新获取网络连接状态并重新设置图标和tooltip */ void MainWindow::resetTrayIconTool() { //ZJP_TODO 检测当前连接的是有线还是无线,是否可用,设置图标和tooltip,图标最好提前define // int connectivity = objKyDBus->getNetworkConectivity(); // qDebug() << "Value of current network Connectivity property : "<< connectivity; // switch (connectivity) { // case UnknownConnectivity: // case Portal: // case Limited: // setTrayIcon(iconLanOnlineNoInternet); // trayIcon->setToolTip(QString(tr("Network Connected But Can Not Access Internet"))); // break; // case NoConnectivity: // case Full: // setTrayIcon(iconLanOnline); // trayIcon->setToolTip(QString(tr("kylin-nm"))); // break; // } qDebug() << "Has set tray icon to be XXX." << Q_FUNC_INFO << __LINE__; } /** * @brief MainWindow::initWindowTheme 初始化窗口主题并创建信号槽 */ void MainWindow::initWindowTheme() { const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { m_styleGsettings = new QGSettings(style_id); // resetWindowTheme(); connect(m_styleGsettings, &QGSettings::changed, this, &MainWindow::onThemeChanged); } else { qWarning() << "Gsettings interface \"org.ukui.style\" is not exist!" << Q_FUNC_INFO << __LINE__; } } /** * @brief MainWindow::resetWindowTheme 读取和设置窗口主题 */ void MainWindow::resetWindowTheme() { if (!m_styleGsettings) { return; } QString currentTheme = m_styleGsettings->get(COLOR_THEME).toString(); auto app = static_cast(QCoreApplication::instance()); if(currentTheme == "ukui-dark" || currentTheme == "ukui-black"){ app->setStyle(new CustomStyle("ukui-dark")); qDebug() << "Has set color theme to ukui-dark." << Q_FUNC_INFO << __LINE__; Q_EMIT qApp->paletteChanged(qApp->palette()); return; } app->setStyle(new CustomStyle("ukui-light")); qDebug() << "Has set color theme to " << currentTheme << Q_FUNC_INFO << __LINE__; Q_EMIT qApp->paletteChanged(qApp->palette()); return; } /** * @brief MainWindow::showControlCenter 打开控制面板网络界面 */ void MainWindow::slideWindowByPanelPosition() { if (m_panelType == 1) { if (m_settingsIslandPosition) { KWindowEffects::slideWindow(this->windowHandle(), KWindowEffects::TopEdge); } else { KWindowEffects::slideWindow(this->windowHandle(), KWindowEffects::BottomEdge); } } else { switch(m_panelPosition) { case PANEL_TOP: KWindowEffects::slideWindow(this->windowHandle(), KWindowEffects::TopEdge); break; case PANEL_LEFT: KWindowEffects::slideWindow(this->windowHandle(), KWindowEffects::LeftEdge); break; case PANEL_RIGHT: KWindowEffects::slideWindow(this->windowHandle(), KWindowEffects::RightEdge); break; case PANEL_BOTTOM: KWindowEffects::slideWindow(this->windowHandle(), KWindowEffects::BottomEdge); break; } } } void MainWindow::showByWaylandHelper() { //设置窗体位置,传入参数为QWindow*,QRect //跳过任务栏和分页器的属性 kdk::WindowManager::setSkipSwitcher(this->windowHandle(), true); kdk::WindowManager::setSkipTaskBar(this->windowHandle(), true); const KWindowInfo info(this->winId(), NET::WMState); if (!info.hasState(NET::SkipTaskbar) || !info.hasState(NET::SkipPager) || !info.hasState(NET::SkipSwitcher)) KX11Extras::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager | NET::SkipSwitcher); this->show(); this->setFocus(); //跳过任务栏和分页器的属性 kdk::WindowManager::setSkipSwitcher(this->windowHandle(), true); kdk::WindowManager::setSkipTaskBar(this->windowHandle(), true); if (!info.hasState(NET::SkipTaskbar) || !info.hasState(NET::SkipPager) || !info.hasState(NET::SkipSwitcher)) KX11Extras::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager | NET::SkipSwitcher); //滑动弹出和窗口位置需在show函数之后调用才可正常处理窗口位置 slideWindowByPanelPosition(); resetWindowPosition(); } void MainWindow::setCentralWidgetType(IconActiveType iconStatus) { if (iconStatus == WLAN_CONNECTED || iconStatus == WLAN_CONNECTED_LIMITED) { m_centralWidget->setCurrentIndex(WLAN_PAGE_INDEX); } else if (iconStatus == ACTIVATING) { if (m_wlanWidget->checkWlanStatus(NetworkManager::ActiveConnection::State::Activating)) { m_centralWidget->setCurrentIndex(WLAN_PAGE_INDEX); } else { m_centralWidget->setCurrentIndex(LAN_PAGE_INDEX); } } else { m_centralWidget->setCurrentIndex(LAN_PAGE_INDEX); } } /** * @brief MainWindow::assembleTrayIconTooltip 整理托盘图标tooltip内容 * @param map <网卡名,网络状态> * @param tip tooltip */ void MainWindow::assembleTrayIconTooltip(QMap &map, QString &tip) { if (map.isEmpty()) { tip = QString(tr("Network tool")); return; } QMap::iterator iter = map.begin(); if (map.size() == 1) { tip = map.value(iter.key()); if (tip.indexOf(":")) { tip = tip.mid(tip.indexOf(":") + 2); //单网卡显示时去掉“已连接: ”字样 } } else if (map.size() > 1) { tip = ""; int count = 0; while (iter != map.end()) { count += 1; tip += QString(tr("Network Card")) + QString("%1").arg(count) + "\n" + map.value(iter.key()); ++iter; if (iter != map.end()) { tip += "\n"; } } } } void MainWindow::setThemePalette() { QPalette pal = qApp->palette(); QGSettings * styleGsettings = nullptr; const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { styleGsettings = new QGSettings(style_id, QByteArray(), this); QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = themePalette(true, this); } } this->setPalette(pal); } /** * @brief MainWindow::onTrayIconActivated 点击托盘图标的槽函数 */ void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) { setCentralWidgetType(iconStatus); if (reason == QSystemTrayIcon::ActivationReason::Context) { m_trayIconMenu->popup(QCursor::pos()); } else { if (this->isVisible()) { qDebug() << "Received signal of tray icon activated, will hide mainwindow." << Q_FUNC_INFO << __LINE__; hideMainwindow(); return; } qDebug() << "Received signal of tray icon activated, will show mainwindow." << Q_FUNC_INFO << __LINE__; // this->showMainwindow(); QDBusInterface iface("org.ukui.Sidebar", "/org/ukui/Sidebar", "org.ukui.Sidebar", QDBusConnection::sessionBus()); iface.asyncCall("shortcutWidgetActive", "org.ukui.shortcut.network", false); } } void MainWindow::onShowMainwindowActionTriggled() { showMainwindow(); } void MainWindow::onShowSettingsActionTriggled() { showControlCenter(); } void MainWindow::onThemeChanged(const QString &key) { if (key == COLOR_THEME) { qDebug() << "Received signal of theme changed, will reset theme." << Q_FUNC_INFO << __LINE__; // resetWindowTheme(); setThemePalette(); paintWithTrans(); Q_EMIT qApp->paletteChanged(qApp->palette()); } else if ("themeColor" == key) { setThemePalette(); } else { qDebug() << "Received signal of theme changed, key=" << key << " will do nothing." << Q_FUNC_INFO << __LINE__; } } void MainWindow::onRefreshTrayIcon() { //更新托盘图标显示 int signalStrength = 0; iconTimer->stop(); if (m_lanWidget->lanIsConnected()) { m_trayIcon->setIcon(QIcon::fromTheme("network-wired-connected-symbolic")); iconStatus = IconActiveType::LAN_CONNECTED; } else if (m_wlanWidget->checkWlanStatus(NetworkManager::ActiveConnection::State::Activated)){ // m_trayIcon->setIcon(QIcon::fromTheme("network-wireless-connected-symbolic")); signalStrength = m_wlanWidget->getActivateWifiSignal(m_wlanWidget->getCurrentDisplayDevice()); if (signalStrength == -1) { signalStrength = m_wlanWidget->getActivateWifiSignal(); } iconStatus = IconActiveType::WLAN_CONNECTED; } else { m_trayIcon->setIcon(QIcon::fromTheme("network-wired-disconnected-symbolic")); iconStatus = IconActiveType::NOT_CONNECTED; } NetworkManager::Connectivity connecttivity; m_wlanWidget->getConnectivity(connecttivity); if (connecttivity != NetworkManager::Connectivity::Full) { if (iconStatus == IconActiveType::LAN_CONNECTED) { m_trayIcon->setIcon(QIcon::fromTheme("network-error-symbolic")); iconStatus = IconActiveType::LAN_CONNECTED_LIMITED; } else if (iconStatus == IconActiveType::WLAN_CONNECTED) { //todo 信号强度 // m_trayIcon->setIcon(QIcon::fromTheme("network-wireless-signal-excellent-error-symbolic")); iconStatus = IconActiveType::WLAN_CONNECTED_LIMITED; } } if (iconStatus == IconActiveType::WLAN_CONNECTED || iconStatus == IconActiveType::WLAN_CONNECTED_LIMITED) { if (signalStrength > MW_EXCELLENT_SIGNAL){ m_trayIcon->setIcon(QIcon::fromTheme(EXCELLENT_SIGNAL_ICON)); } else if (signalStrength > MW_GOOD_SIGNAL) { m_trayIcon->setIcon(QIcon::fromTheme(GOOD_SIGNAL_ICON)); } else if (signalStrength > MW_OK_SIGNAL) { m_trayIcon->setIcon(QIcon::fromTheme(OK_SIGNAL_ICON)); } else if (signalStrength > MW_LOW_SIGNAL) { m_trayIcon->setIcon(QIcon::fromTheme(LOW_SIGNAL_ICON)); } else { m_trayIcon->setIcon(QIcon::fromTheme(NONE_SIGNAL_ICON)); } } else if (iconStatus == IconActiveType::WLAN_CONNECTED_LIMITED) { if (signalStrength > MW_EXCELLENT_SIGNAL){ m_trayIcon->setIcon(QIcon::fromTheme(EXCELLENT_SIGNAL_LIMIT_ICON)); } else if (signalStrength > MW_GOOD_SIGNAL) { m_trayIcon->setIcon(QIcon::fromTheme(GOOD_SIGNAL_LIMIT_ICON)); } else if (signalStrength > MW_OK_SIGNAL) { m_trayIcon->setIcon(QIcon::fromTheme(OK_SIGNAL_LIMIT_ICON)); } else if (signalStrength > MW_LOW_SIGNAL) { m_trayIcon->setIcon(QIcon::fromTheme(LOW_SIGNAL_LIMIT_ICON)); } else { m_trayIcon->setIcon(QIcon::fromTheme(NONE_SIGNAL_LIMIT_ICON)); } } if(!getConnectivityCheckSpareUriByGDbus().isEmpty()) { if (iconStatus == IconActiveType::LAN_CONNECTED) { m_trayIcon->setIcon(QIcon::fromTheme("network-intranet-symbolic")); } else if (iconStatus == IconActiveType::WLAN_CONNECTED) { if (signalStrength > MW_EXCELLENT_SIGNAL){ m_trayIcon->setIcon(QIcon::fromTheme(EXCELLENT_SIGNAL_INTRANET_ICON)); } else if (signalStrength > MW_GOOD_SIGNAL) { m_trayIcon->setIcon(QIcon::fromTheme(GOOD_SIGNAL_INTRANET_ICON)); } else if (signalStrength > MW_OK_SIGNAL) { m_trayIcon->setIcon(QIcon::fromTheme(OK_SIGNAL_INTRANET_ICON)); } else if (signalStrength > MW_LOW_SIGNAL) { m_trayIcon->setIcon(QIcon::fromTheme(LOW_SIGNAL_INTRANET_ICON)); } else { m_trayIcon->setIcon(QIcon::fromTheme(NONE_SIGNAL_INTRANET_ICON)); } } } if (signalStrength == -1) { m_trayIcon->setIcon(QIcon::fromTheme("network-wired-disconnected-symbolic")); } onRefreshTrayIconTooltip(); if (iconStatus > IconActiveType::NOT_CONNECTED) { m_trayIconMenu->addAction(m_showConnectivityPageAction); } else { m_trayIconMenu->removeAction(m_showConnectivityPageAction); } } void MainWindow::onSetTrayIconLoading() { if (currentIconIndex > 7) { currentIconIndex = 0; } m_trayIcon->setIcon(loadIcons.at(currentIconIndex)); iconStatus = IconActiveType::ACTIVATING; currentIconIndex ++; } void MainWindow::onConnectStatusToChangeTrayIcon(int state) { if (state == 1 || state == 3){ iconStatus = IconActiveType::ACTIVATING; iconTimer->start(LOADING_TRAYICON_TIMER_MS); } else { if (!m_wlanWidget->checkInternetLoading()) { onRefreshTrayIcon(); } } } void MainWindow::onLanConnectStatusToChangeTrayIcon(int state) { qDebug() << "lan state:" << state << Q_FUNC_INFO << __LINE__; if (state==1 || state==3){ m_lanIsLoading = true; iconTimer->start(LOADING_TRAYICON_TIMER_MS); } else { m_lanIsLoading = false; if (m_wlanIsLoading == false) { onRefreshTrayIcon(); } } } void MainWindow::onWlanConnectStatusToChangeTrayIcon(int state) { qDebug() << "wlan state:" << state << Q_FUNC_INFO << __LINE__; if (state==1 || state==3){ m_wlanIsLoading = true; iconTimer->start(LOADING_TRAYICON_TIMER_MS); } else { if (m_wlanWidget->checkWlanStatus(NetworkManager::ActiveConnection::State::Activating)) { return; } m_wlanIsLoading = false; if (m_lanIsLoading == false) { onRefreshTrayIcon(); } } } void MainWindow::onTabletModeChanged(bool mode) { qDebug() << "TabletMode change" << mode; Q_UNUSED(mode) //模式切换时,隐藏主界面 hideMainwindow(); } /** * @brief MainWindow::onRefreshTrayIconTooltip 根据托盘图标调整其tooltip */ void MainWindow::onRefreshTrayIconTooltip() { if (!m_trayIcon) { return; } QString trayIconToolTip = ""; QMap lanMap; QMap wlanMap; switch(iconStatus) { case IconActiveType::NOT_CONNECTED: trayIconToolTip = QString(tr("Not connected to the network")); break; case LAN_CONNECTED: case IconActiveType::LAN_CONNECTED_LIMITED: m_lanWidget->getWiredDeviceConnectState(lanMap); assembleTrayIconTooltip(lanMap, trayIconToolTip); break; case IconActiveType::WLAN_CONNECTED: case IconActiveType::WLAN_CONNECTED_LIMITED: m_wlanWidget->getWirelssDeviceConnectState(wlanMap); assembleTrayIconTooltip(wlanMap, trayIconToolTip); break; case IconActiveType::ACTIVATING: default: trayIconToolTip = QString(tr("Network tool")); break; } m_trayIcon->setToolTip(trayIconToolTip); } void MainWindow::onPrimaryScreenChanged() { QTimer::singleShot(500, this, [=](){ if (this->isVisible()) { resetWindowPosition(); } }); } void MainWindow::onShowMainWindow(int type) { if (type == LANPAGE || type == WLANPAGE) { m_centralWidget->setCurrentIndex(type); if(QApplication::activeWindow() != this) { this->showMainwindow(); } } else if (type == AUTOSELET) { onTrayIconActivated(QSystemTrayIcon::ActivationReason::Trigger); } else { qWarning() << "unsupport parameter"; } } void MainWindow::onConnectivityChanged(NetworkManager::Connectivity connectivity) { if (!m_trayIcon) { return; } if (iconStatus == ACTIVATING) { return; } onRefreshTrayIcon(); } void MainWindow::onConnectivityCheckSpareUriChanged() { if (!m_trayIcon) { return; } if (iconStatus == ACTIVATING) { return; } onRefreshTrayIcon(); } void MainWindow::onTimeUpdateTrayIcon() { if (!m_trayIcon) { return; } if (iconStatus == ACTIVATING || (iconStatus != WLAN_CONNECTED && iconStatus != WLAN_CONNECTED_LIMITED)) { return; } onRefreshTrayIcon(); } /** * @brief MainWindow::keyPressEvent 按esc键关闭主界面 * @param event */ void MainWindow::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Escape) { hideMainwindow(); } return QWidget::keyPressEvent(event); } /** * @brief MainWindow::getWirelessList 获取wifi列表,供dbus调用 * @param devName * @param list */ void MainWindow::getWirelessList(QString devName, QList &list) { list.clear(); if (nullptr != m_wlanWidget) { m_wlanWidget->getWirelessList(devName, list); } } bool MainWindow::getWirelessSwitchBtnState() { if (nullptr != m_wlanWidget) { return m_wlanWidget->getWirelessSwitchBtnState(); } } bool MainWindow::getWiredEnabledState() { if (nullptr != m_lanWidget) { return m_lanWidget->getWiredEnabledState(); } } bool MainWindow::getCableStateByDevice(const QString &deviceName) { if (nullptr != m_lanWidget) { return m_lanWidget->getCableStateByDevice(deviceName); } } int MainWindow::getDeviceConnectivity(const QString deviceName) { if (nullptr != m_lanWidget) { return m_lanWidget->getDeviceConnectivity(deviceName); } } /** * @brief MainWindow::getWiredList 获取lan列表,供dbus调用 * @param map */ void MainWindow::getWiredList(QString devName, QList &list) { list.clear(); if (nullptr != m_lanWidget) { m_lanWidget->getWiredList(devName, list); } } /** * @brief MainWindow::activeWirelessAp 开启热点,供dbus调用 * @param apName * @param apPassword * @param apDevice */ void MainWindow::activeWirelessAp(const QString apName, const QString apPassword, const QString band, const QString apDevice) { m_wlanWidget->activeWirelessAp(apName, apPassword, band, apDevice); } /** * @brief MainWindow::activeWirelessAp 断开热点,供dbus调用 * @param apName */ void MainWindow::deactiveWirelessAp(const QString apName, const QString uuid) { m_wlanWidget->deactiveWirelessAp(apName, uuid); } /** * @brief MainWindow::activeWirelessAp 获取热点,供dbus调用 * @param list */ void MainWindow::getApInfoBySsid(QString devName, QString ssid, QStringList &list) { m_wlanWidget->getApInfoBySsid(devName, ssid, list); } void MainWindow::getStoredApInfo(QStringList &list) { m_wlanWidget->getStoredApInfo(list); } void MainWindow::getApConnectionPath(QString &path, QString uuid) { m_wlanWidget->getApConnectionPath(path, uuid); } void MainWindow::getActiveConnectionPath(QString &path, QString uuid) { m_wlanWidget->getActiveConnectionPath(path, uuid); } //无线开关 void MainWindow::setWirelessSwitchEnable(bool enable) { m_wlanWidget->setWirelessSwitchEnable(enable); } void MainWindow::setWiredEnableStatus(bool enable) { m_lanWidget->setWiredEnabledState(enable); } void MainWindow::setWiredDeviceEnable(const QString& devName, bool enable) { m_lanWidget->setWiredDeviceEnable(devName, enable); } void MainWindow::showPropertyWidget(QString devName, QString ssid) { KyNetworkDeviceResourse *devResourse = new KyNetworkDeviceResourse(); QStringList wiredDeviceList; wiredDeviceList.clear(); devResourse->getNetworkDeviceList(NetworkManager::Device::Type::Ethernet, wiredDeviceList); if (wiredDeviceList.contains(devName)) { qDebug() << "showPropertyWidget device type wired device name " << devName << " uuid " << ssid; m_lanWidget->showDetailPage(devName, ssid); delete devResourse; devResourse = nullptr; return; } QStringList wirelessDeviceList; wirelessDeviceList.clear(); devResourse->getNetworkDeviceList(NetworkManager::Device::Type::Wifi, wirelessDeviceList); if (wirelessDeviceList.contains(devName)) { qDebug() << "showPropertyWidget device type wireless device name " << devName << " ssid " << ssid; m_wlanWidget->showDetailPage(devName, ssid); delete devResourse; devResourse = nullptr; return; } qWarning() << "showPropertyWidget no such device " << devName; delete devResourse; devResourse = nullptr; } void MainWindow::showCreateWiredConnectWidget(const QString devName) { qDebug() << "showCreateWiredConnectWidget! devName = " << devName; if (m_createPagePtrMap.contains(devName)) { if (m_createPagePtrMap[devName] != nullptr) { qDebug() << "showCreateWiredConnectWidget" << devName << "already create,just raise"; KX11Extras::forceActiveWindow(m_createPagePtrMap[devName]->winId()); //KWindowSystem::raiseWindow(m_createPagePtrMap[devName]->winId());////mqtest qt6移除待sdk说明 return; } } NetDetail *netDetail = new NetDetail(devName, "", "", false, false, true,0,this); connect(netDetail, &NetDetail::createPageClose, [&](QString interfaceName){ if (m_createPagePtrMap.contains(interfaceName)) { m_createPagePtrMap[interfaceName] = nullptr; } }); m_createPagePtrMap.insert(devName, netDetail); netDetail->show(); } void MainWindow::showAddOtherWlanWidget(QString devName) { qDebug() << "showAddOtherWlanWidget! devName = " << devName; m_wlanWidget->showAddOtherPage(devName); } void MainWindow::getWirelessDeviceCap(QMap &map) { m_wlanWidget->getWirelessDeviceCap(map); } //有线连接断开 void MainWindow::activateWired(const QString& devName, const QString& connUuid) { m_lanWidget->activateWired(devName, connUuid); } void MainWindow::deactivateWired(const QString& devName, const QString& connUuid, bool concise) { m_lanWidget->deactivateWired(devName, connUuid, concise); } void MainWindow::setWiredDeviceAutoconnect(const QString& devName, bool state) { m_lanWidget->setWiredDeviceAutoconnect(devName, state); } void MainWindow::deleteWiredConnect(int type, const QString& connUuid) { qDebug() << Q_FUNC_INFO << __LINE__ << type << connUuid; if (type == 0) m_lanWidget->deleteWiredConnect(connUuid); } //无线连接断开 void MainWindow::activateWireless(const QString& devName, const QString& ssid) { m_wlanWidget->activateWirelessConnection(devName, ssid); } void MainWindow::deactivateWireless(const QString& devName, const QString& ssid) { m_wlanWidget->deactivateWirelessConnection(devName, ssid); } void MainWindow::deleteWireleeConnect(int type, const QString& connUuid) { qDebug() << Q_FUNC_INFO << __LINE__ << type << connUuid; if (type == 1) m_wlanWidget->deleteWirelessConnect(connUuid); } void MainWindow::rescan() { m_wlanWidget->requestScan(); } void MainWindow::passwordConnect(QString devName, QString ssid, QString type, QString psk, bool autoConnect) { KyWirelessConnectOperation m_wirelessConnectOperation; KyWirelessConnectSetting settings; settings.m_connectName = ssid; settings.m_ssid = ssid; settings.isAutoConnect = autoConnect; settings.m_psk = psk; if (type.isEmpty() || type == "") { settings.m_type = WpaNone; } else if (type.contains("WPA1") || type.contains("WPA2")) { settings.m_type = WpaPsk; } else if (type.contains("WPA3")) { settings.m_type = SAE; } m_wirelessConnectOperation.addAndActiveWirelessConnect(devName, settings, false); } void MainWindow::keyRingInit() { agent_init(); qDebug()<lanIsConnected() && m_wlanWidget->checkWlanStatus(NetworkManager::ActiveConnection::State::Activated)){ process.startDetached("ukui-control-center", QStringList() << "-m" << "wlanconnect"); } else { process.startDetached("ukui-control-center", QStringList() << "-m" << "netconnect"); } } /*弹窗时机应该自洽,原方案两个包之间会通过dbus交互,登录锁屏前端容易崩,直接使用后端锁屏与否的信号来决定是否在桌面注册弹窗*/ void MainWindow::kylinAgentInit() { bool lockState = false; QDBusInterface dbusInterface("org.ukui.ScreenSaver", "/", "org.ukui.ScreenSaver", QDBusConnection::sessionBus()); if (!dbusInterface.isValid()) { qWarning()<无线 后面拓展 */ void MainWindow::netCtrlDiscon(QMap lanMap,QMap wlanMap) { NetworkManager::Connection::Ptr connectPtr; int priority=0; int maxPriority=0; QString maxDevName; QString maxUuid; int fristFlag=1,haveWireCon=0; /*多连接有线只保留优先级最高的一个连接*/ if(lanMap.size()) { for (auto itLan=lanMap.cbegin();itLan != lanMap.cend(); ++itLan) { QString key = itLan.key(); QString uuid = itLan.value(); connectPtr =NetworkManager::findConnectionByUuid(uuid); if(connectPtr.isNull() || connectPtr->settings().isNull()) { continue; } priority = connectPtr->settings()->autoconnectPriority(); /*缓存连接*/ if(fristFlag) { maxDevName=key; maxUuid=uuid; maxPriority=priority; fristFlag=0; continue; } if(maxPrioritydeactivateWired(maxDevName,maxUuid); maxDevName=key; maxUuid=uuid; maxPriority=priority; } else { m_lanWidget->deactivateWired(key,uuid); } } haveWireCon=1;//有有线连接需要全部关掉 } else { haveWireCon=0;//无有线连接需要保留一个无线 } maxDevName.clear(); maxUuid.clear(); maxPriority=0; fristFlag=1; if(wlanMap.size()) { for (auto itWlan = wlanMap.cbegin(); itWlan != wlanMap.cend(); ++itWlan) { QString key = itWlan.key(); QString uuid = itWlan.value(); connectPtr =NetworkManager::findConnectionByUuid(uuid); if(connectPtr.isNull() || connectPtr->settings().isNull()) { continue; } priority = connectPtr->settings()->autoconnectPriority(); if(haveWireCon) { m_wlanWidget->deactivateWirelessConnectionWithUuid(key,uuid); continue; } /*缓存连接*/ if(fristFlag) { maxDevName=key; maxUuid=uuid; maxPriority=priority; fristFlag=0; continue; } if(maxPrioritydeactivateWirelessConnectionWithUuid(maxDevName,maxUuid); maxDevName=key; maxUuid=uuid; maxPriority=priority; } else { m_wlanWidget->deactivateWirelessConnectionWithUuid(key,uuid); } } } } /*禁止双跨时虽然后端做了连接限制,但是开始在没打开管控规则时可能存在多个连接已经连上的情况,在打开管控规则时应该要主动断开*/ void MainWindow::updateNetCtrl(QString modName,QVariantMap value) { QMap lanMap; QMap wlanMap; bool enable=false; if(modName!="Connect") return; qInfo()<getWiredDeviceConnect(lanMap); m_wlanWidget->getWirelssDeviceConnect(wlanMap); /*禁止双跨时主动断开*/ netCtrlDiscon(lanMap,wlanMap); return; } void MainWindow::initNetCtrl() { QVariantMap map; int errCode=0; QString netCtrlConnectName="Connect"; /* QDBusReply reply = m_interface->call(QStringLiteral("getNetContrlRule"),netCtrlConnectName);//不能使用该接口,获取不到数据 if (!reply.isValid()) { qWarning() << "D-Bus call failed:" << reply.error().message(); } */ QDBusInterface dbusInterface("com.kylin.networkCtrol", "/com/kylin/networkCtrol", "com.kylin.networkCtrol", QDBusConnection::systemBus()); if (!dbusInterface.isValid()) { qWarning()<=2) { const QDBusArgument &dbusArg1st = result.arguments().at( 0 ).value(); dbusArg1st >> map; errCode = result.arguments().at( 1 ).toInt(); qInfo()<<"mainwindows"<(option)) { switch (tab->shape) { case QTabBar::RoundedNorth: case QTabBar::RoundedSouth: { return size + QSize(50,0); break; } case QTabBar::RoundedWest: case QTabBar::RoundedEast: { return size + QSize(0,50); break; } default: { break; } } } return size; break; } default: { break; } } return QProxyStyle::sizeFromContents(type, option, contentsSize, widget); } void CustomStyle::drawControl(QStyle::ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { // switch (element) { // case CE_TabBarTab: { // if (QStyle::State_Selected != option->state) { // painter->save(); // painter->setBrush(QColor(0,0,0,0)); // painter->drawRect(widget->rect()); //// painter->setOpacity(0.1); // painter->restore(); // } // break; // } // default: { // break; // } // } return QProxyStyle::drawControl(element, option, painter, widget); } //void CustomStyle::drawComplexControl(QStyle::ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget) const //{ // return QProxyStyle::drawComplexControl(control, option, painter, widget); //} //void CustomStyle::drawItemPixmap(QPainter *painter, const QRect &rectangle, int alignment, const QPixmap &pixmap) const //{ // return QProxyStyle::drawItemPixmap(painter, rectangle, alignment, pixmap); //} //void CustomStyle::drawItemText(QPainter *painter, const QRect &rectangle, int alignment, const QPalette &palette, bool enabled, const QString &text, QPalette::ColorRole textRole) const //{ // return QProxyStyle::drawItemText(painter, rectangle, alignment, palette, enabled, text, textRole); //} //void CustomStyle::drawPrimitive(QStyle::PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const //{ // return QProxyStyle::drawPrimitive(element, option, painter, widget); //} //QPixmap CustomStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *option) const //{ // return QProxyStyle::generatedIconPixmap(iconMode, pixmap, option); //} //QStyle::SubControl CustomStyle::hitTestComplexControl(QStyle::ComplexControl control, const QStyleOptionComplex *option, const QPoint &position, const QWidget *widget) const //{ // return QProxyStyle::hitTestComplexControl(control, option, position, widget); //} //QRect CustomStyle::itemPixmapRect(const QRect &rectangle, int alignment, const QPixmap &pixmap) const //{ // return QProxyStyle::itemPixmapRect(rectangle, alignment, pixmap); //} //QRect CustomStyle::itemTextRect(const QFontMetrics &metrics, const QRect &rectangle, int alignment, bool enabled, const QString &text) const //{ // return QProxyStyle::itemTextRect(metrics, rectangle, alignment, enabled, text); //} //int CustomStyle::pixelMetric(QStyle::PixelMetric metric, const QStyleOption *option, const QWidget *widget) const //{ // return QProxyStyle::pixelMetric(metric, option, widget); //} //void CustomStyle::polish(QWidget *widget) //{ // return QProxyStyle::polish(widget); //} //void CustomStyle::polish(QApplication *application) //{ // return QProxyStyle::polish(application); //} //void CustomStyle::polish(QPalette &palette) //{ // return QProxyStyle::polish(palette); //} //void CustomStyle::unpolish(QWidget *widget) //{ // return QProxyStyle::unpolish(widget); //} //void CustomStyle::unpolish(QApplication *application) //{ // return QProxyStyle::unpolish(application); //} //QIcon CustomStyle::standardIcon(QStyle::StandardPixmap standardIcon, const QStyleOption *option, const QWidget *widget) const //{ // return QProxyStyle::standardIcon(standardIcon, option, widget); //} //QPalette CustomStyle::standardPalette() const //{ // return QProxyStyle::standardPalette(); //} //int CustomStyle::styleHint(QStyle::StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const //{ // return QProxyStyle::styleHint(hint, option, widget, returnData); //} //QRect CustomStyle::subControlRect(QStyle::ComplexControl control, const QStyleOptionComplex *option, QStyle::SubControl subControl, const QWidget *widget) const //{ // return QProxyStyle::subControlRect(control, option, subControl, widget); //} //QRect CustomStyle::subElementRect(QStyle::SubElement element, const QStyleOption *option, const QWidget *widget) const //{ // return QProxyStyle::subElementRect(element, option, widget); //} kylin-nm/src/frontend/xatom/0000775000175000017500000000000015167651420015003 5ustar fengfengkylin-nm/src/frontend/xatom/xatom-helper.cpp0000664000175000017500000001641015167651420020116 0ustar fengfeng/* * KWin Style UKUI * * Copyright (C) 2020, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: Yue Lan * */ #include #include #include #include #include "xatom-helper.h" static XAtomHelper *global_instance = nullptr; XAtomHelper *XAtomHelper::getInstance() { if(!global_instance) global_instance = new XAtomHelper; return global_instance; } bool XAtomHelper::isFrameLessWindow(int winId) { auto hints = getInstance()->getWindowMotifHint(winId); if(hints.flags == MWM_HINTS_DECORATIONS && hints.functions == 1) { return true; } return false; } bool XAtomHelper::isWindowDecorateBorderOnly(int winId) { return isWindowMotifHintDecorateBorderOnly(getInstance()->getWindowMotifHint(winId)); } bool XAtomHelper::isWindowMotifHintDecorateBorderOnly(const MotifWmHints &hint) { bool isDeco = false; if(hint.flags & MWM_HINTS_DECORATIONS && hint.flags != MWM_HINTS_DECORATIONS) { if(hint.decorations == MWM_DECOR_BORDER) isDeco = true; } return isDeco; } bool XAtomHelper::isUKUICsdSupported() { // fixme: return false; } bool XAtomHelper::isUKUIDecorationWindow(int winId) { if(m_ukuiDecorationAtion == None) return false; Atom type; int format; ulong nitems; ulong bytes_after; uchar *data; Display *display=nullptr; bool isUKUIDecoration = false; if(auto *x11Application=qGuiApp->nativeInterface()) { display=x11Application->display(); XGetWindowProperty(display, winId, m_ukuiDecorationAtion, 0, LONG_MAX, false, m_ukuiDecorationAtion, &type, &format, &nitems, &bytes_after, &data); } if(type == m_ukuiDecorationAtion) { if(nitems == 1) { isUKUIDecoration = data[0]; } } return isUKUIDecoration; } UnityCorners XAtomHelper::getWindowBorderRadius(int winId) { UnityCorners corners; Atom type; int format; ulong nitems; ulong bytes_after; uchar *data; Display *display=nullptr; if(m_unityBorderRadiusAtom != None) { if(auto *x11Application=qGuiApp->nativeInterface()) { display=x11Application->display(); XGetWindowProperty(display, winId, m_unityBorderRadiusAtom, 0, LONG_MAX, false, XA_CARDINAL, &type, &format, &nitems, &bytes_after, &data); if(type == XA_CARDINAL) { if(nitems == 4) { corners.topLeft = static_cast(data[0]); corners.topRight = static_cast(data[1 * sizeof(ulong)]); corners.bottomLeft = static_cast(data[2 * sizeof(ulong)]); corners.bottomRight = static_cast(data[3 * sizeof(ulong)]); } XFree(data); } } } return corners; } void XAtomHelper::setWindowBorderRadius(int winId, const UnityCorners &data) { Display *display=nullptr; if(m_unityBorderRadiusAtom == None) return; ulong corners[4] = {data.topLeft, data.topRight, data.bottomLeft, data.bottomRight}; if(auto *x11Application=qGuiApp->nativeInterface()) { display=x11Application->display(); XChangeProperty(display, winId, m_unityBorderRadiusAtom, XA_CARDINAL, 32, XCB_PROP_MODE_REPLACE, (const unsigned char *) &corners, sizeof(corners) / sizeof(corners[0])); } } void XAtomHelper::setWindowBorderRadius(int winId, int topLeft, int topRight, int bottomLeft, int bottomRight) { Display *display=nullptr; if(m_unityBorderRadiusAtom == None) return; ulong corners[4] = {(ulong)topLeft, (ulong)topRight, (ulong)bottomLeft, (ulong)bottomRight}; if(auto *x11Application=qGuiApp->nativeInterface()) { display=x11Application->display(); XChangeProperty(display, winId, m_unityBorderRadiusAtom, XA_CARDINAL, 32, XCB_PROP_MODE_REPLACE, (const unsigned char *) &corners, sizeof(corners) / sizeof(corners[0])); } } void XAtomHelper::setUKUIDecoraiontHint(int winId, bool set) { Display *display=nullptr; if(m_ukuiDecorationAtion == None) return; if(auto *x11Application=qGuiApp->nativeInterface()) { display=x11Application->display(); XChangeProperty(display, winId, m_ukuiDecorationAtion, m_ukuiDecorationAtion, 32, XCB_PROP_MODE_REPLACE, (const unsigned char *) &set, 1); } } void XAtomHelper::setWindowMotifHint(int winId, const MotifWmHints &hints) { Display *display=nullptr; if(m_unityBorderRadiusAtom == None) return; if(auto *x11Application=qGuiApp->nativeInterface()) { display=x11Application->display(); XChangeProperty(display, winId, m_motifWMHintsAtom, m_motifWMHintsAtom, 32, XCB_PROP_MODE_REPLACE, (const unsigned char *)&hints, sizeof(MotifWmHints) / sizeof(ulong)); } } MotifWmHints XAtomHelper::getWindowMotifHint(int winId) { MotifWmHints hints; Display *display=nullptr; if(m_unityBorderRadiusAtom == None) return hints; uchar *data; Atom type; int format; ulong nitems; ulong bytes_after; if(auto *x11Application=qGuiApp->nativeInterface()) { display=x11Application->display(); XGetWindowProperty(display, winId, m_motifWMHintsAtom, 0, sizeof(MotifWmHints) / sizeof(long), false, AnyPropertyType, &type, &format, &nitems, &bytes_after, &data); } if(type == None) { return hints; } else { hints = *(MotifWmHints *)data; XFree(data); } return hints; } XAtomHelper::XAtomHelper(QObject *parent) : QObject(parent) { Display *display=nullptr; if(auto *x11Application=qGuiApp->nativeInterface()) { display=x11Application->display(); m_motifWMHintsAtom = XInternAtom(display, "_MOTIF_WM_HINTS", true); m_unityBorderRadiusAtom = XInternAtom(display, "_UNITY_GTK_BORDER_RADIUS", false); m_ukuiDecorationAtion = XInternAtom(display, "_KWIN_UKUI_DECORAION", false); } } Atom XAtomHelper::registerUKUICsdNetWmSupportAtom() { // fixme: return None; } void XAtomHelper::unregisterUKUICsdNetWmSupportAtom() { // fixme: } kylin-nm/src/frontend/xatom/xatom-helper.h0000664000175000017500000000626415167651420017571 0ustar fengfeng/* * KWin Style UKUI * * Copyright (C) 2020, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: Yue Lan * */ #ifndef XATOMHELPER_H #define XATOMHELPER_H #include #include #include struct UnityCorners { ulong topLeft = 0; ulong topRight = 0; ulong bottomLeft = 0; ulong bottomRight = 0; }; typedef struct { ulong flags = 0; ulong functions = 0; ulong decorations = 0; long input_mode = 0; ulong status = 0; } MotifWmHints, MwmHints; #define MWM_HINTS_FUNCTIONS (1L << 0) #define MWM_HINTS_DECORATIONS (1L << 1) #define MWM_HINTS_INPUT_MODE (1L << 2) #define MWM_HINTS_STATUS (1L << 3) #define MWM_FUNC_ALL (1L << 0) #define MWM_FUNC_RESIZE (1L << 1) #define MWM_FUNC_MOVE (1L << 2) #define MWM_FUNC_MINIMIZE (1L << 3) #define MWM_FUNC_MAXIMIZE (1L << 4) #define MWM_FUNC_CLOSE (1L << 5) #define MWM_DECOR_ALL (1L << 0) #define MWM_DECOR_BORDER (1L << 1) #define MWM_DECOR_RESIZEH (1L << 2) #define MWM_DECOR_TITLE (1L << 3) #define MWM_DECOR_MENU (1L << 4) #define MWM_DECOR_MINIMIZE (1L << 5) #define MWM_DECOR_MAXIMIZE (1L << 6) #define MWM_INPUT_MODELESS 0 #define MWM_INPUT_PRIMARY_APPLICATION_MODAL 1 #define MWM_INPUT_SYSTEM_MODAL 2 #define MWM_INPUT_FULL_APPLICATION_MODAL 3 #define MWM_INPUT_APPLICATION_MODAL MWM_INPUT_PRIMARY_APPLICATION_MODAL #define MWM_TEAROFF_WINDOW (1L<<0) namespace UKUI { class Decoration; } class XAtomHelper : public QObject { // friend class UKUI::Decoration; Q_OBJECT public: static XAtomHelper *getInstance(); static bool isFrameLessWindow(int winId); static bool isWindowDecorateBorderOnly(int winId); static bool isWindowMotifHintDecorateBorderOnly(const MotifWmHints &hint); bool isUKUICsdSupported(); bool isUKUIDecorationWindow(int winId); UnityCorners getWindowBorderRadius(int winId); void setWindowBorderRadius(int winId, const UnityCorners &data); void setWindowBorderRadius(int winId, int topLeft, int topRight, int bottomLeft, int bottomRight); void setUKUIDecoraiontHint(int winId, bool set = true); void setWindowMotifHint(int winId, const MotifWmHints &hints); MotifWmHints getWindowMotifHint(int winId); private: explicit XAtomHelper(QObject *parent = nullptr); Atom registerUKUICsdNetWmSupportAtom(); void unregisterUKUICsdNetWmSupportAtom(); Atom m_motifWMHintsAtom = None; Atom m_unityBorderRadiusAtom = None; Atom m_ukuiDecorationAtion = None; }; #endif kylin-nm/src/frontend/xatom/xatom.pri0000664000175000017500000000015115167646234016653 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/xatom-helper.h \ SOURCES += \ $$PWD/xatom-helper.cpp \ kylin-nm/src/frontend/frontend.pri0000664000175000017500000000113615167651420016207 0ustar fengfengINCLUDEPATH += $$PWD include(tools/tools.pri) include(xatom/xatom.pri) #没有使用 注销 include(tab-pages/tab-pages.pri) include(list-items/list-items.pri) include(netdetails/netdetails.pri) include(enterprise-wlan/enterprise-wlan.pri) include(connectivity/connectivity.pri) include(networkmode/networkmode.pri) FORMS += \ $$PWD/wificonfigdialog.ui HEADERS += \ $$PWD/customstyle.h \ $$PWD/mainwindow.h \ $$PWD/wificonfigdialog.h SOURCES += \ $$PWD/customstyle.cpp \ $$PWD/mainwindow.cpp \ $$PWD/wificonfigdialog.cpp DISTFILES += \ $$PWD/networkmode/networkmode.pri kylin-nm/src/frontend/netdetails/0000775000175000017500000000000015167651420016007 5ustar fengfengkylin-nm/src/frontend/netdetails/securitypage.cpp0000664000175000017500000013216215167651420021224 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "securitypage.h" #include "netdetail.h" #include #define DETAIL_MIN_LABEL_WIDTH 80 #define DETAIL_MIN_EDIT_WIDTH 390 #define MIN_LABEL_WIDTH 146 #define MIN_EDIT_WIDTH 286 enum ComboxFileIndex { NONE_INDEX = 0, CHOOSE_FILE_INDEX = 1 }; SecurityPage::SecurityPage(bool isNetDetailPage, QWidget *parent) : isDetailPage(isNetDetailPage), QFrame(parent) { initUI(); initConnect(); } void SecurityPage::initUI() { mainLayout = new QVBoxLayout(this); secuTypeLabel = new QLabel(this); pwdLabel = new QLabel(this); //企业wifi共有 eapTypeLabel = new QLabel(this); //TLS identityLable = new QLabel(this); domainLable = new QLabel(this); caCertPathLabel = new QLabel(this); caNeedFlagLabel = new QLabel(this); clientCertPathLabel = new FixLabel(this); clientCertPathLabel->setFixedWidth(MIN_LABEL_WIDTH); clientPrivateKeyLabel = new FixLabel(this); clientPrivateKeyLabel->setFixedWidth(MIN_LABEL_WIDTH); clientPrivateKeyPwdLabel = new FixLabel(this); clientPrivateKeyPwdLabel->setFixedWidth(MIN_LABEL_WIDTH); pwdOptionLabel = new FixLabel(this); pwdOptionLabel->setFixedWidth(MIN_LABEL_WIDTH); //PEAP TTLS共有 eapMethodLabel = new FixLabel(this); eapMethodLabel->setFixedWidth(MIN_LABEL_WIDTH); userNameLabel = new QLabel(this); userPwdLabel = new QLabel(this); userPwdFlagLabel = new QLabel(this); secuTypeCombox = new QComboBox(this); pwdEdit = new KPasswordEdit(this); pwdEdit->setMaxLength(63); eapTypeCombox = new QComboBox(this); //TLS identityEdit = new LineEdit(this); domainEdit = new LineEdit(this); caCertPathCombox = new QComboBox(this); caNeedBox = new QCheckBox(this); clientCertPathCombox = new QComboBox(this); clientPrivateKeyCombox = new QComboBox(this); clientPrivateKeyPwdEdit = new KPasswordEdit(this); pwdOptionCombox = new QComboBox(this); tlsWidget = new QWidget(this); //PEAP && TTLS eapMethodCombox = new QComboBox(this); userNameEdit = new LineEdit(this); userPwdEdit = new KPasswordEdit(this); userPwdFlagBox = new QCheckBox(this); //FAST m_pacCheckBox = new QCheckBox(this); m_pacProvisionComboBox = new QComboBox(this); m_pacFilePathComboBox = new QComboBox(this); m_pacProvisionLabel = new FixLabel(this); m_pacProvisionLabel->setFixedWidth(MIN_LABEL_WIDTH); m_pacFlagLabel = new FixLabel(this); m_pacFileLabel = new QLabel(this); QWidget *queryWidget = new QWidget(this); QHBoxLayout *queryLayout = new QHBoxLayout(queryWidget); queryLayout->setContentsMargins(0, 0, 0, 0); queryLayout->addWidget(userPwdFlagBox); queryLayout->addWidget(userPwdFlagLabel); queryLayout->addStretch(); //记住该网络复选框 m_emptyLabel = new QLabel(this); m_emptyLabel->setMinimumWidth(MIN_LABEL_WIDTH - 8); m_checkLabel = new QLabel(this); m_checkLabel->setText(tr("Remember the Network")); //记住该网络 m_rememberCheckBox = new QCheckBox(this); m_rememberCheckBox->setChecked(true); QWidget *checkWidget = new QWidget(this); QHBoxLayout *rememberLayout = new QHBoxLayout(checkWidget); rememberLayout->setContentsMargins(0, 0, 0, 0); rememberLayout->addWidget(m_emptyLabel); rememberLayout->addWidget(m_rememberCheckBox); rememberLayout->addWidget(m_checkLabel); rememberLayout->addStretch(); //允许自动PAC配置复选框 m_pacCheckWidget = new QWidget(this); QGridLayout *pacCheckLayout = new QGridLayout(m_pacCheckWidget); pacCheckLayout->setContentsMargins(0, 0, 0, 0); pacCheckLayout->setVerticalSpacing(0); pacCheckLayout->setColumnMinimumWidth(0, 16); pacCheckLayout->addWidget(m_pacProvisionComboBox, 0, 0, 1, 2); pacCheckLayout->addWidget(m_pacCheckBox, 1, 0); pacCheckLayout->addWidget(m_pacFlagLabel, 1, 1); topLayout = new QGridLayout(); topLayout->setContentsMargins(0, 0, 0, 0); topLayout->setVerticalSpacing(16); // 安全 Label和选项框 第0行,第0列,第1列 topLayout->addWidget(secuTypeLabel, 0, 0); topLayout->addWidget(secuTypeCombox, 0, 1); //密码 Label和密码框 第1行,第0列,第1列 topLayout->addWidget(pwdLabel, 1, 0); topLayout->addWidget(pwdEdit, 1, 1); // EAP认证 Label和选项框 第2行,第0列,第1列 topLayout->addWidget(eapTypeLabel, 2, 0); topLayout->addWidget(eapTypeCombox, 2, 1); // 匿名身份 Label和输入框 第3行,第0列,第1列 topLayout->addWidget(identityLable, 3, 0); topLayout->addWidget(identityEdit, 3, 1); //PAC配置 允许自动PAC配置 第4行,第0列;第4行,第1列,占2行1列 topLayout->addWidget(m_pacProvisionLabel, 4, 0, Qt::AlignTop); topLayout->addWidget(m_pacCheckWidget, 4, 1); // PAC文件 topLayout->addWidget(m_pacFileLabel, 6, 0); topLayout->addWidget(m_pacFilePathComboBox, 6, 1); //内部认证 Label和选项框 topLayout->addWidget(eapMethodLabel, 7, 0); topLayout->addWidget(eapMethodCombox, 7, 1); //用户名 Label和输入框 topLayout->addWidget(userNameLabel, 8, 0); topLayout->addWidget(userNameEdit, 8, 1); //密码 Label和密码框 topLayout->addWidget(userPwdLabel, 9, 0); topLayout->addWidget(userPwdEdit, 9, 1); // CA证书选项框及CheckBox布局 QWidget *caWidget = new QWidget(this); QGridLayout *checkLayout = new QGridLayout(caWidget); checkLayout->setContentsMargins(0, 0, 0, 0); checkLayout->setVerticalSpacing(0); checkLayout->setColumnMinimumWidth(0, 16); checkLayout->addWidget(caCertPathCombox, 0, 0, 1, 2); checkLayout->addWidget(caNeedBox, 1, 0); checkLayout->addWidget(caNeedFlagLabel, 1, 1); bottomLayout = new QGridLayout(tlsWidget); bottomLayout->setContentsMargins(0, 0, 0, 0); bottomLayout->setVerticalSpacing(8); bottomLayout->setHorizontalSpacing(0); // 域 Label和输入框 第0行,第0列,第1列 bottomLayout->addWidget(domainLable, 0, 0); bottomLayout->addWidget(domainEdit, 0, 1); // CA证书 Label第1行,第0列 bottomLayout->addWidget(caCertPathLabel, 1, 0); // CA证书选项框 不需要CA证书复选框 从第1行,第1列开始,占2行1列 bottomLayout->addWidget(caWidget, 1, 1, 2, 1); // 用户证书 Label和选项框 第3行,第0列,第1列 bottomLayout->addWidget(clientCertPathLabel, 3, 0); bottomLayout->addWidget(clientCertPathCombox, 3, 1); // 用户私钥 Label和选项框 第4行,第0列,第1列 bottomLayout->addWidget(clientPrivateKeyLabel, 4, 0); bottomLayout->addWidget(clientPrivateKeyCombox, 4, 1); // 私钥密码 Label和密码框 第5行,第0列,第1列 bottomLayout->addWidget(clientPrivateKeyPwdLabel, 5, 0); bottomLayout->addWidget(clientPrivateKeyPwdEdit, 5, 1); // 密码选项 Label和选项框 第6行,第0列,第1列 bottomLayout->addWidget(pwdOptionLabel, 6, 0); bottomLayout->addWidget(pwdOptionCombox, 6, 1); if (isDetailPage) { checkWidget->hide(); topLayout->addWidget(queryWidget, 10, 1); changeColumnWidthWithSecuType(); m_pacFlagLabel->setMinimumWidth(MIN_EDIT_WIDTH); } else { queryWidget->hide(); topLayout->setColumnMinimumWidth(0, MIN_LABEL_WIDTH); topLayout->setColumnMinimumWidth(1, MIN_EDIT_WIDTH); bottomLayout->setColumnMinimumWidth(0, MIN_LABEL_WIDTH - 8); m_pacFlagLabel->setMinimumWidth(MIN_EDIT_WIDTH - 36); } topLayout->addWidget(tlsWidget, 10, 0, 6, 2); mainLayout->setContentsMargins(0, 0, 0, 0); mainLayout->setSpacing(0); mainLayout->addLayout(topLayout); mainLayout->addWidget(checkWidget); mainLayout->addStretch(); secuTypeLabel->setText(tr("Security")); pwdLabel->setText(tr("Password")); pwdEdit->setPlaceholderText(hintRequired); //企业wifi共有 eapTypeLabel->setText(tr("EAP type")); //TLS identityLable->setText(tr("Identity")); domainLable->setText(tr("Domain")); caCertPathLabel->setText(tr("CA certficate")); caNeedFlagLabel->setText(tr("no need for CA certificate")); clientCertPathLabel->setLabelText(tr("User certificate")); clientPrivateKeyLabel->setLabelText(tr("User private key")); clientPrivateKeyPwdLabel->setLabelText(tr("User key password")); pwdOptionLabel->setLabelText(tr("Password options")); identityEdit->setPlaceholderText(tr("Required")); clientPrivateKeyPwdEdit->setPlaceholderText(hintRequired); //PEAP TTLS共有 eapMethodLabel->setLabelText(tr("Ineer authentication")); userNameLabel->setText(tr("Username")); userPwdLabel->setText(tr("Password")); userPwdFlagLabel->setText(tr("Ask pwd each query")); userNameEdit->setPlaceholderText(tr("Required")); userPwdEdit->setPlaceholderText(hintRequired); secuTypeCombox->addItem(tr("None"),KYLIN_NM::NONE); secuTypeCombox->addItem(tr("WPA&WPA2 Personal"),KYLIN_NM::WPA_AND_WPA2_PERSONAL); secuTypeCombox->addItem(tr("WPA&WPA2 Enterprise"), KYLIN_NM::WPA_AND_WPA2_ENTERPRISE); secuTypeCombox->addItem(tr("WPA3 Personal"), KYLIN_NM::WPA3_PERSONAL); eapTypeCombox->addItem("TLS", TLS); eapTypeCombox->addItem("PEAP", PEAP); eapTypeCombox->addItem("TTLS", TTLS); eapTypeCombox->addItem("LEAP", LEAP); eapTypeCombox->addItem("PWD", PWD); eapTypeCombox->addItem("FAST", FAST); eapTypeCombox->setCurrentIndex(TLS); //TLS caCertPathCombox->addItem(tr("None"), NONE_INDEX); //无 caCertPathCombox->addItem(tr("Choose from file..."), CHOOSE_FILE_INDEX); //从文件中选择... clientCertPathCombox->addItem(tr("None"), NONE_INDEX); //无 clientCertPathCombox->addItem(tr("Choose from file..."), CHOOSE_FILE_INDEX); //从文件中选择... clientPrivateKeyCombox->addItem(tr("None"), NONE_INDEX); //无 clientPrivateKeyCombox->addItem(tr("Choose from file..."), CHOOSE_FILE_INDEX); //从文件中选择... //仅为该用户存储密码 pwdOptionCombox->addItem(tr("Store passwords only for this user"), QString(tr("Store password only for this user"))); //存储所有用户的密码 pwdOptionCombox->addItem(tr("Store passwords for all users"), QString(tr("Store password for all users"))); //每次询问这个密码 pwdOptionCombox->addItem(tr("Ask this password every time"), QString(tr("Ask password every time"))); pwdOptionCombox->setCurrentIndex(1); //FAST m_pacCheckBox->setChecked(true); m_pacProvisionLabel->setLabelText(tr("PAC provisioning")); //PAC配置 m_pacFlagLabel->setLabelText(tr("Allow automatic PAC provisioning")); //允许自动PAC配置 m_pacFileLabel->setText(tr("PAC file")); //PAC文件 m_pacProvisionComboBox->addItem(tr("Anonymous"), ANON); //匿名 m_pacProvisionComboBox->addItem(tr("Authenticated"), AUTHEN); //已认证 m_pacProvisionComboBox->addItem(tr("Both"), BOTH); //两者兼用 m_pacProvisionComboBox->setCurrentIndex(ANON); m_pacFilePathComboBox->addItem(tr("None"), NONE_INDEX); //无 m_pacFilePathComboBox->addItem(tr("Choose from file..."), CHOOSE_FILE_INDEX); //从文件中选择... //禁用ClearBtn按钮 pwdEdit->setClearButtonEnabled(false); clientPrivateKeyPwdEdit->setClearButtonEnabled(false); userPwdEdit->setClearButtonEnabled(false); QRegularExpression rx("^[A-Za-z0-9`~!@#$%^&*()_-+=<>,.\\\/ ]+$"); QRegularExpressionValidator *latitude = new QRegularExpressionValidator(rx, this); pwdEdit->setValidator(latitude); clientPrivateKeyPwdEdit->setValidator(latitude); userPwdEdit->setValidator(latitude); showNone(); } void SecurityPage::initConnect() { //安全类型变化 // connect(secuTypeCombox, &QComboBox::currentTextChanged, this, &SecurityPage::onSecuTypeComboxIndexChanged); connect(secuTypeCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &SecurityPage::onSecuTypeComboxIndexChanged); connect(secuTypeCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &SecurityPage::changeColumnWidthWithSecuType); //EAP方式变化 // connect(eapTypeCombox, &QComboBox::currentTextChanged, this, &SecurityPage::onEapTypeComboxIndexChanged); connect(eapTypeCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &SecurityPage::onEapTypeComboxIndexChanged); connect(caNeedBox, &QCheckBox::clicked, this, &SecurityPage::onCaNeedBoxClicked); connect(caCertPathCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &SecurityPage::onCaCertPathComboxIndexChanged); connect(clientCertPathCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &SecurityPage::onClientCertPathComboxIndexChanged); connect(clientPrivateKeyCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &SecurityPage::onClientPrivateKeyComboxIndexChanged); /* connect(pwdOptionCombox, static_cast(&QComboBox::currentIndexChanged), this, &SecurityPage::onPwdOptionComboxIndexChanged); */ //早期版本实现 现currentTextChanged mqtest connect(pwdOptionCombox, &QComboBox::currentTextChanged,this, &SecurityPage::onPwdOptionComboxIndexChanged); connect(secuTypeCombox, SIGNAL(currentIndexChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(pwdEdit, &LineEdit::textChanged, this, &SecurityPage::setEnableOfSaveBtn); connect(eapTypeCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); connect(identityEdit, &LineEdit::textChanged, this, &SecurityPage::setEnableOfSaveBtn); connect(caCertPathCombox, SIGNAL(currentTextChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(caNeedBox, &QCheckBox::stateChanged, this, &SecurityPage::setEnableOfSaveBtn); connect(clientCertPathCombox, SIGNAL(currentTextChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(clientPrivateKeyCombox, SIGNAL(currentTextChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(clientPrivateKeyPwdEdit, &LineEdit::textChanged, this, &SecurityPage::setEnableOfSaveBtn); connect(eapMethodCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); connect(userNameEdit, &LineEdit::textChanged, this, &SecurityPage::setEnableOfSaveBtn); connect(userPwdEdit, &LineEdit::textChanged, this, &SecurityPage::setEnableOfSaveBtn); connect(m_pacCheckBox, &QCheckBox::stateChanged, this, &SecurityPage::setEnableOfSaveBtn); connect(m_pacProvisionComboBox, SIGNAL(currentTextChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(m_pacFilePathComboBox, SIGNAL(currentTextChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(m_pacCheckBox, &QCheckBox::clicked, this, &SecurityPage::onPacBoxClicked); connect(m_pacFilePathComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &SecurityPage::onPacFilePathComboxIndexChanged); } void SecurityPage::setSecurity(KySecuType index) { secuTypeCombox->setCurrentIndex(index); onSecuTypeComboxIndexChanged(); } void SecurityPage::setPsk(const QString &psk) { pwdEdit->setText(psk); } void SecurityPage::setTlsInfo(KyEapMethodTlsInfo &info) { showTls(); identityEdit->setText(info.identity); domainEdit->setText(info.domain); if (info.caCertPath.isEmpty()) { caCertPathCombox->setItemText(0, QString(tr("None"))); caNeedBox->setChecked(true); caCertPathCombox->setEnabled(false); } else { caCertPathCombox->setItemText(0, info.caCertPath); caNeedBox->setChecked(false); caCertPathCombox->setEnabled(true); } if (info.clientCertPath.isEmpty()) { clientCertPathCombox->setItemText(0, ""); } else { clientCertPathCombox->setItemText(0, info.clientCertPath); } if (info.clientPrivateKey.isEmpty()) { clientPrivateKeyCombox->setItemText(0, ""); } else { clientPrivateKeyCombox->setItemText(0, info.clientPrivateKey); } clientPrivateKeyPwdEdit->setText(info.clientPrivateKeyPWD); if (info.m_privateKeyPWDFlag == NetworkManager::Setting::AgentOwned) { pwdOptionCombox->setCurrentIndex(0); } else if (info.m_privateKeyPWDFlag == NetworkManager::Setting::None) { pwdOptionCombox->setCurrentIndex(1); } else { pwdOptionCombox->setCurrentIndex(2); } } void SecurityPage::setPeapInfo(KyEapMethodPeapInfo &info) { showPeapOrTtls(); eapTypeCombox->setCurrentIndex(PEAP); onEapTypeComboxIndexChanged(); if (info.phase2AuthMethod == KyAuthMethodMschapv2) { eapMethodCombox->setCurrentIndex(MSCHAPV2_PEAP); } else if (info.phase2AuthMethod == KyAuthMethodMd5){ eapMethodCombox->setCurrentIndex(MD5_PEAP); } else if (info.phase2AuthMethod == KyAuthMethodGtc) { eapMethodCombox->setCurrentIndex(GTC_PEAP); } userNameEdit->setText(info.userName); userPwdEdit->setText(info.userPWD); if (info.m_passwdFlag) { userPwdFlagBox->setChecked(true); } else { userPwdFlagBox->setChecked(false); } } void SecurityPage::setTtlsInfo(KyEapMethodTtlsInfo &info) { showPeapOrTtls(); eapTypeCombox->setCurrentIndex(TTLS); onEapTypeComboxIndexChanged(); if (info.authType == AUTH_EAP) { if (info.authEapMethod = KyAuthEapMethodMschapv2) { eapMethodCombox->setCurrentIndex(MSCHAPV2_EAP); } else if (info.authEapMethod = KyAuthEapMethodMd5) { eapMethodCombox->setCurrentIndex(MD5_EAP); } else if (info.authEapMethod = KyAuthEapMethodMd5) { eapMethodCombox->setCurrentIndex(MD5_EAP); } else { qDebug() << "not support yet. AUTH_EAP method" << info.authEapMethod; } } else { if (info.authNoEapMethod == KyAuthMethodPap) { eapMethodCombox->setCurrentIndex(PAP); } else if (info.authNoEapMethod == KyAuthMethodMschap) { eapMethodCombox->setCurrentIndex(MSCHAP); } else if (info.authNoEapMethod == KyAuthMethodMschapv2) { eapMethodCombox->setCurrentIndex(MSCHAPV2); } else if (info.authNoEapMethod == KyAuthMethodChap) { eapMethodCombox->setCurrentIndex(CHAP); } else { qDebug() << "not support yet. AUTH_NO_EAP method" << info.authNoEapMethod; } } userNameEdit->setText(info.userName); userPwdEdit->setText(info.userPWD); if (info.m_passwdFlag) { userPwdFlagBox->setChecked(true); } else { userPwdFlagBox->setChecked(false); } } void SecurityPage::setLeapInfo(KyEapMethodLeapInfo &info) { showLeapOrPwd(); eapTypeCombox->setCurrentIndex(LEAP); userNameEdit->setText(info.m_userName); userPwdEdit->setText(info.m_userPwd); if (info.m_passwdFlag) { userPwdFlagBox->setChecked(true); } else { userPwdFlagBox->setChecked(false); } } void SecurityPage::setPwdInfo(KyEapMethodPwdInfo &info) { showLeapOrPwd(); eapTypeCombox->setCurrentIndex(PWD); userNameEdit->setText(info.m_userName); userPwdEdit->setText(info.m_userPwd); if (info.m_passwdFlag) { userPwdFlagBox->setChecked(true); } else { userPwdFlagBox->setChecked(false); } } void SecurityPage::setFastInfo(KyEapMethodFastInfo &info) { showFast(); eapTypeCombox->setCurrentIndex(FAST); onEapTypeComboxIndexChanged(); identityEdit->setText(info.m_anonIdentity); m_pacCheckBox->setChecked(false); m_pacProvisionComboBox->setCurrentIndex(ANON); if (info.m_pacProvisioning == KyFastProvisioningDisabled) { m_pacCheckBox->setChecked(false); m_pacProvisionComboBox->setCurrentIndex(ANON); m_pacProvisionComboBox->setEnabled(false); } else if (info.m_pacProvisioning == KyFastProvisioningAllowUnauthenticated) { m_pacProvisionComboBox->setCurrentIndex(ANON); } else if (info.m_pacProvisioning == KyFastProvisioningAllowAuthenticated) { m_pacProvisionComboBox->setCurrentIndex(AUTHEN); } else if (info.m_pacProvisioning == KyFastProvisioningAllowBoth) { m_pacProvisionComboBox->setCurrentIndex(BOTH); } else { qWarning() << "Unknown fastProvisioning type" << Q_FUNC_INFO << __LINE__; m_pacCheckBox->setChecked(false); m_pacProvisionComboBox->setEnabled(false); } if (info.m_pacFilePath.isEmpty()) { m_pacFilePathComboBox->setItemText(0, QString(tr("None"))); } else { m_pacFilePathComboBox->setItemText(0, info.m_pacFilePath); } if (info.m_authMethod == KyAuthMethodGtc) { eapMethodCombox->setCurrentIndex(GTC_FAST); } else if (info.m_authMethod == KyAuthMethodMschapv2) { eapMethodCombox->setCurrentIndex(MSCHAPV2_FAST); } userNameEdit->setText(info.m_userName); userPwdEdit->setText(info.m_userPwd); if (info.m_passwdFlag) { userPwdFlagBox->setChecked(true); } else { userPwdFlagBox->setChecked(false); } } void SecurityPage::setSecurityVisible(const bool &visible) { if (secuTypeLabel) { secuTypeLabel->setVisible(visible); } else { qWarning() << "Set visible of secuTypeLabel failed because of null pointer" << Q_FUNC_INFO << __LINE__; } if (secuTypeCombox) { secuTypeCombox->setVisible(visible); } else { qWarning() << "Set visible of secuTypeCombox failed because of null pointer" << Q_FUNC_INFO << __LINE__; } } void SecurityPage::updateTlsChange(KyEapMethodTlsInfo &info) { KyEapMethodTlsInfo tlsInfo = assembleTlsInfo(); if (tlsInfo.clientPrivateKeyPWD != info.clientPrivateKeyPWD) { tlsInfo.bChanged = true; } tlsInfo.devIfaceName = info.devIfaceName; info = tlsInfo; } void SecurityPage::updatePeapChange(KyEapMethodPeapInfo &info) { KyEapMethodPeapInfo peapInfo = assemblePeapInfo(); if (peapInfo.userPWD != info.userPWD) { peapInfo.bChanged = true; } info = peapInfo; } void SecurityPage::updateTtlsChange(KyEapMethodTtlsInfo &info) { KyEapMethodTtlsInfo ttlsInfo = assembleTtlsInfo(); if (ttlsInfo.userPWD != info.userPWD) { ttlsInfo.bChanged = true; } info = ttlsInfo; } void SecurityPage::updateLeapChange(KyEapMethodLeapInfo &info) { KyEapMethodLeapInfo leapInfo = assembleLeapInfo(); if (leapInfo.m_userPwd != info.m_userPwd) { leapInfo.bChanged = true; } info = leapInfo; } void SecurityPage::updatePwdChange(KyEapMethodPwdInfo &info) { KyEapMethodPwdInfo pwdInfo = assemblePwdInfo(); if (pwdInfo.m_userPwd != info.m_userPwd) { pwdInfo.bChanged = true; } info = pwdInfo; } void SecurityPage::updateFastChange(KyEapMethodFastInfo &info) { KyEapMethodFastInfo pwdInfo = assembleFastInfo(); if (pwdInfo.m_userPwd != info.m_userPwd) { pwdInfo.bChanged = true; } info = pwdInfo; } void SecurityPage::getSecuType(KySecuType &secuType, KyEapMethodType &enterpriseType) { secuType = (KySecuType)secuTypeCombox->currentData().toInt(); enterpriseType = (KyEapMethodType)eapTypeCombox->currentData().toInt(); } bool SecurityPage::getAutoConnectState() { bool state = m_rememberCheckBox->isChecked(); return state; } bool SecurityPage::checkIsChanged(const ConInfo info) { if (info.secType != secuTypeCombox->currentData().toInt()) { return true; } else { if (info.secType == KYLIN_NM::NONE) { return false; } else if (info.secType == KYLIN_NM::WPA_AND_WPA2_PERSONAL || info.secType == KYLIN_NM::WPA3_PERSONAL) { return !(info.strPassword == pwdEdit->text()); } else { if (info.enterpriseType != eapTypeCombox->currentData().toInt()) { return true; } else { if (info.enterpriseType == TLS) { return !(info.tlsInfo == assembleTlsInfo()); } else if (info.enterpriseType == PEAP) { return !(info.peapInfo == assemblePeapInfo()); } else if (info.enterpriseType == TTLS) { return !(info.ttlsInfo == assembleTtlsInfo()); } else if (info.enterpriseType == LEAP) { return !(info.leapInfo == assembleLeapInfo()); } else if (info.enterpriseType == PWD) { return !(info.pwdInfo == assemblePwdInfo()); } else if (info.enterpriseType == FAST) { return !(info.fastInfo == assembleFastInfo()); } } } } } void SecurityPage::showNone() { pwdLabel->hide(); pwdEdit->hide(); //企业wifi共有 eapTypeLabel->hide(); eapTypeCombox->hide(); //TLS identityLable->hide(); identityEdit->hide(); tlsWidget->hide(); //PEAP TTLS共有 eapMethodLabel->hide(); userNameLabel->hide(); userPwdLabel->hide(); userPwdFlagBox->hide(); eapMethodCombox->hide(); userNameEdit->hide(); userPwdEdit->hide(); userPwdFlagLabel->hide(); //FAST m_pacProvisionLabel->hide(); m_pacCheckWidget->hide(); m_pacFileLabel->hide(); m_pacFilePathComboBox->hide(); } void SecurityPage::showPsk() { pwdLabel->show(); pwdEdit->show(); //企业wifi共有 eapTypeLabel->hide(); eapTypeCombox->hide(); //TLS identityLable->hide(); identityEdit->hide(); tlsWidget->hide(); //PEAP TTLS共有 eapMethodLabel->hide(); userNameLabel->hide(); userPwdLabel->hide(); userPwdFlagBox->hide(); eapMethodCombox->hide(); userNameEdit->hide(); userPwdEdit->hide(); userPwdFlagLabel->hide(); //FAST m_pacProvisionLabel->hide(); m_pacCheckWidget->hide(); m_pacFileLabel->hide(); m_pacFilePathComboBox->hide(); } void SecurityPage::showTls() { pwdLabel->hide(); pwdEdit->hide(); eapTypeCombox->show(); eapTypeLabel->show(); //TLS identityLable->show(); identityEdit->show(); tlsWidget->show(); //PEAP TTLS共有 eapMethodLabel->hide(); userNameLabel->hide(); userPwdLabel->hide(); userPwdFlagBox->hide(); eapMethodCombox->hide(); userNameEdit->hide(); userPwdEdit->hide(); userPwdFlagLabel->hide(); //FAST m_pacProvisionLabel->hide(); m_pacCheckWidget->hide(); m_pacFileLabel->hide(); m_pacFilePathComboBox->hide(); } void SecurityPage::showPeapOrTtls() { pwdLabel->hide(); pwdEdit->hide(); //企业wifi共有 eapTypeLabel->show(); eapTypeCombox->show(); //TLS identityLable->hide(); identityEdit->hide(); tlsWidget->hide(); //PEAP TTLS共有 eapMethodLabel->show(); userNameLabel->show(); userPwdLabel->show(); userPwdFlagBox->show(); eapMethodCombox->show(); userNameEdit->show(); userPwdEdit->show(); userPwdFlagLabel->show(); //FAST m_pacProvisionLabel->hide(); m_pacCheckWidget->hide(); m_pacFileLabel->hide(); m_pacFilePathComboBox->hide(); } void SecurityPage::showLeapOrPwd() { pwdLabel->hide(); pwdEdit->hide(); //企业wifi共有 eapTypeLabel->show(); eapTypeCombox->show(); //TLS identityLable->hide(); identityEdit->hide(); tlsWidget->hide(); //FAST m_pacProvisionLabel->hide(); m_pacCheckWidget->hide(); m_pacFileLabel->hide(); m_pacFilePathComboBox->hide(); eapMethodLabel->hide(); eapMethodCombox->hide(); userPwdFlagBox->show(); userPwdFlagLabel->show(); userNameLabel->show(); userNameEdit->show(); userPwdLabel->show(); userPwdEdit->show(); } void SecurityPage::showFast() { pwdLabel->hide(); pwdEdit->hide(); //企业wifi共有 eapTypeLabel->show(); eapTypeCombox->show(); //TLS identityLable->show(); identityEdit->show(); tlsWidget->hide(); //FAST m_pacProvisionLabel->show(); m_pacCheckWidget->show(); m_pacFileLabel->show(); m_pacFilePathComboBox->show(); eapMethodLabel->show(); eapMethodCombox->show(); userPwdFlagBox->show(); userPwdFlagLabel->show(); userNameLabel->show(); userNameEdit->show(); userPwdLabel->show(); userPwdEdit->show(); } KyEapMethodTlsInfo SecurityPage::assembleTlsInfo() { KyEapMethodTlsInfo info; info.identity = identityEdit->text(); info.domain = domainEdit->text(); info.caCertPath = caCertPathCombox->currentText(); info.bNeedCa = !caNeedBox->isChecked(); info.clientCertPath = clientCertPathCombox->currentText(); info.clientPrivateKey = clientPrivateKeyCombox->currentText(); info.clientPrivateKeyPWD = clientPrivateKeyPwdEdit->text(); switch (pwdOptionCombox->currentIndex()) { case 0: info.m_privateKeyPWDFlag = NetworkManager::Setting::AgentOwned; break; case 1: info.m_privateKeyPWDFlag = NetworkManager::Setting::None; break; case 2: info.m_privateKeyPWDFlag = NetworkManager::Setting::NotSaved; break; default: break; } return info; } KyEapMethodPeapInfo SecurityPage::assemblePeapInfo() { KyEapMethodPeapInfo info; // info.phase2AuthMethod = (KyNoEapMethodAuth)eapMethodCombox->currentData().toInt(); switch (eapMethodCombox->currentIndex()) { case 0: info.phase2AuthMethod = KyAuthMethodMschapv2; break; case 1: info.phase2AuthMethod = KyAuthMethodMd5; break; case 2: info.phase2AuthMethod = KyAuthMethodGtc; break; default: break; } info.userName = userNameEdit->text(); info.userPWD = userPwdEdit->text(); info.m_passwdFlag = (userPwdFlagBox->isChecked() ? NetworkManager::Setting::NotSaved : NetworkManager::Setting::None); return info; } KyEapMethodTtlsInfo SecurityPage::assembleTtlsInfo() { KyEapMethodTtlsInfo info; switch (eapMethodCombox->currentIndex()) { case PAP: info.authType = AUTH_NO_EAP; info.authNoEapMethod = KyAuthMethodPap; break; case MSCHAP: info.authType = AUTH_NO_EAP; info.authNoEapMethod = KyAuthMethodChap; break; case MSCHAPV2_EAP: info.authType = AUTH_EAP; info.authEapMethod = KyAuthEapMethodMschapv2; break; case MSCHAPV2: info.authType = AUTH_NO_EAP; info.authNoEapMethod = KyAuthMethodMschapv2; break; case CHAP: info.authType = AUTH_NO_EAP; info.authNoEapMethod = KyAuthMethodChap; break; case MD5_EAP: info.authType = AUTH_EAP; info.authEapMethod = KyAuthEapMethodMd5; break; case GTC_EAP: info.authType = AUTH_EAP; info.authEapMethod = KyAuthEapMethodGtc; break; default: break; } info.userName = userNameEdit->text(); info.userPWD = userPwdEdit->text(); info.m_passwdFlag = (userPwdFlagBox->isChecked() ? NetworkManager::Setting::NotSaved : NetworkManager::Setting::None); return info; } KyEapMethodLeapInfo SecurityPage::assembleLeapInfo() { KyEapMethodLeapInfo info; info.m_userName = userNameEdit->text(); info.m_userPwd = userPwdEdit->text(); info.m_passwdFlag = (userPwdFlagBox->isChecked() ? NetworkManager::Setting::NotSaved : NetworkManager::Setting::None); return info; } KyEapMethodPwdInfo SecurityPage::assemblePwdInfo() { KyEapMethodPwdInfo info; info.m_userName = userNameEdit->text(); info.m_userPwd = userPwdEdit->text(); info.m_passwdFlag = (userPwdFlagBox->isChecked() ? NetworkManager::Setting::NotSaved : NetworkManager::Setting::None); return info; } KyEapMethodFastInfo SecurityPage::assembleFastInfo() { KyEapMethodFastInfo info; info.m_anonIdentity = identityEdit->text(); switch (m_pacProvisionComboBox->currentIndex()) { case ANON: info.m_pacProvisioning = KyFastProvisioningAllowUnauthenticated; break; case AUTHEN: info.m_pacProvisioning = KyFastProvisioningAllowAuthenticated; break; case BOTH: info.m_pacProvisioning = KyFastProvisioningAllowBoth; break; default: break; } info.m_allowAutoPacFlag = m_pacCheckBox->isChecked(); info.m_pacFilePath = m_pacFilePathComboBox->currentText(); switch (eapMethodCombox->currentIndex()) { case GTC_FAST: info.m_authMethod = KyAuthMethodGtc; break; case MSCHAPV2_FAST: info.m_authMethod = KyAuthMethodMschapv2; break; default: break; } info.m_userName = userNameEdit->text(); info.m_userPwd = userPwdEdit->text(); info.m_passwdFlag = (userPwdFlagBox->isChecked() ? NetworkManager::Setting::NotSaved : NetworkManager::Setting::None); return info; } void SecurityPage::updateSecurityChange(KyWirelessConnectSetting &setting) { qDebug() << "secuTypeCombox->currentData()" << secuTypeCombox->currentData().toInt() << pwdEdit->text(); if (secuTypeCombox->currentData().toInt() == KYLIN_NM::NONE) { setting.m_psk = ""; } else { setting.m_psk = pwdEdit->text(); } if (secuTypeCombox->currentData().toInt() == KYLIN_NM::NONE) { setting.m_type = WpaNone; } else if (secuTypeCombox->currentData().toInt() == KYLIN_NM::WPA_AND_WPA2_PERSONAL) { setting.m_type = WpaPsk; } else if (secuTypeCombox->currentData().toInt() == KYLIN_NM::WPA3_PERSONAL) { setting.m_type = SAE; } setting.isAutoConnect = m_rememberCheckBox->isChecked(); } bool SecurityPage::checkConnectBtnIsEnabled() { int index = secuTypeCombox->currentData().toInt(); if (index == KYLIN_NM::NONE) { } else if (index == KYLIN_NM::WPA_AND_WPA2_PERSONAL || index == KYLIN_NM::WPA3_PERSONAL) { if (pwdEdit->text().isEmpty() || pwdEdit->text().length() < 8 ) { qDebug() << "password is empty or length < 8"; m_errorMessage = tr("Wifi password length less than 8"); return false; } } else if (index == KYLIN_NM::WPA_AND_WPA2_ENTERPRISE) { int type = eapTypeCombox->currentData().toInt(); if (type == TLS) { if (identityEdit->text().isEmpty()) { qDebug() << "tls identity is empty"; m_errorMessage = tr("TLS identity is empty"); return false; } QFile cafile(caCertPathCombox->currentText()); if(!caNeedBox->isChecked() && !cafile.exists()) { qDebug() << "ca cert filepath " << caCertPathCombox->currentText() << " is invalid"; m_errorMessage = tr("CA cert filepath is invalid"); return false; } QFile cliCafile(clientCertPathCombox->currentText()); if(!cliCafile.exists()) { qDebug() << "client cert filepath " << clientCertPathCombox->currentText() << " is invalid"; m_errorMessage = tr("Client cert filepath is invalid"); return false; } QFile cliKeyfile(clientPrivateKeyCombox->currentText()); if(!cliKeyfile.exists()) { qDebug() << "client private key filepath " << clientPrivateKeyCombox->currentText() << " is invalid"; m_errorMessage = tr("Client private key filepath is invalid"); return false; } if(clientPrivateKeyPwdEdit->text().isEmpty()) { qDebug() << "client Private Key password is empty"; m_errorMessage = tr("Client private key password is empty"); return false; } } else if (type == PEAP || type == TTLS || type == LEAP || type == PWD) { if(userNameEdit->text().isEmpty() || userPwdEdit->text().isEmpty()) { qDebug() << "user name or user password is empty"; m_errorMessage = tr("User name or user password is empty"); return false; } } else if (type == FAST) { if(!m_pacCheckBox->isChecked()) { if (m_pacFilePathComboBox->currentText() == QString(tr("None"))) { qDebug() << "Not allow automatic PAC provisioning && pac file is empty"; m_errorMessage = tr("No PAC file is selected "); return false; } } if(userNameEdit->text().isEmpty() || userPwdEdit->text().isEmpty()) { qDebug() << "user name or user password is empty"; m_errorMessage = tr("User name or user password is empty"); return false; } } } m_errorMessage.clear(); return true; } void SecurityPage::setEnableOfSaveBtn() { Q_EMIT setSecuPageState(checkConnectBtnIsEnabled()); } void SecurityPage::onSecuTypeComboxIndexChanged() { int index = secuTypeCombox->currentData().toInt(); if (index == KYLIN_NM::WPA_AND_WPA2_PERSONAL) { showPsk(); Q_EMIT this->secuTypeChanged(KYLIN_NM::WPA_AND_WPA2_PERSONAL); } else if (index == KYLIN_NM::WPA3_PERSONAL) { showPsk(); Q_EMIT this->secuTypeChanged(KYLIN_NM::WPA3_PERSONAL); } else if (index == KYLIN_NM::WPA_AND_WPA2_ENTERPRISE) { onEapTypeComboxIndexChanged(); Q_EMIT this->secuTypeChanged(KYLIN_NM::WPA_AND_WPA2_ENTERPRISE); } else if (index == KYLIN_NM::NONE) { showNone(); Q_EMIT this->secuTypeChanged(KYLIN_NM::NONE); } } void SecurityPage::onEapTypeComboxIndexChanged() { qDebug() << "onEapTypeComboxIndexChanged"; int index = eapTypeCombox->currentData().toInt(); if (index == TLS) { showTls(); Q_EMIT this->eapTypeChanged(TLS); } else if (index == PEAP) { showPeapOrTtls(); eapMethodCombox->clear(); eapMethodCombox->addItem("MSCHAPv2", MSCHAPV2_PEAP); eapMethodCombox->addItem("MD5", MD5_PEAP); eapMethodCombox->addItem("GTC", GTC_PEAP); Q_EMIT this->eapTypeChanged(PEAP); } else if (index == TTLS) { showPeapOrTtls(); eapMethodCombox->clear(); eapMethodCombox->addItem("pap", PAP); eapMethodCombox->addItem("mschap", MSCHAP); eapMethodCombox->addItem("mschapv2(eap)", MSCHAPV2_EAP); eapMethodCombox->addItem("mschapv2", MSCHAPV2); eapMethodCombox->addItem("chap", CHAP); eapMethodCombox->addItem("md5(eap)", MD5_EAP); eapMethodCombox->addItem("gtc(eap)", GTC_EAP); Q_EMIT this->eapTypeChanged(TTLS); } else if (index == LEAP) { showLeapOrPwd(); Q_EMIT this->eapTypeChanged(LEAP); } else if (index == PWD) { showLeapOrPwd(); Q_EMIT this->eapTypeChanged(PWD); } else if (index == FAST) { showFast(); eapMethodCombox->clear(); eapMethodCombox->addItem("GTC", GTC_FAST); eapMethodCombox->addItem("MSCHAPv2", MSCHAPV2_FAST); Q_EMIT this->eapTypeChanged(FAST); } } void SecurityPage::onCaNeedBoxClicked() { if (caNeedBox->isChecked()) { caCertPathCombox->setItemText(0, QString(tr("None"))); caCertPathCombox->setEnabled(false); } else { caCertPathCombox->setEnabled(true); } } void SecurityPage::onPacBoxClicked() { if (!m_pacCheckBox->isChecked()) { m_pacProvisionComboBox->setCurrentIndex(ANON); m_pacProvisionComboBox->setEnabled(false); } else { m_pacProvisionComboBox->setEnabled(true); } } void SecurityPage::onCaCertPathComboxIndexChanged() { if (caCertPathCombox->currentData().toInt() == CHOOSE_FILE_INDEX) { //fix bug 367425 QString fileName = QFileDialog::getOpenFileName(nullptr, tr("Choose a CA certificate"), "recent:///", tr("CA Files ( *.pem *.der *.p12 *.crt *.cer *.pfx)")); qDebug() << "onCaCertPathComboxIndexChanged fileName" << fileName; if (!fileName.isNull()) { QStringList nameList = fileName.split("/"); caCertPathCombox->blockSignals(true); caCertPathCombox->setItemText(CHOOSE_FILE_INDEX, fileName); caCertPathCombox->setCurrentIndex(CHOOSE_FILE_INDEX); caCertPathCombox->blockSignals(false); } else { caCertPathCombox->blockSignals(true); caCertPathCombox->setItemText(NONE_INDEX, tr("None")); caCertPathCombox->setCurrentIndex(NONE_INDEX); caCertPathCombox->blockSignals(false); } } else { qWarning() << "Choose file is null or unvalible"; } } void SecurityPage::onClientCertPathComboxIndexChanged() { if (clientCertPathCombox->currentData().toInt() == CHOOSE_FILE_INDEX) { QString fileName = QFileDialog::getOpenFileName(nullptr, tr("Choose a CA certificate"), "recent:///", tr("CA Files ( *.pem *.der *.p12 *.crt *.cer *.pfx)")); if (!fileName.isNull()) { clientCertPathCombox->blockSignals(true); clientCertPathCombox->setItemText(CHOOSE_FILE_INDEX, fileName); clientCertPathCombox->setCurrentIndex(CHOOSE_FILE_INDEX); clientCertPathCombox->blockSignals(false); } else { clientCertPathCombox->blockSignals(true); clientCertPathCombox->setItemText(NONE_INDEX, tr("None")); clientCertPathCombox->setCurrentIndex(NONE_INDEX); clientCertPathCombox->blockSignals(false); } } else { qWarning() << "Choose file is null or unvalible"; } } void SecurityPage::onClientPrivateKeyComboxIndexChanged() { if (clientPrivateKeyCombox->currentData().toInt() == CHOOSE_FILE_INDEX) { QString fileName = QFileDialog::getOpenFileName(nullptr, tr("Choose a CA certificate"), "recent:///", tr("CA Files ( *.pem *.der *.p12 *.crt *.cer *.pfx)")); if (!fileName.isNull()) { QStringList nameList = fileName.split("/"); clientPrivateKeyCombox->blockSignals(true); clientPrivateKeyCombox->setItemText(CHOOSE_FILE_INDEX, fileName); clientPrivateKeyCombox->setCurrentIndex(CHOOSE_FILE_INDEX); clientPrivateKeyCombox->blockSignals(false); } else { clientPrivateKeyCombox->blockSignals(true); clientPrivateKeyCombox->setItemText(NONE_INDEX, tr("None")); clientPrivateKeyCombox->setCurrentIndex(NONE_INDEX); clientPrivateKeyCombox->blockSignals(false); } } else { qWarning() << "Choose file is null or unvalible"; } } void SecurityPage::onPwdOptionComboxIndexChanged(QString str) { KyEapMethodTlsInfo info; if (str.contains("Store passwords only for this user") || str.contains("仅为该用户存储密码")) { info.m_privateKeyPWDFlag = NetworkManager::Setting::AgentOwned; clientPrivateKeyPwdEdit->setPlaceholderText(emptyhint); } else if (str.contains("Store passwords for all users") || str.contains("存储所有用户的密码")) { info.m_privateKeyPWDFlag = NetworkManager::Setting::None; clientPrivateKeyPwdEdit->setPlaceholderText(hintRequired); } else { info.m_privateKeyPWDFlag = NetworkManager::Setting::NotSaved; clientPrivateKeyPwdEdit->setPlaceholderText(emptyhint); } } void SecurityPage::changeColumnWidthWithSecuType() { if (!isDetailPage) { return; } if (secuTypeCombox->currentData().toInt() == WPA_AND_WPA2_ENTERPRISE && eapMethodCombox->currentData().toInt() == TLS) { topLayout->setColumnMinimumWidth(0, MIN_LABEL_WIDTH); topLayout->setColumnMinimumWidth(1, MIN_EDIT_WIDTH); bottomLayout->setColumnMinimumWidth(0, MIN_LABEL_WIDTH - 8); } else { topLayout->setColumnMinimumWidth(0, DETAIL_MIN_LABEL_WIDTH); topLayout->setColumnMinimumWidth(1, DETAIL_MIN_EDIT_WIDTH); } } void SecurityPage::onPacFilePathComboxIndexChanged() { if (m_pacFilePathComboBox->currentData().toInt() == CHOOSE_FILE_INDEX) { QString fileName = QFileDialog::getOpenFileName(nullptr, tr("Choose a PAC file"), "recent:///", tr("PAC Files ( *.pac)")); if (!fileName.isNull()) { QStringList nameList = fileName.split("/"); m_pacFilePathComboBox->blockSignals(true); m_pacFilePathComboBox->setItemText(CHOOSE_FILE_INDEX, fileName); m_pacFilePathComboBox->setCurrentIndex(CHOOSE_FILE_INDEX); m_pacFilePathComboBox->blockSignals(false); } else { m_pacFilePathComboBox->blockSignals(true); m_pacFilePathComboBox->setItemText(NONE_INDEX, tr("None")); m_pacFilePathComboBox->setCurrentIndex(NONE_INDEX); m_pacFilePathComboBox->blockSignals(false); } } else { qWarning() << "Choose file is null or unvalible"; } } QString SecurityPage::getErrorMessage() { checkConnectBtnIsEnabled(); return m_errorMessage; } kylin-nm/src/frontend/netdetails/configpage.h0000664000175000017500000000344415167646234020276 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef CONFIGPAGE_H #define CONFIGPAGE_H #include #include #include #include #include #include #include "kwidget.h" #include "kborderlessbutton.h" using namespace kdk; class ConfigPage : public QFrame { Q_OBJECT public: ConfigPage(QWidget *parent = nullptr); ~ConfigPage() = default; void setConfigState(int type); bool checkIsChanged(int type); int getConfigState(); private: void initUi(); void initComponent(); QLabel *m_descriptionLabel = nullptr; QRadioButton *m_publicButton = nullptr; QRadioButton *m_privateButton = nullptr; QLabel *m_publicLabel = nullptr; QLabel *m_privateLabel = nullptr; KBorderlessButton *m_congigBtn = nullptr; QVBoxLayout *m_vBoxLayout = nullptr; private Q_SLOTS: void onConfigButtonClicked(); Q_SIGNALS: void publicConfig(); void privateConfig(); }; #endif // CONFIGPAGE_H kylin-nm/src/frontend/netdetails/multiplednswidget.h0000664000175000017500000000475515167651420021737 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef MULTIPLEDNSWIDGET_H #define MULTIPLEDNSWIDGET_H #include #include #include #include #include #include #include #include #include #include #include #include "listitemedit.h" #include "dnssettingwidget.h" #include "kborderlessbutton.h" #include "kbuttonbox.h" using namespace kdk; class MultipleDnsWidget: public QWidget { Q_OBJECT public: MultipleDnsWidget(const QRegularExpression &rx, bool settingShow = true, QWidget *parent = nullptr); ~MultipleDnsWidget() = default; void setEditEnabled(bool state); QList getDns() const; void setDnsListText(const QList &dns); void setUuid(QString uuid) { m_uuid = uuid; } bool getDnsSettingsChanged() { return m_dnsSettingChanged; } private: void initUI(); void initComponent(); void AddOneDnsItem(QListWidget *listWidget); void RemoveOneDnsItem(QListWidgetItem *aItem, QListWidget *listWidget); void showDnsSettingWidget(); QLabel *m_mulDnsLabel; QLabel *emptyLabel; QFrame *m_emptyWidget; QListWidget *m_dnsListWidget = nullptr; KPushButton *m_addDnsBtn; KPushButton *m_removeDnsBtn; KButtonBox *m_buttonBox; KBorderlessButton* m_settingsLabel; QRegularExpression m_regExp; QString m_uuid; bool m_settingShow; bool m_dnsSettingChanged = false; private Q_SLOTS: void onAddBtnClicked(); void onRemoveBtnClicked(); void setPlaceholderTextColor(); Q_SIGNALS: void scrollToBottom(); }; #endif // MULTIPLEDNSWIDGET_H kylin-nm/src/frontend/netdetails/securitypage.h0000664000175000017500000001175515167651420020675 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef SECURITYWIDGET_H #define SECURITYWIDGET_H #include #include #include #include #include #include #include "coninfo.h" #include "kylable.h" #include "kwidget.h" #include "kpasswordedit.h" using namespace kdk; class SecurityPage : public QFrame { Q_OBJECT public: SecurityPage(bool isNetDetailPage, QWidget *parent = nullptr); void setSecurity(KySecuType index); void setPsk(const QString &psk); void setTlsInfo(KyEapMethodTlsInfo &info); void setPeapInfo(KyEapMethodPeapInfo &info); void setTtlsInfo(KyEapMethodTtlsInfo &info); void setLeapInfo(KyEapMethodLeapInfo &info); void setPwdInfo(KyEapMethodPwdInfo &info); void setFastInfo(KyEapMethodFastInfo &info); void setSecurityVisible(const bool &visible); bool checkIsChanged(const ConInfo info); void updateSecurityChange(KyWirelessConnectSetting &setting); void updateTlsChange(KyEapMethodTlsInfo &info); void updatePeapChange(KyEapMethodPeapInfo &info); void updateTtlsChange(KyEapMethodTtlsInfo &info); void updateLeapChange(KyEapMethodLeapInfo &info); void updatePwdChange(KyEapMethodPwdInfo &info); void updateFastChange(KyEapMethodFastInfo &info); void getSecuType(KySecuType &secuType, KyEapMethodType &enterpriseType); bool getAutoConnectState(); QString getErrorMessage(); private: bool isDetailPage; // QFormLayout *mSecuLayout; QGridLayout *topLayout; QGridLayout *bottomLayout; QVBoxLayout *mainLayout; QLabel *secuTypeLabel; QLabel *pwdLabel; //企业wifi共有 QLabel *eapTypeLabel; //TLS QLabel *identityLable; QLabel *domainLable; QLabel *caCertPathLabel; QLabel *caNeedFlagLabel; FixLabel *clientCertPathLabel; FixLabel *clientPrivateKeyLabel; FixLabel *clientPrivateKeyPwdLabel; FixLabel *pwdOptionLabel; //PEAP TTLS共有 FixLabel *eapMethodLabel; QLabel *userNameLabel; QLabel *userPwdLabel; QLabel *userPwdFlagLabel; QComboBox *secuTypeCombox; KPasswordEdit *pwdEdit = nullptr; QComboBox *eapTypeCombox; //TLS LineEdit *identityEdit; LineEdit *domainEdit; QComboBox *caCertPathCombox; QCheckBox *caNeedBox; QComboBox *clientCertPathCombox; QComboBox *clientPrivateKeyCombox; KPasswordEdit *clientPrivateKeyPwdEdit = nullptr; QComboBox *pwdOptionCombox; QWidget *tlsWidget; //PEAP && TTLS QComboBox *eapMethodCombox; LineEdit *userNameEdit; KPasswordEdit *userPwdEdit = nullptr; QCheckBox *userPwdFlagBox; //FAST QCheckBox *m_pacCheckBox; QComboBox *m_pacProvisionComboBox; QComboBox *m_pacFilePathComboBox; FixLabel *m_pacProvisionLabel; FixLabel *m_pacFlagLabel; QLabel *m_pacFileLabel; QWidget *m_pacCheckWidget; QLabel *m_emptyLabel = nullptr; QLabel *m_checkLabel = nullptr; QCheckBox *m_rememberCheckBox = nullptr; QString hintRequired = tr("Required"); //必填 QString emptyhint = tr(" "); QString m_errorMessage; private: void showNone(); void showPsk(); void showTls(); void showPeapOrTtls(); void showLeapOrPwd(); void showFast(); void initUI(); void initConnect(); KyEapMethodTlsInfo assembleTlsInfo(); KyEapMethodPeapInfo assemblePeapInfo(); KyEapMethodTtlsInfo assembleTtlsInfo(); KyEapMethodLeapInfo assembleLeapInfo(); KyEapMethodPwdInfo assemblePwdInfo(); KyEapMethodFastInfo assembleFastInfo(); bool checkConnectBtnIsEnabled(); private Q_SLOTS: void onSecuTypeComboxIndexChanged(); void onEapTypeComboxIndexChanged(); void setEnableOfSaveBtn(); void onCaNeedBoxClicked(); void onPacBoxClicked(); void onCaCertPathComboxIndexChanged(); void onClientCertPathComboxIndexChanged(); void onClientPrivateKeyComboxIndexChanged(); void onPwdOptionComboxIndexChanged(QString str); void changeColumnWidthWithSecuType(); void onPacFilePathComboxIndexChanged(); Q_SIGNALS: void setSecuPageState(bool); void secuTypeChanged(const KySecuType &type); void eapTypeChanged(const KyEapMethodType &type); }; #endif // SECURITYWIDGET_H kylin-nm/src/frontend/netdetails/coninfo.h0000664000175000017500000002377415167646234017637 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef CONINFO_H #define CONINFO_H #include #include #include #include #include #include #include #include "kywirelessnetitem.h" #include "kylinconnectresource.h" #include "kylinactiveconnectresource.h" #include "kywirelessconnectoperation.h" #include "kywirelessnetresource.h" #include "kyenterpricesettinginfo.h" #define AUTO_CONFIG 0 #define MANUAL_CONFIG 1 enum PeapInnerType { MSCHAPV2_PEAP = 0, MD5_PEAP, GTC_PEAP, }; enum TtlsInnerType { PAP = 0, MSCHAP, MSCHAPV2_EAP, MSCHAPV2, CHAP, MD5_EAP, GTC_EAP }; enum FastInnerType { GTC_FAST = 0, MSCHAPV2_FAST, }; enum PacProvisioningInnerType { ANON = 0, AUTHEN, BOTH, }; class LineEdit : public QLineEdit { Q_OBJECT public: explicit LineEdit(QWidget *parent = nullptr) : QLineEdit(parent) {} ~LineEdit() {} protected: void contextMenuEvent(QContextMenuEvent *event) { QMenu *menu = createStandardContextMenu();//默认的标准右键菜单,如果不需要刻意完全自己实现 menu->setPalette(this->palette()); menu->exec(event->globalPos()); delete menu; } }; class ConInfo { public: QString strConName; QString strConType; QString strSecType; KySecuType secType = WPA_AND_WPA2_PERSONAL; QString strPassword; QString strChan; QString strMac; QString strHz; QString strBandWidth; QString strDynamicIpv4; QString strDynamicIpv6; QString strDynamicIpv4Dns; bool isAutoConnect = false; KyIpConfigType ipv4ConfigType = CONFIG_IP_DHCP; QString strIPV4Address; QString strIPV4NetMask; QString strIPV4FirDns; QString strIPV4SecDns; QString strIPV4GateWay; QList ipv4DnsList; KyIpConfigType ipv6ConfigType = CONFIG_IP_DHCP; QString strIPV6Address; int iIPV6Prefix; QString strIPV6FirDns; QString strIPV6SecDns; QString strIPV6GateWay; QList ipv6DnsList; KyEapMethodType enterpriseType; KyEapMethodTlsInfo tlsInfo; KyEapMethodPeapInfo peapInfo; KyEapMethodTtlsInfo ttlsInfo; KyEapMethodLeapInfo leapInfo; KyEapMethodPwdInfo pwdInfo; KyEapMethodFastInfo fastInfo; }; static void setFramePalette(QFrame *widget, QPalette &pal) { QList lineEditList = widget->findChildren(); for (int i = 0; i < lineEditList.count(); ++i) { lineEditList.at(i)->setPalette(pal); lineEditList.at(i)->setContextMenuPolicy(Qt::DefaultContextMenu); } QList comboBoxList = widget->findChildren(); for (int i = 0; i < comboBoxList.count(); ++i) { comboBoxList.at(i)->setPalette(pal); if (comboBoxList.at(i)->view()) { comboBoxList.at(i)->view()->setPalette(pal); } } } static QPalette lightPalette(QWidget *widget) { QPalette palette = qApp->palette(); //ukui-light palette UKUI3.1 亮主题色板 QColor windowText_at(38, 38, 38), windowText_iat(0, 0, 0, 255 * 0.55), windowText_dis(0, 0, 0, 255 * 0.3), button_at(230, 230, 230), button_iat(230, 230, 230), button_dis(233, 233, 233), light_at(255, 255, 255), light_iat(255, 255, 255), light_dis(242, 242, 242), midlight_at(218, 218, 218), midlight_iat(218, 218, 218), midlight_dis(230, 230, 230), dark_at(77, 77, 77), dark_iat(77, 77, 77), dark_dis(64, 64, 64), mid_at(115, 115, 115), mid_iat(115, 115, 115), mid_dis(102, 102, 102), text_at(38, 38, 38), text_iat(38, 38, 38), text_dis(0, 0, 0, 255 * 0.3), brightText_at(0, 0, 0), brightText_iat(0, 0, 0), brightText_dis(0, 0, 0), buttonText_at(38, 38, 38), buttonText_iat(38, 38, 38), buttonText_dis(179, 179, 179), base_at(255, 255, 255), base_iat(245, 245, 245), base_dis(237, 237, 237), window_at(245, 245, 245), window_iat(237, 237, 237), window_dis(230, 230, 230), shadow_at(0, 0, 0, 255 * 0.16), shadow_iat(0, 0, 0, 255 * 0.16), shadow_dis(0, 0, 0, 255 * 0.21), highLightText_at(255, 255, 255), highLightText_iat(255, 255, 255), highLightText_dis(179, 179, 179), alternateBase_at(245, 245, 245), alternateBase_iat(245, 245, 245), alternateBase_dis(245, 245, 245), noRale_at(240, 240, 240), noRole_iat(240, 240, 240), noRole_dis(217, 217, 217), toolTipBase_at(255, 255, 255), toolTipBase_iat(255, 255, 255), toolTipBase_dis(255, 255, 255), toolTipText_at(38, 38, 38), toolTipText_iat(38, 38, 38), toolTipText_dis(38, 38, 38), placeholderText_at(0, 0, 0, 255 * 0.35), placeholderText_iat(0, 0, 0, 255 * 0.35), placeholderText_dis(0, 0, 0, 255 * 0.3); palette.setColor(QPalette::Active, QPalette::WindowText, windowText_at); palette.setColor(QPalette::Inactive, QPalette::WindowText, windowText_iat); palette.setColor(QPalette::Disabled, QPalette::WindowText, windowText_dis); palette.setColor(QPalette::Active, QPalette::Button, button_at); palette.setColor(QPalette::Inactive, QPalette::Button, button_iat); palette.setColor(QPalette::Disabled, QPalette::Button, button_dis); palette.setColor(QPalette::Active, QPalette::Light, light_at); palette.setColor(QPalette::Inactive, QPalette::Light, light_iat); palette.setColor(QPalette::Disabled, QPalette::Light, light_dis); palette.setColor(QPalette::Active, QPalette::Midlight, midlight_at); palette.setColor(QPalette::Inactive, QPalette::Midlight, midlight_iat); palette.setColor(QPalette::Disabled, QPalette::Midlight, midlight_dis); palette.setColor(QPalette::Active, QPalette::Dark, dark_at); palette.setColor(QPalette::Inactive, QPalette::Dark, dark_iat); palette.setColor(QPalette::Disabled, QPalette::Dark, dark_dis); palette.setColor(QPalette::Active, QPalette::Mid, mid_at); palette.setColor(QPalette::Inactive, QPalette::Mid, mid_iat); palette.setColor(QPalette::Disabled, QPalette::Mid, mid_dis); palette.setColor(QPalette::Active, QPalette::Text, text_at); palette.setColor(QPalette::Inactive, QPalette::Text, text_iat); palette.setColor(QPalette::Disabled, QPalette::Text, text_dis); palette.setColor(QPalette::Active, QPalette::BrightText, brightText_at); palette.setColor(QPalette::Inactive, QPalette::BrightText, brightText_iat); palette.setColor(QPalette::Disabled, QPalette::BrightText, brightText_dis); palette.setColor(QPalette::Active, QPalette::ButtonText, buttonText_at); palette.setColor(QPalette::Inactive, QPalette::ButtonText, buttonText_iat); palette.setColor(QPalette::Disabled, QPalette::ButtonText, buttonText_dis); palette.setColor(QPalette::Active, QPalette::Base, base_at); palette.setColor(QPalette::Inactive, QPalette::Base, base_iat); palette.setColor(QPalette::Disabled, QPalette::Base, base_dis); palette.setColor(QPalette::Active, QPalette::Window, window_at); palette.setColor(QPalette::Inactive, QPalette::Window, window_iat); palette.setColor(QPalette::Disabled, QPalette::Window, window_dis); palette.setColor(QPalette::Active, QPalette::Shadow, shadow_at); palette.setColor(QPalette::Inactive, QPalette::Shadow, shadow_iat); palette.setColor(QPalette::Disabled, QPalette::Shadow, shadow_dis); palette.setColor(QPalette::Active, QPalette::HighlightedText, highLightText_at); palette.setColor(QPalette::Inactive, QPalette::HighlightedText, highLightText_iat); palette.setColor(QPalette::Disabled, QPalette::HighlightedText, highLightText_dis); palette.setColor(QPalette::Active, QPalette::AlternateBase, alternateBase_at); palette.setColor(QPalette::Inactive, QPalette::AlternateBase, alternateBase_iat); palette.setColor(QPalette::Disabled, QPalette::AlternateBase, alternateBase_dis); palette.setColor(QPalette::Active, QPalette::NoRole, noRale_at); palette.setColor(QPalette::Inactive, QPalette::NoRole, noRole_iat); palette.setColor(QPalette::Disabled, QPalette::NoRole, noRole_dis); palette.setColor(QPalette::Active, QPalette::ToolTipBase, toolTipBase_at); palette.setColor(QPalette::Inactive, QPalette::ToolTipBase, toolTipBase_iat); palette.setColor(QPalette::Disabled, QPalette::ToolTipBase, toolTipBase_dis); palette.setColor(QPalette::Active, QPalette::ToolTipText, toolTipText_at); palette.setColor(QPalette::Inactive, QPalette::ToolTipText, toolTipText_iat); palette.setColor(QPalette::Disabled, QPalette::ToolTipText, toolTipText_dis); #if (QT_VERSION >= QT_VERSION_CHECK(5,12,0)) palette.setColor(QPalette::Active, QPalette::PlaceholderText, placeholderText_at); palette.setColor(QPalette::Inactive, QPalette::PlaceholderText, placeholderText_iat); palette.setColor(QPalette::Disabled, QPalette::PlaceholderText, placeholderText_dis); #endif return palette; } #endif // CONINFO_H kylin-nm/src/frontend/netdetails/ipv4page.cpp0000664000175000017500000004266515167651420020247 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "ipv4page.h" #include "netdetail.h" #include "math.h" #define LAYOUT_MARGINS 0,0,0,0 #define LAYOUT_SPACING 0 #define HINT_TEXT_MARGINS 8, 1, 0, 3 #define LABEL_HEIGHT 24 #define FRAME_SPEED 150 #define ICON_SIZE 16,16 Ipv4Page::Ipv4Page(QWidget *parent):QFrame(parent) { initUI(); initComponent(); initNetCtrl(); } void Ipv4Page::initUI() { ipv4ConfigCombox = new QComboBox(this); ipv4addressEdit = new LineEdit(this); netMaskEdit = new LineEdit(this); gateWayEdit = new LineEdit(this); m_configLabel = new QLabel(this); m_addressLabel = new QLabel(this); m_maskLabel = new QLabel(this); m_gateWayLabel = new QLabel(this); m_configEmptyLabel = new QLabel(this); m_configEmptyLabel->setFixedHeight(LABEL_HEIGHT); m_addressHintLabel = new KLabel(this); m_addressHintLabel->setFixedHeight(LABEL_HEIGHT); m_addressHintLabel->setContentsMargins(HINT_TEXT_MARGINS); initConflictHintLable(); m_maskHintLabel = new KLabel(this); m_maskHintLabel->setFixedHeight(LABEL_HEIGHT); m_maskHintLabel->setContentsMargins(HINT_TEXT_MARGINS); m_gateWayEmptyLabel = new QLabel(this); m_gateWayEmptyLabel->setFixedHeight(LABEL_HEIGHT); m_dnsEmptyLabel = new QLabel(this); m_dnsEmptyLabel->setFixedHeight(21); m_configLabel->setText(tr("IPv4Config")); m_addressLabel->setText(tr("Address")); m_maskLabel->setText(tr("Netmask")); m_gateWayLabel->setText(tr("Default Gateway")); m_statusLabel = new QLabel(this); m_statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); QHBoxLayout *pPwdLayout = new QHBoxLayout(ipv4addressEdit); pPwdLayout->addStretch(); pPwdLayout->addWidget(m_statusLabel); //V11 qlabel 使用调色板颜色显示有问题 m_addressHintLabel->setFontColorRole(QPalette::WindowText); m_addressHintLabel->setFontColor(Qt::red); m_maskHintLabel->setFontColorRole(QPalette::WindowText); m_maskHintLabel->setFontColor(Qt::red); QWidget *addressWidget = new QWidget(this); QVBoxLayout *addressLayout = new QVBoxLayout(addressWidget); addressLayout->setContentsMargins(LAYOUT_MARGINS); addressLayout->setSpacing(LAYOUT_SPACING); addressLayout->addWidget(ipv4addressEdit); addressLayout->addWidget(m_addressHintLabel); QWidget *maskWidget = new QWidget(this); QVBoxLayout *maskLayout = new QVBoxLayout(maskWidget); maskLayout->setContentsMargins(LAYOUT_MARGINS); maskLayout->setSpacing(LAYOUT_SPACING); maskLayout->addWidget(netMaskEdit); maskLayout->addWidget(m_maskHintLabel); // IP的正则格式限制 QRegularExpression rx("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); Divider* divider = new Divider(false, this); m_dnsWidget = new MultipleDnsWidget(rx, true, this); m_detailLayout = new QFormLayout(this); m_detailLayout->setVerticalSpacing(0); m_detailLayout->setContentsMargins(LAYOUT_MARGINS); m_detailLayout->addRow(m_configLabel,ipv4ConfigCombox); m_detailLayout->addRow(m_configEmptyLabel); m_detailLayout->addRow(m_addressLabel,addressWidget); m_detailLayout->addRow(m_maskLabel,maskWidget); m_detailLayout->addRow(m_gateWayLabel,gateWayEdit); m_detailLayout->addRow(m_gateWayEmptyLabel); m_detailLayout->addRow(divider); m_detailLayout->addRow(m_dnsEmptyLabel); m_detailLayout->addRow(m_dnsWidget); m_addressLabel->setContentsMargins(0, 0, 0, LABEL_HEIGHT); //解决布局错位问题 m_maskLabel->setContentsMargins(0, 0, 0, LABEL_HEIGHT); ipv4ConfigCombox->addItem(tr("Auto(DHCP)")); //"自动(DHCP)" ipv4ConfigCombox->addItem(tr("Manual")); //"手动" // netMaskCombox->addItem(""); // netMaskCombox->addItem("255.255.255.0"); //24 // netMaskCombox->addItem("255.255.254.0"); //23 // netMaskCombox->addItem("255.255.252.0"); //22 // netMaskCombox->addItem("255.255.0.0"); //16 // netMaskCombox->addItem("255.0.0.0"); //8 ipv4addressEdit->setValidator(new QRegularExpressionValidator(rx, this)); gateWayEdit->setValidator(new QRegularExpressionValidator(rx, this)); netMaskEdit->setValidator(new QRegularExpressionValidator(rx, this)); initLoadingIcon(); } void Ipv4Page::initComponent() { if (ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { setLineEnabled(false); } else if (ipv4ConfigCombox->currentIndex() == MANUAL_CONFIG) { setLineEnabled(true); } connect(ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(configChanged(int))); connect(ipv4addressEdit, SIGNAL(textChanged(QString)), this, SLOT(onAddressTextChanged())); connect(ipv4addressEdit, SIGNAL(editingFinished()), this, SLOT(onAddressEditFinished())); connect(netMaskEdit, SIGNAL(textChanged(QString)), this, SLOT(onNetMaskTextChanged())); connect(ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); connect(ipv4addressEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(netMaskEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(gateWayEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(m_dnsWidget, &MultipleDnsWidget::scrollToBottom, this, &Ipv4Page::scrollToBottom); } void Ipv4Page::setIpv4Config(KyIpConfigType ipv4Config) { if (ipv4Config == CONFIG_IP_MANUAL) { ipv4ConfigCombox->setCurrentIndex(MANUAL_CONFIG); } else { ipv4ConfigCombox->setCurrentIndex(AUTO_CONFIG); } } void Ipv4Page::setIpv4(const QString &ipv4) { ipv4addressEdit->setText(ipv4); } void Ipv4Page::setNetMask(const QString &netMask) { netMaskEdit->setText(netMask); } void Ipv4Page::setMulDns(const QList &dns) { m_dnsWidget->setDnsListText(dns); } void Ipv4Page::setGateWay(const QString &gateWay) { gateWayEdit->setText(gateWay); } bool Ipv4Page::checkIsChanged(const ConInfo info, KyConnectSetting &setting) { bool isChanged = false; KyIpConfigType type; if (ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { type = CONFIG_IP_DHCP; if (info.ipv4ConfigType != CONFIG_IP_DHCP) { qDebug() << "ipv4ConfigType change to Auto"; isChanged = true; } } else { type = CONFIG_IP_MANUAL; if (info.ipv4ConfigType != CONFIG_IP_MANUAL) { qDebug() << "ipv4ConfigType change to Manual"; isChanged = true; } else { if(info.strIPV4Address != ipv4addressEdit->text() || info.strIPV4NetMask != getNetMaskText(netMaskEdit->text()) || info.strIPV4GateWay != gateWayEdit->text()) { qDebug() << "ipv4 info changed"; isChanged = true; } } } QList ipv4dnsList; ipv4dnsList.clear(); ipv4dnsList = m_dnsWidget->getDns(); if(info.ipv4DnsList != ipv4dnsList) { isChanged = true; } if (isChanged) { setting.setIpConfigType(IPADDRESS_V4, type); QString ipv4address = ipv4addressEdit->text(); QString netMask = getNetMaskText(netMaskEdit->text()); QString gateWay = gateWayEdit->text(); setting.ipv4AddressConstruct(ipv4address, netMask, gateWay); setting.ipv4DnsConstruct(ipv4dnsList); setting.dumpInfo(); } return isChanged; } bool Ipv4Page::checkDnsSettingsIsChanged() { return m_dnsWidget->getDnsSettingsChanged(); } bool Ipv4Page::checkConnectBtnIsEnabled() { qDebug() << "checkConnectBtnIsEnabled currentIndex" << ipv4ConfigCombox->currentIndex(); if (ipv4ConfigCombox->currentIndex() != AUTO_CONFIG) { if (ipv4addressEdit->text().isEmpty() || !getTextEditState(ipv4addressEdit->text())) { qDebug() << "ipv4address empty or invalid"; m_errorMessage = tr("IPv4 address is empty or invalid"); return false; } if (netMaskEdit->text().isEmpty() || !netMaskIsValide(netMaskEdit->text())) { qDebug() << "ipv4 netMask empty or invalid"; m_errorMessage = tr("IPv4 netMask is empty or invalid"); return false; } if (/*gateWayEdit->text().isEmpty() ||*/ !getTextEditState(gateWayEdit->text())) { qDebug() << "ipv4 gateway empty or invalid"; m_errorMessage = tr("IPv4 gateway is empty or invalid"); return false; } } m_errorMessage.clear(); return true; } void Ipv4Page::configChanged(int index) { if (index == AUTO_CONFIG) { setLineEnabled(false); } if (index == MANUAL_CONFIG) { setLineEnabled(true); } } void Ipv4Page::onAddressTextChanged() { m_iconLabel->hide(); m_textLabel->hide(); if (!getTextEditState(ipv4addressEdit->text())) { m_addressHintLabel->setText(tr("Invalid address")); } else { m_addressHintLabel->clear(); } } void Ipv4Page::onNetMaskTextChanged() { if (!netMaskIsValide(netMaskEdit->text())) { m_maskHintLabel->setText(tr("Invalid subnet mask")); } else { m_maskHintLabel->clear(); } } void Ipv4Page::onAddressEditFinished() { if (ipv4addressEdit->isModified()) { if (!ipv4addressEdit->text().isEmpty() && getTextEditState(ipv4addressEdit->text())) { Q_EMIT ipv4EditFinished(ipv4addressEdit->text()); } } } void Ipv4Page::setLineEnabled(bool check) { if (!check) { ipv4addressEdit->clear(); netMaskEdit->clear(); gateWayEdit->clear(); ipv4addressEdit->setPlaceholderText(" "); netMaskEdit->setPlaceholderText(" "); gateWayEdit->setPlaceholderText(" "); } else { ipv4addressEdit->setPlaceholderText(tr("Required")); //必填 netMaskEdit->setPlaceholderText(tr("Required")); //必填 } updateUi(); } void Ipv4Page::setEnableOfSaveBtn() { Q_EMIT setIpv4PageState(checkConnectBtnIsEnabled()); } bool Ipv4Page::getTextEditState(QString text) { if (text.isEmpty()) { return true; } // IP地址正则表达式,包含开始和结束锚点确保完全匹配 QRegularExpression rx("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); // 进行匹配并返回结果 QRegularExpressionMatch match = rx.match(text); return match.hasMatch(); } bool Ipv4Page::netMaskIsValide(QString text) { if (getTextEditState(text)) { return true; } else { if (text.length() > 0 && text.length() < 3) { int num = text.toInt(); if (num > 0 && num < 33) { return true; } } } return false; } QString Ipv4Page::getNetMaskText(QString text) { if (text.length() > 2) { return text; } int num = text.toInt(); QStringList list; list << "0" << "0" << "0" << "0"; int count = 0; while (num - 8 >= 0) { list[count] = "255"; num = num - 8; count ++; } if (num > 0) { int size = pow(2, 8) - pow(2,(8-num)); list[count] = QString::number(size); } return QString("%1.%2.%3.%4").arg(list[0],list[1],list[2],list[3]); } void Ipv4Page::initConflictHintLable() { QIcon icon = QIcon::fromTheme("dialog-warning"); m_iconLabel = new QLabel(m_addressHintLabel); m_iconLabel->setPixmap(icon.pixmap(ICON_SIZE)); m_textLabel = new KLabel(m_addressHintLabel); m_textLabel->setText(tr("Address conflict")); m_textLabel->setFontColorRole(QPalette::WindowText); m_textLabel->setFontColor(Qt::red); QHBoxLayout *conflictHintLayout = new QHBoxLayout(m_addressHintLabel); conflictHintLayout->setContentsMargins(0, 0, 0, 0); conflictHintLayout->addWidget(m_iconLabel); conflictHintLayout->addWidget(m_textLabel); conflictHintLayout->addStretch(); m_addressHintLabel->setLayout(conflictHintLayout); m_iconLabel->hide(); m_textLabel->hide(); } void Ipv4Page::initLoadingIcon() { m_loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); m_iconTimer = new QTimer(this); connect(m_iconTimer, &QTimer::timeout, this, &Ipv4Page::updateIcon); } void Ipv4Page::updateIcon() { if (m_currentIconIndex > 6) { m_currentIconIndex = 0; } m_statusLabel->setPixmap(m_loadIcons.at(m_currentIconIndex).pixmap(ICON_SIZE)); m_currentIconIndex ++; } void Ipv4Page::startLoading() { m_iconTimer->start(FRAME_SPEED); } void Ipv4Page::stopLoading() { m_iconTimer->stop(); m_statusLabel->clear(); } void Ipv4Page::showIpv4AddressConflict(bool isConflict) { if (isConflict) { m_iconLabel->show(); m_textLabel->show(); } else { m_iconLabel->hide(); m_textLabel->hide(); } } QString Ipv4Page::getErrorMessage() { checkConnectBtnIsEnabled(); return m_errorMessage; } void Ipv4Page::updateNetCtrl(QString modName, QVariantMap value) { if(modName!="IPV4" && modName!="DNS") return; qInfo()<currentIndex(); if (m_ipv4addressCtrl || currentIndex==AUTO_CONFIG) { ipv4addressEdit->setEnabled(false); } else { ipv4addressEdit->setEnabled(true); } if (m_netMaskCtrl || currentIndex==AUTO_CONFIG) { netMaskEdit->setEnabled(false); } else { netMaskEdit->setEnabled(true); } if (m_gateWayCtrl || currentIndex==AUTO_CONFIG) { gateWayEdit->setEnabled(false); } else { gateWayEdit->setEnabled(true); } if(m_dnsWayCtrl) { m_dnsWidget->setEnabled(false); } else { m_dnsWidget->setEnabled(true); } } void Ipv4Page::initNetCtrl() { QVariantMap map; int errCode=0; QString netCtrlIPV4Name="IPV4"; QString netCtrlDNSName="DNS"; QDBusInterface dbusInterface("com.kylin.networkCtrol", "/com/kylin/networkCtrol", "com.kylin.networkCtrol", QDBusConnection::systemBus()); if (!dbusInterface.isValid()) { qWarning()<=2) { const QDBusArgument &dbusArg1st = result.arguments().at( 0 ).value(); dbusArg1st >> map; errCode = result.arguments().at( 1 ).toInt(); qInfo()<<"ipv4"<=2) { const QDBusArgument &dbusArg1st = result.arguments().at( 0 ).value(); dbusArg1st >> map; errCode = result.arguments().at( 1 ).toInt(); qInfo()<<"ipv4"< #include #include #include #include #include #include #include #include #include #include "klabel.h" //#include "kylinconnectsetting.h" #include "coninfo.h" #include "multiplednswidget.h" class Ipv6Page : public QFrame { Q_OBJECT public: Ipv6Page(QWidget *parent = nullptr); void setIpv6Config(KyIpConfigType ipv6Config); void setIpv6(const QString &ipv4); void setIpv6Perfix(const int &ipv6Perfix); void setMulDns(const QList &dns); void setGateWay(const QString &gateWay); bool checkIsChanged(const ConInfo info, KyConnectSetting &setting); int getPerfixLength(QString text); void startLoading(); void stopLoading(); void showIpv6AddressConflict(bool isConflict); QString getErrorMessage(); private: QComboBox *ipv6ConfigCombox; LineEdit *ipv6AddressEdit; LineEdit *lengthEdit; LineEdit *gateWayEdit; QFormLayout *m_detailLayout; QLabel *m_configLabel; QLabel *m_addressLabel; QLabel *m_subnetLabel; QLabel *m_gateWayLabel; QLabel *m_configEmptyLabel; KLabel *m_addressHintLabel; QLabel *m_subnetEmptyLabel; KLabel *m_gateWayHintLabel; MultipleDnsWidget *m_dnsWidget = nullptr; QLabel *m_statusLabel = nullptr; QList m_loadIcons; QTimer *m_iconTimer = nullptr; int m_currentIconIndex =0; QLabel *m_iconLabel; QLabel *m_textLabel; QString m_errorMessage; //kylin 网络设置控制接口 bool m_ipaddressCtrl = false; bool m_netMaskCtrl = false; bool m_gateWayCtrl = false; bool m_dnsWayCtrl = false; private: void initUI(); void initComponent(); void setControlEnabled(bool check); bool getIpv6EditState(QString text); bool checkConnectBtnIsEnabled(); void initConflictHintLable(); void initLoadingIcon(); void initNetCtrl(); void updateUi(); private Q_SLOTS: void configChanged(int index); void setEnableOfSaveBtn(); void onAddressTextChanged(); void onGatewayTextChanged(); void onAddressEidtFinished(); void updateIcon(); void updateNetCtrl(QString modName,QVariantMap value); Q_SIGNALS: void setIpv6PageState(bool); void ipv6EditFinished(const QString &address); void scrollToBottom(); }; #endif // IPV6PAGE_H kylin-nm/src/frontend/netdetails/creatnetpage.cpp0000664000175000017500000003227515167651420021166 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "creatnetpage.h" #include "math.h" #define MAX_NAME_LENGTH 32 #define HINT_TEXT_MARGINS 8, 1, 0, 3 #define LABEL_HEIGHT 24 #define FRAME_SPEED 150 #define ICON_SIZE 16,16 CreatNetPage::CreatNetPage(QWidget *parent):QFrame(parent) { initUI(); initComponent(); } void CreatNetPage::initUI() { connNameEdit = new LineEdit(this); ipv4ConfigCombox = new QComboBox(this); ipv4addressEdit = new LineEdit(this); netMaskEdit = new LineEdit(this); gateWayEdit = new LineEdit(this); m_connNameLabel = new QLabel(this); m_configLabel = new QLabel(this); m_addressLabel = new QLabel(this); m_maskLabel = new QLabel(this); m_gateWayLabel = new QLabel(this); // IP的正则格式限制 QRegularExpression rx("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); m_dnsWidget = new MultipleDnsWidget(rx, false, this); QLabel *nameEmptyLabel = new QLabel(this); QLabel *configEmptyLabel = new QLabel(this); QLabel *gateWayEmptyLabel = new QLabel(this); QLabel *firstDnsEmptyLabel = new QLabel(this); nameEmptyLabel->setFixedHeight(LABEL_HEIGHT); configEmptyLabel->setFixedHeight(LABEL_HEIGHT); gateWayEmptyLabel->setFixedHeight(LABEL_HEIGHT); firstDnsEmptyLabel->setFixedHeight(LABEL_HEIGHT); m_addressHintLabel = new KLabel(this); m_maskHintLabel = new KLabel(this); m_addressHintLabel->setFixedHeight(LABEL_HEIGHT); m_maskHintLabel->setFixedHeight(LABEL_HEIGHT); m_addressHintLabel->setContentsMargins(HINT_TEXT_MARGINS); m_maskHintLabel->setContentsMargins(HINT_TEXT_MARGINS); m_statusLabel = new QLabel(this); m_statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); QHBoxLayout *pPwdLayout = new QHBoxLayout(ipv4addressEdit); pPwdLayout->addStretch(); pPwdLayout->addWidget(m_statusLabel); m_addressHintLabel->setFontColorRole(QPalette::WindowText); m_addressHintLabel->setFontColor(Qt::red); m_maskHintLabel->setFontColorRole(QPalette::WindowText); m_maskHintLabel->setFontColor(Qt::red); QWidget *addressWidget = new QWidget(this); QVBoxLayout *addressLayout = new QVBoxLayout(addressWidget); addressLayout->setContentsMargins(0, 0, 0, 0); addressLayout->setSpacing(0); addressLayout->addWidget(ipv4addressEdit); addressLayout->addWidget(m_addressHintLabel); initConflictHintLable(); QWidget *maskWidget = new QWidget(this); QVBoxLayout *maskLayout = new QVBoxLayout(maskWidget); maskLayout->setContentsMargins(0, 0, 0, 0); maskLayout->setSpacing(0); maskLayout->addWidget(netMaskEdit); maskLayout->addWidget(m_maskHintLabel); m_connNameLabel->setText(tr("Connection Name")); m_configLabel->setText(tr("IPv4Config")); m_addressLabel->setText(tr("Address")); m_maskLabel->setText(tr("Netmask")); m_gateWayLabel->setText(tr("Default Gateway")); m_detailLayout = new QFormLayout(this); m_detailLayout->setVerticalSpacing(0); m_detailLayout->setContentsMargins(0, 0, 0, 0); m_detailLayout->addRow(m_connNameLabel,connNameEdit); m_detailLayout->addRow(nameEmptyLabel); m_detailLayout->addRow(m_configLabel,ipv4ConfigCombox); m_detailLayout->addRow(configEmptyLabel); m_detailLayout->addRow(m_addressLabel, addressWidget); m_detailLayout->addRow(m_maskLabel, maskWidget); m_detailLayout->addRow(m_gateWayLabel,gateWayEdit); m_detailLayout->addRow(gateWayEmptyLabel); m_addressLabel->setContentsMargins(0, 0, 0, LABEL_HEIGHT); //解决布局错位问题 m_maskLabel->setContentsMargins(0, 0, 0, LABEL_HEIGHT); m_detailLayout->addRow(m_dnsWidget); ipv4ConfigCombox->addItem(tr("Auto(DHCP)"), AUTO_CONFIG); //"自动(DHCP)" ipv4ConfigCombox->addItem(tr("Manual"), MANUAL_CONFIG); //"手动" QRegularExpression nameRx("^.{0,32}$"); QValidator *validator = new QRegularExpressionValidator(nameRx, this); connNameEdit->setValidator(validator); ipv4addressEdit->setValidator(new QRegularExpressionValidator(rx, this)); gateWayEdit->setValidator(new QRegularExpressionValidator(rx, this)); netMaskEdit->setValidator(new QRegularExpressionValidator(rx, this)); initLoadingIcon(); } void CreatNetPage::initComponent() { if (ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { setLineEnabled(false); } else if (ipv4ConfigCombox->currentIndex() == MANUAL_CONFIG) { setLineEnabled(true); } connect(ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(configChanged(int))); connect(connNameEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); connect(netMaskEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(gateWayEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(ipv4addressEdit, SIGNAL(textChanged(QString)), this, SLOT(onAddressTextChanged())); connect(ipv4addressEdit, SIGNAL(editingFinished()), this, SLOT(onAddressEditFinished())); connect(netMaskEdit, SIGNAL(textChanged(QString)), this, SLOT(onNetMaskTextChanged())); } bool CreatNetPage::checkConnectBtnIsEnabled() { if (connNameEdit->text().isEmpty()) { qDebug() << "create connName empty or invalid"; m_errorMessage = tr("Connection name is empty or invalid"); return false; } qDebug() << "checkConnectBtnIsEnabled currentIndex" << ipv4ConfigCombox->currentIndex(); if (ipv4ConfigCombox->currentIndex() != AUTO_CONFIG) { if (ipv4addressEdit->text().isEmpty() || !getTextEditState(ipv4addressEdit->text())) { qDebug() << "create ipv4address empty or invalid"; m_errorMessage = tr("IPv4 address is empty or invalid"); return false; } if (netMaskEdit->text().isEmpty() || !netMaskIsValide(netMaskEdit->text())) { qDebug() << "create ipv4 netMask empty or invalid"; m_errorMessage = tr("IPv4 netMask is empty or invalid"); return false; } if (/*gateWayEdit->text().isEmpty() ||*/ !getTextEditState(gateWayEdit->text())) { qDebug() << "create ipv4 gateway empty or invalid"; m_errorMessage = tr("IPv4 gateway is empty or invalid"); return false; } } m_errorMessage.clear(); return true; } void CreatNetPage::configChanged(int index) { if (index == AUTO_CONFIG) { setLineEnabled(false); } if (index == MANUAL_CONFIG) { setLineEnabled(true); } } void CreatNetPage::onAddressTextChanged() { m_iconLabel->hide(); m_textLabel->hide(); if (!getTextEditState(ipv4addressEdit->text())) { m_addressHintLabel->setText(tr("Invalid address")); } else { m_addressHintLabel->clear(); } } void CreatNetPage::onAddressEditFinished() { if (ipv4addressEdit->isModified()) { if (!ipv4addressEdit->text().isEmpty() && getTextEditState(ipv4addressEdit->text())) { Q_EMIT ipv4EditFinished(ipv4addressEdit->text()); } } } void CreatNetPage::onNetMaskTextChanged() { if (!netMaskIsValide(netMaskEdit->text())) { m_maskHintLabel->setText(tr("Invalid subnet mask")); } else { m_maskHintLabel->clear(); } } void CreatNetPage::setLineEnabled(bool check) { ipv4addressEdit->setEnabled(check); netMaskEdit->setEnabled(check); gateWayEdit->setEnabled(check); if (!check) { ipv4addressEdit->clear(); netMaskEdit->clear(); gateWayEdit->clear(); ipv4addressEdit->setPlaceholderText(" "); netMaskEdit->setPlaceholderText(" "); gateWayEdit->setPlaceholderText(" "); } else { ipv4addressEdit->setPlaceholderText(tr("Required")); //必填 netMaskEdit->setPlaceholderText(tr("Required")); //必填 gateWayEdit->setPlaceholderText(tr(" ")); //必填 } } void CreatNetPage::setEnableOfSaveBtn() { Q_EMIT setCreatePageState(checkConnectBtnIsEnabled()); } bool CreatNetPage::getTextEditState(QString text) { if (text.isEmpty()) { return true; } // IP地址正则表达式,包含开始和结束锚点确保完全匹配 QRegularExpression rx("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); // 进行匹配并返回结果 QRegularExpressionMatch match = rx.match(text); return match.hasMatch(); } void CreatNetPage::constructIpv4Info(KyConnectSetting &setting) { setting.m_connectName = connNameEdit->text(); QString ipv4address =ipv4addressEdit->text(); QString netMask = getNetMaskText(netMaskEdit->text()); QString gateWay = gateWayEdit->text(); qDebug() << "constructIpv4Info: " << "ipv4address " << ipv4address << " netMask " << netMask << " gateWay " << gateWay; QStringList dnsList; dnsList.clear(); #if 0 if (!firstDnsEdit->text().isEmpty()) { dnsList << firstDnsEdit->text(); if (!secondDnsEdit->text().isEmpty()) { dnsList << secondDnsEdit->text(); } } #endif QList ipv4dnsList; ipv4dnsList.clear(); ipv4dnsList = m_dnsWidget->getDns(); if (ipv4ConfigCombox->currentData() == AUTO_CONFIG) { setting.setIpConfigType(IPADDRESS_V4, CONFIG_IP_DHCP); } else { setting.setIpConfigType(IPADDRESS_V4, CONFIG_IP_MANUAL); setting.ipv4AddressConstruct(ipv4address, netMask, gateWay); } setting.ipv4DnsConstruct(ipv4dnsList); } bool CreatNetPage::netMaskIsValide(QString text) { if (getTextEditState(text)) { return true; } else { if (text.length() > 0 && text.length() < 3) { int num = text.toInt(); if (num > 0 && num < 33) { return true; } } } return false; } QString CreatNetPage::getNetMaskText(QString text) { if (text.length() > 2) { return text; } int num = text.toInt(); QStringList list; list << "0" << "0" << "0" << "0"; int count = 0; while (num - 8 >= 0) { list[count] = "255"; num = num - 8; count ++; } if (num > 0) { int size = pow(2, 8) - pow(2,(8-num)); list[count] = QString::number(size); } return QString("%1.%2.%3.%4").arg(list[0],list[1],list[2],list[3]); } void CreatNetPage::initConflictHintLable() { QIcon icon = QIcon::fromTheme("dialog-warning"); m_iconLabel = new QLabel(m_addressHintLabel); m_iconLabel->setPixmap(icon.pixmap(ICON_SIZE)); m_textLabel = new KLabel(m_addressHintLabel); m_textLabel->setText(tr("Address conflict")); m_textLabel->setFontColorRole(QPalette::WindowText); m_textLabel->setFontColor(Qt::red); QHBoxLayout *conflictHintLayout = new QHBoxLayout(m_addressHintLabel); conflictHintLayout->setContentsMargins(0, 0, 0, 0); conflictHintLayout->addWidget(m_iconLabel); conflictHintLayout->addWidget(m_textLabel); conflictHintLayout->addStretch(); m_addressHintLabel->setLayout(conflictHintLayout); m_iconLabel->hide(); m_textLabel->hide(); } void CreatNetPage::initLoadingIcon() { m_loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); m_iconTimer = new QTimer(this); connect(m_iconTimer, &QTimer::timeout, this, &CreatNetPage::updateIcon); } void CreatNetPage::updateIcon() { if (m_currentIconIndex > 6) { m_currentIconIndex = 0; } m_statusLabel->setPixmap(m_loadIcons.at(m_currentIconIndex).pixmap(ICON_SIZE)); m_currentIconIndex ++; } void CreatNetPage::startLoading() { m_iconTimer->start(FRAME_SPEED); } void CreatNetPage::stopLoading() { m_iconTimer->stop(); m_statusLabel->clear(); } void CreatNetPage::showIpv4AddressConflict(bool isConflict) { if (isConflict) { m_iconLabel->show(); m_textLabel->show(); } else { m_iconLabel->hide(); m_textLabel->hide(); } } QString CreatNetPage::getErrorMessage() { checkConnectBtnIsEnabled(); return m_errorMessage; } kylin-nm/src/frontend/netdetails/ipv6page.cpp0000664000175000017500000004510115167651420020235 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "ipv6page.h" #include "netdetail.h" #define LAYOUT_MARGINS 0,0,0,0 #define LAYOUT_SPACING 0 #define HINT_TEXT_MARGINS 8, 1, 0, 3 #define LABEL_HEIGHT 24 #define FRAME_SPEED 150 #define ICON_SIZE 16,16 Ipv6Page::Ipv6Page(QWidget *parent):QFrame(parent) { initUI(); initComponent(); initNetCtrl(); } void Ipv6Page::setIpv6Config(KyIpConfigType ipv6Config) { if (ipv6Config == CONFIG_IP_MANUAL) { ipv6ConfigCombox->setCurrentIndex(MANUAL_CONFIG); } else { ipv6ConfigCombox->setCurrentIndex(AUTO_CONFIG); } } void Ipv6Page::setIpv6(const QString &ipv6) { ipv6AddressEdit->setText(ipv6); } void Ipv6Page::setIpv6Perfix(const int &ipv6Perfix) { lengthEdit->setText(QString::number(ipv6Perfix)); } void Ipv6Page::setMulDns(const QList &dns) { m_dnsWidget->setDnsListText(dns); } void Ipv6Page::setGateWay(const QString &gateWay) { gateWayEdit->setText(gateWay); } bool Ipv6Page::checkIsChanged(const ConInfo info, KyConnectSetting &setting) { bool isChanged = false; KyIpConfigType type; if (ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { type = CONFIG_IP_DHCP; if (info.ipv6ConfigType != CONFIG_IP_DHCP) { qDebug() << "ipv6ConfigType change to Auto"; isChanged = true; } } else { type = CONFIG_IP_MANUAL; if (info.ipv6ConfigType != CONFIG_IP_MANUAL) { qDebug() << "ipv6ConfigType change to Manual"; isChanged = true; } if(info.strIPV6Address != ipv6AddressEdit->text() || info.iIPV6Prefix != lengthEdit->text().toInt() || info.strIPV6GateWay != gateWayEdit->text()) { isChanged = true; } } QList ipv6dnsList; ipv6dnsList.clear(); ipv6dnsList = m_dnsWidget->getDns(); if (info.ipv6DnsList != ipv6dnsList) { isChanged = true; } if (isChanged) { setting.setIpConfigType(IPADDRESS_V6, type); QString ipv6address =ipv6AddressEdit->text(); QString prefix = lengthEdit->text(); QString gateWay = gateWayEdit->text(); setting.ipv6AddressConstruct(ipv6address, prefix, gateWay); setting.ipv6DnsConstruct(ipv6dnsList); setting.dumpInfo(); } return isChanged; } void Ipv6Page::initUI() { ipv6ConfigCombox = new QComboBox(this); ipv6AddressEdit = new LineEdit(this); lengthEdit = new LineEdit(this); gateWayEdit = new LineEdit(this); m_configLabel = new QLabel(this); m_addressLabel = new QLabel(this); m_subnetLabel = new QLabel(this); m_gateWayLabel = new QLabel(this); m_configEmptyLabel = new QLabel(this); m_configEmptyLabel->setFixedHeight(LABEL_HEIGHT); m_addressHintLabel = new KLabel(this); m_addressHintLabel->setFixedHeight(LABEL_HEIGHT); m_addressHintLabel->setContentsMargins(HINT_TEXT_MARGINS); initConflictHintLable(); m_gateWayHintLabel = new KLabel(this); m_gateWayHintLabel->setFixedHeight(LABEL_HEIGHT); m_gateWayHintLabel->setContentsMargins(HINT_TEXT_MARGINS); m_subnetEmptyLabel = new QLabel(this); m_subnetEmptyLabel->setFixedHeight(LABEL_HEIGHT); m_configLabel->setText(tr("IPv6Config")); m_addressLabel->setText(tr("Address")); m_subnetLabel->setText(tr("Subnet prefix Length")); m_gateWayLabel->setText(tr("Default Gateway")); m_statusLabel = new QLabel(this); m_statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); QHBoxLayout *pPwdLayout = new QHBoxLayout(ipv6AddressEdit); pPwdLayout->addStretch(); pPwdLayout->addWidget(m_statusLabel); //V11 qlabel 使用调色板颜色显示有问题 m_addressHintLabel->setFontColorRole(QPalette::WindowText); m_addressHintLabel->setFontColor(Qt::red); m_gateWayHintLabel->setFontColorRole(QPalette::WindowText); m_gateWayHintLabel->setFontColor(Qt::red); QWidget *addressWidget = new QWidget(this); QVBoxLayout *addressLayout = new QVBoxLayout(addressWidget); addressLayout->setContentsMargins(LAYOUT_MARGINS); addressLayout->setSpacing(LAYOUT_SPACING); addressLayout->addWidget(ipv6AddressEdit); addressLayout->addWidget(m_addressHintLabel); QWidget *gateWayWidget = new QWidget(this); QVBoxLayout *gateWayLayout = new QVBoxLayout(gateWayWidget); gateWayLayout->setContentsMargins(LAYOUT_MARGINS); gateWayLayout->setSpacing(LAYOUT_SPACING); gateWayLayout->addWidget(gateWayEdit); gateWayLayout->addWidget(m_gateWayHintLabel); QRegularExpression ipv6_rx("^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$"); m_dnsWidget = new MultipleDnsWidget(ipv6_rx, false, this); m_detailLayout = new QFormLayout(this); m_detailLayout->setContentsMargins(0, 0, 0, 0); m_detailLayout->setVerticalSpacing(0); m_detailLayout->addRow(m_configLabel,ipv6ConfigCombox); m_detailLayout->addRow(m_configEmptyLabel); m_detailLayout->addRow(m_addressLabel,addressWidget); m_detailLayout->addRow(m_subnetLabel,lengthEdit); m_detailLayout->addRow(m_subnetEmptyLabel); m_detailLayout->addRow(m_gateWayLabel,gateWayWidget); m_detailLayout->addRow(m_dnsWidget); m_addressLabel->setContentsMargins(0, 0, 0, LABEL_HEIGHT); //解决布局错位问题 m_gateWayLabel->setContentsMargins(0, 0, 0, LABEL_HEIGHT); ipv6ConfigCombox->addItem(tr("Auto(DHCP)")); //"自动(DHCP)" ipv6ConfigCombox->addItem(tr("Manual")); //"手动" ipv6AddressEdit->setValidator(new QRegularExpressionValidator(ipv6_rx, this)); gateWayEdit->setValidator(new QRegularExpressionValidator(ipv6_rx, this)); QRegularExpression prefix_rx("\\b(?:(?:12[0-8]|1[0-1][0-9]|^[1-9][0-9]?$)\\.){3}(?:12[0-8]|1[0-1][0-9]|^[1-9][0-9]?$)\\b"); lengthEdit->setValidator(new QRegularExpressionValidator(prefix_rx,this)); initLoadingIcon(); } void Ipv6Page::initComponent() { if (ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { setControlEnabled(false); } else if (ipv6ConfigCombox->currentIndex() == MANUAL_CONFIG) { setControlEnabled(true); } connect(ipv6ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(configChanged(int))); connect(ipv6AddressEdit, SIGNAL(textChanged(QString)), this, SLOT(onAddressTextChanged())); connect(ipv6AddressEdit, SIGNAL(editingFinished()), this, SLOT(onAddressEidtFinished())); connect(gateWayEdit, SIGNAL(textChanged(QString)), this, SLOT(onGatewayTextChanged())); connect(ipv6ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); connect(ipv6AddressEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(lengthEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(gateWayEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(m_dnsWidget, &MultipleDnsWidget::scrollToBottom, this, &Ipv6Page::scrollToBottom); } void Ipv6Page::configChanged(int index) { if (index == AUTO_CONFIG) { setControlEnabled(false); } if (index == MANUAL_CONFIG) { setControlEnabled(true); } } void Ipv6Page::setControlEnabled(bool check) { if (!check) { ipv6AddressEdit->clear(); lengthEdit->clear(); gateWayEdit->clear(); ipv6AddressEdit->setPlaceholderText(" "); lengthEdit->setPlaceholderText(" "); gateWayEdit->setPlaceholderText(" "); } else { ipv6AddressEdit->setPlaceholderText(tr("Required")); //必填 lengthEdit->setPlaceholderText(tr("Required")); //必填 } updateUi(); } void Ipv6Page::setEnableOfSaveBtn() { Q_EMIT setIpv6PageState(checkConnectBtnIsEnabled()); } void Ipv6Page::onAddressTextChanged() { m_iconLabel->hide(); m_textLabel->hide(); if (!getIpv6EditState(ipv6AddressEdit->text())) { m_addressHintLabel->setText(tr("Invalid address")); } else { m_addressHintLabel->clear(); } } void Ipv6Page::onGatewayTextChanged() { if (!getIpv6EditState(gateWayEdit->text())) { m_gateWayHintLabel->setText(tr("Invalid gateway")); } else { m_gateWayHintLabel->clear(); } } void Ipv6Page::onAddressEidtFinished() { if (ipv6AddressEdit->isModified()) { if (!ipv6AddressEdit->text().isEmpty() && getIpv6EditState(ipv6AddressEdit->text())) { Q_EMIT ipv6EditFinished(ipv6AddressEdit->text()); } } } bool Ipv6Page::checkConnectBtnIsEnabled() { if (ipv6ConfigCombox->currentIndex() != AUTO_CONFIG){ if (ipv6AddressEdit->text().isEmpty() || !getIpv6EditState(ipv6AddressEdit->text())) { qDebug() << "ipv6address empty or invalid"; m_errorMessage = tr("IPv6 address is empty or invalid"); return false; } if (lengthEdit->text().isEmpty()) { qDebug() << "ipv6 prefix length empty"; m_errorMessage = tr("IPv6 prefix length is empty or invalid"); return false; } // if (gateWayEdit->text().isEmpty() || !getIpv6EditState(gateWayEdit->text())) { // qDebug() << "ipv6 gateway empty or invalid"; // return false; // } } m_errorMessage.clear(); return true; } void Ipv6Page::initConflictHintLable() { QIcon icon = QIcon::fromTheme("dialog-warning"); m_iconLabel = new QLabel(m_addressHintLabel); m_iconLabel->setPixmap(icon.pixmap(ICON_SIZE)); m_textLabel = new QLabel(m_addressHintLabel); m_textLabel->setText(tr("Address conflict")); QHBoxLayout *conflictHintLayout = new QHBoxLayout(m_addressHintLabel); conflictHintLayout->setContentsMargins(0, 0, 0, 0); conflictHintLayout->addWidget(m_iconLabel); conflictHintLayout->addWidget(m_textLabel); conflictHintLayout->addStretch(); m_addressHintLabel->setLayout(conflictHintLayout); m_iconLabel->hide(); m_textLabel->hide(); } bool Ipv6Page::getIpv6EditState(QString text) { if (text.isEmpty()) { return true; } QRegularExpression rx("^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$"); // 进行匹配并返回结果 QRegularExpressionMatch match = rx.match(text); return match.hasMatch(); } int Ipv6Page::getPerfixLength(QString text) { qDebug() << "getPerfixLength" << text; int length = 0; QStringList list= text.split(":"); for (int i = 0; i < list.size(); ++i) { QString temp = list.at(i); if (temp.isEmpty()) { continue; } bool ok; unsigned int val = temp.toUInt(&ok, 16); temp = temp.setNum(val,2); for(int j = 0; j < temp.length(); ++j) { if (temp.at(j) == "1") { length++; } } } qDebug() << "getPerfixLength" << length; return length; } void Ipv6Page::initLoadingIcon() { m_loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); m_iconTimer = new QTimer(this); connect(m_iconTimer, &QTimer::timeout, this, &Ipv6Page::updateIcon); } void Ipv6Page::updateIcon() { if (m_currentIconIndex > 6) { m_currentIconIndex = 0; } m_statusLabel->setPixmap(m_loadIcons.at(m_currentIconIndex).pixmap(ICON_SIZE)); m_currentIconIndex ++; } void Ipv6Page::startLoading() { m_iconTimer->start(FRAME_SPEED); } void Ipv6Page::stopLoading() { m_iconTimer->stop(); m_statusLabel->clear(); } void Ipv6Page::showIpv6AddressConflict(bool isConflict) { if (isConflict) { m_iconLabel->show(); m_textLabel->show(); } else { m_iconLabel->hide(); m_textLabel->hide(); } } QString Ipv6Page::getErrorMessage() { checkConnectBtnIsEnabled(); return m_errorMessage; } void Ipv6Page::updateNetCtrl(QString modName,QVariantMap value) { if(modName!="IPV6" && modName!="DNS") return; qInfo()<currentIndex(); if (m_ipaddressCtrl || currentIndex==AUTO_CONFIG) { ipv6AddressEdit->setEnabled(false); } else { ipv6AddressEdit->setEnabled(true); } if (m_netMaskCtrl || currentIndex==AUTO_CONFIG) { lengthEdit->setEnabled(false); } else { lengthEdit->setEnabled(true); } if (m_gateWayCtrl || currentIndex==AUTO_CONFIG) { gateWayEdit->setEnabled(false); } else { gateWayEdit->setEnabled(true); } if(m_dnsWayCtrl) m_dnsWidget->setEnabled(false); else m_dnsWidget->setEnabled(true); } void Ipv6Page::initNetCtrl() { QVariantMap map; int errCode=0; QString netCtrlIPV6Name="IPV6"; QString netCtrlDNSName="DNS"; QDBusInterface dbusInterface("com.kylin.networkCtrol", "/com/kylin/networkCtrol", "com.kylin.networkCtrol", QDBusConnection::systemBus()); if (!dbusInterface.isValid()) { qWarning()<=2) { const QDBusArgument &dbusArg1st = result.arguments().at( 0 ).value(); dbusArg1st >> map; errCode = result.arguments().at( 1 ).toInt(); qInfo()<<"ipv6"<=2) { const QDBusArgument &dbusArg1st = result.arguments().at( 0 ).value(); dbusArg1st >> map; errCode = result.arguments().at( 1 ).toInt(); qInfo()<<"ipv6"< #include #include #include #include #include #include #include #include #include #include "coninfo.h" #include "multiplednswidget.h" #include "klabel.h" class CreatNetPage : public QFrame { Q_OBJECT public: CreatNetPage(QWidget *parent = nullptr); void constructIpv4Info(KyConnectSetting &setting); void startLoading(); void stopLoading(); void showIpv4AddressConflict(bool isConflict); QString getErrorMessage(); private: LineEdit *connNameEdit; QComboBox *ipv4ConfigCombox; LineEdit *ipv4addressEdit; LineEdit *netMaskEdit; LineEdit *gateWayEdit; QFormLayout *m_detailLayout; QVBoxLayout *mvBoxLayout; QLabel *m_connNameLabel; QLabel *m_configLabel; QLabel *m_addressLabel; QLabel *m_maskLabel; QLabel *m_gateWayLabel; KLabel *m_addressHintLabel; KLabel *m_maskHintLabel; MultipleDnsWidget *m_dnsWidget = nullptr; QLabel *m_statusLabel = nullptr; QList m_loadIcons; QTimer *m_iconTimer = nullptr; int m_currentIconIndex =0; QLabel *m_iconLabel; KLabel *m_textLabel; private: QString m_errorMessage; void initUI(); void initComponent(); void setLineEnabled(bool check); void configSave(); bool getTextEditState(QString text); bool checkConnectBtnIsEnabled(); void initConflictHintLable(); void initLoadingIcon(); bool netMaskIsValide(QString text); QString getNetMaskText(QString text); private Q_SLOTS: void setEnableOfSaveBtn(); void configChanged(int index); void onAddressTextChanged(); void onNetMaskTextChanged(); void onAddressEditFinished(); public Q_SLOTS: void updateIcon(); Q_SIGNALS: void setCreatePageState(bool); void ipv4EditFinished(QString); }; #endif // CREATNETPAGE_H kylin-nm/src/frontend/netdetails/detailwidget.h0000664000175000017500000000265615167646234020646 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef DetailWidget_H #define DetailWidget_H #include #include #include #include "kylable.h" class DetailWidget : public QWidget { Q_OBJECT public: explicit DetailWidget(QWidget *valueWidget = nullptr, QWidget *parent = nullptr, QWidget *buttonWidget = nullptr); ~DetailWidget(); void setKey(const QString &keyLabel); private: QHBoxLayout *m_mainLayout = nullptr; FixLabel *m_keyLabel = nullptr; QWidget *m_valueWidget = nullptr; QWidget *m_copyButton; void initUI(); }; #endif // DetailWidget_H kylin-nm/src/frontend/netdetails/multiplednswidget.cpp0000664000175000017500000002550615167651420022267 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "multiplednswidget.h" #include #include #include #include #include "ukuistylehelper/ukuistylehelper.h" #include "coninfo.h" #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" #define DNS_LISTWIDGET_EMPTY_HEIGHT 79 #define DNS_LISTWIDGET_HEIGHT 188 #define BUTTON_SIZE 36,36 #define ITEM_HEIGHT 36 #define STR_ATTEMPTS "attempts" #define STR_TIMEOUT "timeout" #define STR_TYPE "type" #define SYSTEM_DBUS_SERVICE "com.kylin.network.qt.systemdbus" #define SYSTEM_DBUS_PATH "/" #define SYSTEM_DBUS_INTERFACE "com.kylin.network.interface" MultipleDnsWidget::MultipleDnsWidget(const QRegularExpression &rx, bool settingShow, QWidget *parent) : m_regExp(rx), m_settingShow(settingShow), QWidget(parent) { initUI(); initComponent(); } void MultipleDnsWidget::initUI() { QVBoxLayout *mulDnsVLayout = new QVBoxLayout(this); mulDnsVLayout->setContentsMargins(0, 0, 0, 30); m_mulDnsLabel = new QLabel(this); m_mulDnsLabel->setText(tr("DNS server(Drag to sort)")); //DNS服务器: m_emptyWidget = new QFrame(this); m_emptyWidget->setFrameShape(QFrame::Shape::StyledPanel); m_emptyWidget->setFixedHeight(DNS_LISTWIDGET_EMPTY_HEIGHT); emptyLabel = new QLabel(m_emptyWidget); emptyLabel->setAlignment(Qt::AlignCenter); emptyLabel->setText(tr("Click \"+\" to configure DNS")); QVBoxLayout* emptyLayout = new QVBoxLayout(m_emptyWidget); emptyLayout->addWidget(emptyLabel,Qt::AlignCenter); m_dnsListWidget = new QListWidget(this); m_dnsListWidget->setFixedHeight(DNS_LISTWIDGET_EMPTY_HEIGHT); m_dnsListWidget->setBackgroundRole(QPalette::Base); m_dnsListWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus); m_dnsListWidget->setFrameShape(QFrame::Shape::StyledPanel); m_dnsListWidget->setEditTriggers(QAbstractItemView::DoubleClicked); m_dnsListWidget->setAlternatingRowColors(true); //item可拖拽 m_dnsListWidget->setSelectionMode(QAbstractItemView::SingleSelection); m_dnsListWidget->setDragEnabled(true); m_dnsListWidget->viewport()->setAcceptDrops(true); m_dnsListWidget->setDropIndicatorShown(true); m_dnsListWidget->setDragDropMode(QAbstractItemView::DragDropMode::InternalMove); setPlaceholderTextColor(); m_buttonBox = new KButtonBox(this); m_buttonBox->setExclusive(false); m_addDnsBtn = new KPushButton(this); m_addDnsBtn->setIcon(QIcon::fromTheme("list-add-symbolic")); m_addDnsBtn->setFixedSize(BUTTON_SIZE); m_addDnsBtn->setProperty("useButtonPalette", true); m_removeDnsBtn = new KPushButton(this); m_removeDnsBtn->setIcon(QIcon::fromTheme("list-remove-symbolic")); m_removeDnsBtn->setFixedSize(BUTTON_SIZE); m_removeDnsBtn->setProperty("useButtonPalette", true); m_removeDnsBtn->setEnabled(false); m_buttonBox->addButton(m_addDnsBtn); m_buttonBox->addButton(m_removeDnsBtn); m_settingsLabel = new KBorderlessButton(this); m_settingsLabel->setText(tr("Settings")); QHBoxLayout *btnHLayout = new QHBoxLayout(); btnHLayout->setContentsMargins(0, 0, 0, 0); btnHLayout->setSpacing(1); btnHLayout->setAlignment(Qt::AlignLeft); btnHLayout->addWidget(m_buttonBox); btnHLayout->addSpacing(23); btnHLayout->addWidget(m_settingsLabel); mulDnsVLayout->addWidget(m_mulDnsLabel, Qt::AlignLeft); mulDnsVLayout->addWidget(m_emptyWidget); mulDnsVLayout->addWidget(m_dnsListWidget); mulDnsVLayout->addLayout(btnHLayout); m_emptyWidget->show(); m_dnsListWidget->hide(); if (!m_settingShow) { m_settingsLabel->hide(); } } void MultipleDnsWidget::initComponent() { connect(qApp, &QApplication::paletteChanged, this, &MultipleDnsWidget::setPlaceholderTextColor); connect(m_addDnsBtn, &KPushButton::clicked, this, &MultipleDnsWidget::onAddBtnClicked); connect(m_removeDnsBtn, &KPushButton::clicked, this, &MultipleDnsWidget::onRemoveBtnClicked); connect(m_dnsListWidget, &QListWidget::itemClicked, this, [=]() { if (m_dnsListWidget->count() < 1) { m_removeDnsBtn->setEnabled(false); } else { m_removeDnsBtn->setEnabled(true); } }); connect(m_dnsListWidget, &QListWidget::itemDoubleClicked, this, [=](QListWidgetItem *item) { m_dnsListWidget->edit(m_dnsListWidget->currentIndex()); item->setFlags(item->flags() | Qt::ItemIsEditable); }); connect(m_settingsLabel, &KBorderlessButton::clicked, this, [&](){ showDnsSettingWidget(); }); } void MultipleDnsWidget::setEditEnabled(bool state) { m_addDnsBtn->setEnabled(state); if (!state) { m_dnsListWidget->clear(); } } QList MultipleDnsWidget::getDns() const { QStringList dnsList; dnsList.clear(); QList ipv4dnsList; ipv4dnsList.clear(); int row = 0; QString aDns; while (m_dnsListWidget->count() > row) { aDns = m_dnsListWidget->item(row)->text(); if (!dnsList.contains(aDns) && !aDns.isEmpty()) { dnsList << aDns; ipv4dnsList << QHostAddress(aDns); } row ++; } return ipv4dnsList; } void MultipleDnsWidget::setDnsListText(const QList &dns) { m_dnsListWidget->clear(); if (!dns.isEmpty()) { m_dnsListWidget->setFixedHeight(DNS_LISTWIDGET_HEIGHT); m_emptyWidget->hide(); m_dnsListWidget->show(); } for (int i = 0; i < dns.size(); ++i) { QString str = dns.at(i).toString(); QListWidgetItem *dnsListWidgetItem = new QListWidgetItem(m_dnsListWidget); dnsListWidgetItem->setSizeHint(QSize(0,ITEM_HEIGHT)); ListItemEdit *dnsListItemEdit = new ListItemEdit(m_regExp, m_dnsListWidget); m_dnsListWidget->setItemDelegateForRow(i, dnsListItemEdit); dnsListWidgetItem->setText(str); } } void MultipleDnsWidget::AddOneDnsItem(QListWidget *listWidget) { if (m_dnsListWidget->count() == 0) { m_emptyWidget->hide(); m_dnsListWidget->show(); m_dnsListWidget->setFixedHeight(DNS_LISTWIDGET_HEIGHT); Q_EMIT scrollToBottom(); } QListWidgetItem *dnsListWidgetItem = new QListWidgetItem(listWidget); dnsListWidgetItem->setSizeHint(QSize(0,ITEM_HEIGHT)); dnsListWidgetItem->setFlags(dnsListWidgetItem->flags() | Qt::ItemIsEditable); listWidget->addItem(dnsListWidgetItem); listWidget->setCurrentItem(dnsListWidgetItem); ListItemEdit *dnsListItemEdit = new ListItemEdit(m_regExp, listWidget); listWidget->setItemDelegateForRow(listWidget->currentIndex().row() , dnsListItemEdit); listWidget->editItem(dnsListWidgetItem); } void MultipleDnsWidget::RemoveOneDnsItem(QListWidgetItem *aItem, QListWidget *listWidget) { if (aItem) { listWidget->removeItemWidget(aItem); delete aItem; } if (m_dnsListWidget->count() == 0) { m_emptyWidget->show(); m_dnsListWidget->hide(); m_dnsListWidget->setFixedHeight(DNS_LISTWIDGET_EMPTY_HEIGHT); } } #if 0 void MultipleDnsWidget::setDnsListWidgetStyle() { QPalette pal = qApp->palette(); const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { QGSettings styleGsettings(style_id); QString currentTheme = styleGsettings.get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = lightPalette(this); } } this->setPalette(pal); m_dnsListWidget->setAlternatingRowColors(true); QColor color = pal.color(QPalette::PlaceholderText); pal.setColor(QPalette::WindowText, color); emptyLabel->setPalette(pal); } #endif void MultipleDnsWidget::onAddBtnClicked() { AddOneDnsItem(m_dnsListWidget); //避免重复添加空白项 int row = m_dnsListWidget->count() - 1; while (row >= 0) { if (!m_dnsListWidget->item(row)->isSelected() && m_dnsListWidget->item(row)->text().isEmpty()) { m_dnsListWidget->removeItemWidget(m_dnsListWidget->item(row)); delete m_dnsListWidget->item(row); } row --; } m_removeDnsBtn->setEnabled(true); } void MultipleDnsWidget::onRemoveBtnClicked() { QListWidgetItem *aItem = m_dnsListWidget->currentItem(); if (!aItem) { return; } RemoveOneDnsItem(aItem, m_dnsListWidget); if (m_dnsListWidget->count()< 1) { m_removeDnsBtn->setEnabled(false); } } void MultipleDnsWidget::setPlaceholderTextColor() { QPalette pal = qApp->palette(); QColor color = pal.color(QPalette::PlaceholderText); pal.setColor(QPalette::WindowText, color); emptyLabel->setPalette(pal); } void MultipleDnsWidget::showDnsSettingWidget() { QDBusInterface iface(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, QDBusConnection::systemBus()); if (!iface.isValid()) { return; } QDBusMessage result = iface.call("getExtraDnsEnhance", m_uuid); const QDBusArgument &dbusArg1st = result.arguments().at( 0 ).value(); QVariantMap map = result.arguments().at(0).toMap(); QString timeout, retry, tactic; dbusArg1st >> map; QString originTimeout,originRetry,originType; originTimeout = map.value(STR_TIMEOUT).toString(); originRetry = map.value(STR_ATTEMPTS).toString(); originType = map.value(STR_TYPE).toString(); timeout = !originTimeout.isEmpty() ? map.value(STR_TIMEOUT).toString() : "5"; retry = !originRetry.isEmpty() ? map.value(STR_ATTEMPTS).toString() : "2"; tactic = !originType.isEmpty() ? map.value(STR_TYPE).toString() : "order"; DnsSettingWidget* dialog = new DnsSettingWidget(timeout, retry, tactic, this); if (dialog->exec() == QDialog::Accepted) { QString timeout, retry, tactic; dialog->getDnsSettings(timeout, retry, tactic); if (iface.isValid()) { iface.call("setOptionsEnhance", m_uuid, timeout, retry, tactic); } if (timeout != originTimeout || retry != originRetry || tactic != originType) { m_dnsSettingChanged = true; } } delete dialog; dialog = nullptr; } kylin-nm/src/frontend/netdetails/customtabstyle.cpp0000664000175000017500000001016115167646234021603 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "customtabstyle.h" CustomTabStyle::CustomTabStyle() { } QSize CustomTabStyle::sizeFromContents(QStyle::ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const { QSize s = QProxyStyle::sizeFromContents(type, option, size, widget); if (type == QStyle::CT_TabBarTab) { s.transpose(); s.rwidth() = 60; // 设置每个tabBar中item的大小 s.rheight() = 36; } return s; } void CustomTabStyle::drawControl(QStyle::ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { if (element == CE_TabBarTab) { if (const QStyleOptionTab *tab = qstyleoption_cast(option)) { QRect allRect = tab->rect; if (tab->state & QStyle::State_Selected) { //选中状态:tab的Qlabel为矩形,底色为白色,边框淡灰色,文字为淡蓝色且加粗居中(具体颜色值由拾色器提取) painter->save(); painter->setPen(0x3790FA); //设置画笔颜色为淡灰色 painter->setBrush(QBrush(0x3790FA)); //设置画刷为白色 painter->drawRoundedRect(allRect.adjusted(0,0,0,0),6,6); //重绘tab的矩形边框 painter->restore(); //还原为默认 painter->save(); painter->setPen(0xffffff); //重新设置画笔颜色为淡蓝色 QTextOption option; option.setAlignment(Qt::AlignCenter); //设置文字居中 painter->drawText(allRect, tab->text, option); //重绘文字 painter->restore(); } else if(tab->state & QStyle::State_MouseOver) { //hover状态:tab的Qlabel为矩形,底色为灰色,边框仍未淡灰色,文字加粗居中 painter->save(); painter->setPen(tab->palette.color(QPalette::Window)); //设置画笔颜色为淡灰色 painter->setBrush(tab->palette.color(QPalette::Window)); //设置画刷为灰色 painter->drawRoundedRect(allRect.adjusted(0,0,0,0),6,6); //重绘tab的矩形边框 painter->restore(); //还原 painter->save(); QTextOption option; option.setAlignment(Qt::AlignCenter); //设置文字居中 painter->drawText(allRect, tab->text, option); //重绘文字 painter->restore(); } else //其它的:tab的Qlabel为矩形,底色为灰色,边框为淡灰色不变,文字不加粗但居中 { painter->save(); painter->setPen(tab->palette.color(QPalette::Button)); painter->setBrush(tab->palette.color(QPalette::Button)); painter->drawRoundedRect(allRect.adjusted(0,0,0,0),6,6); //重绘tab的矩形边框 painter->restore(); painter->save(); QTextOption option; option.setAlignment(Qt::AlignCenter); painter->drawText(allRect, tab->text, option); painter->restore(); } return; } } if (element == CE_TabBarTab) { QProxyStyle::drawControl(element, option, painter, widget); } } kylin-nm/src/frontend/netdetails/detailpage.h0000664000175000017500000000732115167651420020262 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef DETAILPAGE_H #define DETAILPAGE_H #include #include #include #include #include #include #include #include #include #include #include #include "detailwidget.h" #include "coninfo.h" #include "kwidget.h" #include "ktabbar.h" #include "kballontip.h" #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" using namespace kdk; class DetailPage : public QFrame { Q_OBJECT public: DetailPage(bool isWlan, bool isCreate = false, QWidget *parent = nullptr); ~DetailPage(); void setSSID(const QString &ssid); void setProtocol(const QString &protocol); void setSecType(const QString &secType); void setHz(const QString &hz); void setChan(const QString &chan); void setBandWidth(const QString &brandWidth); void setIpv4(const QString &ipv4); void setIpv4Dns(const QString &ipv4Dns); void setIpv6(const QString &ipv6); void setMac(const QString &mac); void setAutoConnect(bool flag); bool checkIsChanged(const ConInfo info); void getSsid(QString &ssid); private: void initUI(); void addDetailItem(QListWidget *listWidget, QWidget *detailWidget); void newCopiedTip(); void setInteractionFlag(); public: QListWidget *m_listWidget = nullptr; DetailWidget *m_ssidWidget = nullptr; DetailWidget *m_protocolWidget = nullptr; DetailWidget *m_secTypeWidget = nullptr; DetailWidget *m_hzWidget = nullptr; DetailWidget *m_chanelWidget = nullptr; DetailWidget *m_bandwidthWidget = nullptr; DetailWidget *m_ipv4Widget = nullptr; DetailWidget *m_ipv4DnsWidget = nullptr; DetailWidget *m_ipv6Widget = nullptr; DetailWidget *m_macWidget = nullptr; QPushButton *m_netCopyButton = nullptr; LineEdit *m_SSIDEdit = nullptr; QLabel *m_SSIDLabel = nullptr; QLabel *m_Protocol = nullptr; QLabel *m_SecType = nullptr; QLabel *m_Hz = nullptr; QLabel *m_Chan = nullptr; QLabel *m_BandWidth = nullptr; QLabel *m_IPV4 = nullptr; FixLabel *m_IPV4Dns = nullptr; FixLabel *m_IPV6 = nullptr; QLabel *m_Mac = nullptr; QLabel *m_autoConnect = nullptr; KBallonTip *m_copiedTip = nullptr; // QWidget *autoFrame; private: QVBoxLayout *m_layout = nullptr; QVBoxLayout *m_DetailLayout = nullptr; QHBoxLayout *m_AutoLayout = nullptr; QCheckBox *m_forgetNetBox = nullptr; bool m_IsWlan = false; bool m_IsCreate = false; QWidget *m_autoConWidget = nullptr; QString m_formerSSID = nullptr; QString m_formerIPV6 = nullptr; private Q_SLOTS: void setEnableOfSaveBtn(); void on_btnCopyNetDetail_clicked(); Q_SIGNALS: void setDetailPageState(bool); }; #endif // DETAILPAGE_H kylin-nm/src/frontend/netdetails/joinhiddenwifipage.h0000664000175000017500000000475215167651420022017 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef JOINHIDDENWIFIPAGE_H #define JOINHIDDENWIFIPAGE_H #include #include #include #include #include "coninfo.h" #include "kywirelessconnectoperation.h" #include "securitypage.h" #include "divider.h" #include "kwidget.h" #include "kdialog.h" #include "kborderlessbutton.h" using namespace kdk; class JoinHiddenWiFiPage : public KDialog { Q_OBJECT public: JoinHiddenWiFiPage(QString devName, KDialog *parent = nullptr); ~JoinHiddenWiFiPage(); protected: void closeEvent(QCloseEvent *event); private: void initUI(); void initComponent(); void setJoinBtnEnable(); private: KyWirelessConnectOperation *m_wirelessConnOpration = nullptr; QString m_devName; QWidget *m_topWidget; QWidget *m_centerWidget; QWidget *m_bottomWidget; SecurityPage *m_secuWidget; FixLabel *m_descriptionLabel; FixLabel *m_nameLabel; LineEdit *m_nameEdit; Divider *m_bottomDivider = nullptr; KBorderlessButton *m_showListBtn; QPushButton *m_cancelBtn; QPushButton *m_joinBtn; QScrollArea *m_hiddenWifiScrollArea; QVBoxLayout *m_pageLayout; QHBoxLayout *m_topLayout; QVBoxLayout *m_centerVBoxLayout; QHBoxLayout *m_bottomLayout; bool m_isJoinBtnEnable = false; bool m_isSecuOk = false; ConInfo m_info; private Q_SLOTS: void onBtnJoinClicked(); void onBtnShowListClicked(); void onSecuTypeChanged(const KySecuType &type); void onEapTypeChanged(const KyEapMethodType &type); Q_SIGNALS: void hiddenWiFiPageClose(QString); void showWlanList(int type); }; #endif // JOINHIDDENWIFIPAGE_H kylin-nm/src/frontend/netdetails/detailwidget.cpp0000664000175000017500000000414315167646234021172 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "detailwidget.h" #include #define ITEM_HEIGHT 36 #define ITEM_MARGINS 18,0,16,0 #define MIN_LABEL_WIDTH 146 #define MAX_LABEL_WIDTH 154 #define MAX_WIDGET_WIDTH 270 DetailWidget::DetailWidget(QWidget *valueWidget, QWidget *parent, QWidget *buttonWidget) : m_valueWidget(valueWidget) , QWidget(parent) , m_copyButton(buttonWidget) { // m_valueWidget = valueWidget; initUI(); } DetailWidget::~DetailWidget() { } void DetailWidget::initUI() { this->setFixedHeight(ITEM_HEIGHT); m_mainLayout = new QHBoxLayout(this); m_mainLayout->setContentsMargins(ITEM_MARGINS); m_keyLabel = new FixLabel(this); m_keyLabel->setMinimumWidth(MIN_LABEL_WIDTH); m_keyLabel->setMaximumWidth(MAX_LABEL_WIDTH); m_keyLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); m_mainLayout->addWidget(m_keyLabel); m_mainLayout->addStretch(); if (m_copyButton != nullptr) { m_copyButton->setMaximumWidth(ITEM_HEIGHT-8); m_copyButton->setMaximumHeight(ITEM_HEIGHT-8); m_mainLayout->addWidget(m_copyButton); } m_mainLayout->addWidget(m_valueWidget); m_valueWidget->setMaximumWidth(MAX_WIDGET_WIDTH); } void DetailWidget::setKey(const QString &keyLabel) { m_keyLabel->setLabelText(keyLabel); } kylin-nm/src/frontend/netdetails/netdetail.cpp0000664000175000017500000013744615167651420020503 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "netdetail.h" //#include "xatom/xatom-helper.h" #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" #include #include #include #include #include #include "windowmanager/windowmanager.h" #include #include "kwindowsystem_export.h" #define WINDOW_WIDTH 520 #define WINDOW_HEIGHT 602 #define ICON_SIZE 22,22 #define TITLE_LAYOUT_MARGINS 9,9,0,0 #define CENTER_LAYOUT_MARGINS 24,0,0,0 #define BOTTOM_LAYOUT_MARGINS 24,0,24,0 #define BOTTOM_LAYOUT_SPACING 16 #define DETAIL_PAGE_NUM 0 #define IPV4_PAGE_NUM 1 #define IPV6_PAGE_NUM 2 #define SECURITY_PAGE_NUM 3 #define CONFIG_PAGE_NUM 4 #define CREATE_NET_PAGE_NUM 5 #define PAGE_MIN_HEIGHT 40 #define PAGE_WIDTH 472 #define PPPOE_TAB_WIDTH 120 #define LAN_TAB_WIDTH 180 #define WLAN_TAB_WIDTH 240 #define SCRO_WIDTH 496 #define SCRO_HEIGHT 600 #define PEAP_SCRO_HEIGHT 300 #define TLS_SCRO_HEIGHT 480 #define MAX_TAB_TEXT_LENGTH 44 #define SYSTEM_DBUS_SERVICE "com.kylin.network.qt.systemdbus" #define SYSTEM_DBUS_PATH "/" //systemdbus的路径是"/" #define SYSTEM_DBUS_INTERFACE "com.kylin.network.interface" WarningDialog::WarningDialog(QWidget *parent) :KDialog(parent) { this->setFixedSize(480, 204); this->closeButton(); initUI(); } void WarningDialog::initUI() { warningLabel = new QLabel(this); warningTitle = new QLabel(this); warningText = new QLabel(this); confirmButton = new QPushButton(this); warningLabel->setContentsMargins(0,0,0,0); warningLabel->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(16,16)); warningTitle->setText(tr("Unable to save modifications")); warningText->setEnabled(false); warningText->setWordWrap(true); confirmButton->setText(tr("Confirm")); QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(26,13,24,24); QFormLayout* fLayout = new QFormLayout(this); fLayout->setVerticalSpacing(0); fLayout->setContentsMargins(0, 0, 0, 0); fLayout->addRow(warningLabel,warningTitle); fLayout->addRow("", warningText); QHBoxLayout *hLayout = new QHBoxLayout(this); hLayout->setContentsMargins(0, 0, 0, 0); hLayout->addStretch(); hLayout->addWidget(confirmButton); mainLayout->addLayout(fLayout); mainLayout->addStretch(); mainLayout->addLayout(hLayout); this->mainWidget()->setLayout(mainLayout); connect(confirmButton, &QPushButton::clicked, [=](){ this->close(); }); } void WarningDialog::setWarningMessage(QString message) { warningText->setText(message); } void NetDetail::showDesktopNotify(const QString &message, QString soundName) { QDBusInterface iface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus()); QStringList actions; //跳转动作 actions.append("default"); actions.append("kylin-nm"); //默认动作:点击消息体时打开麒麟录音 QMap hints; if (!soundName.isEmpty()) { hints.insert("sound-name", soundName); //添加声音 } QList args; args<<(tr("Kylin NM")) <<((unsigned int) 0) <setEnabled(on); ipv4Page->setEnabled(on); ipv6Page->setEnabled(on); securityPage->setEnabled(on); createNetPage->setEnabled(on); cancelBtn->setEnabled(on); forgetBtn->setEnabled(on); confimBtn->setEnabled(on); } void NetDetail::startObjectThread() { m_objectThread = new QThread(); m_object = new ThreadObject(m_deviceName); m_object->moveToThread(m_objectThread); connect(m_objectThread, &QThread::finished, m_objectThread, &QObject::deleteLater); connect(m_objectThread, &QThread::finished, m_object, &QObject::deleteLater); if (m_isCreateNet && !isWlan) { connect(createNetPage, &CreatNetPage::ipv4EditFinished, this, [=](){ createNetPage->startLoading(); }); connect(createNetPage, SIGNAL(ipv4EditFinished(const QString &)), m_object, SLOT(checkIpv4ConflictThread(const QString &))); connect(m_object, &ThreadObject::ipv4IsConflict, this, [=](bool ipv4IsConf) { createNetPage->stopLoading(); createNetPage->showIpv4AddressConflict(ipv4IsConf); }); } else { connect(ipv4Page, &Ipv4Page::ipv4EditFinished, this, [=](){ ipv4Page->startLoading(); }); connect(ipv6Page, &Ipv6Page::ipv6EditFinished, this, [=](){ ipv6Page->startLoading(); }); connect(ipv4Page, SIGNAL(ipv4EditFinished(const QString &)), m_object, SLOT(checkIpv4ConflictThread(const QString &))); connect(ipv6Page, SIGNAL(ipv6EditFinished(const QString &)), m_object, SLOT(checkIpv6ConflictThread(const QString &))); connect(this, SIGNAL(checkCurrentIpv4Conflict(const QString &)), m_object, SLOT(checkIpv4ConflictThread(const QString &))); connect(this, SIGNAL(checkCurrentIpv6Conflict(const QString &)), m_object, SLOT(checkIpv6ConflictThread(const QString &))); connect(m_object, &ThreadObject::ipv4IsConflict, this, [=](bool ipv4IsConf) { ipv4Page->stopLoading(); ipv4Page->showIpv4AddressConflict(ipv4IsConf); }); connect(m_object, &ThreadObject::ipv6IsConflict, this, [=](bool ipv6IsConf) { ipv6Page->stopLoading(); ipv6Page->showIpv6AddressConflict(ipv6IsConf); }); } m_objectThread->start(); } NetDetail::NetDetail(QString interface, QString name, QString uuid, bool isActive, bool isWlan, bool isCreateNet,int category, QWidget *parent) :m_deviceName(interface), m_name(name), m_uuid(uuid), isActive(isActive), isWlan(isWlan), m_isCreateNet(isCreateNet), mCategory(category), KDialog(parent) { KX11Extras::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager); setFixedSize(WINDOW_WIDTH,WINDOW_HEIGHT); centerToScreen(); setWindowIcon("kylin-network"); if (!m_isCreateNet && name.isEmpty()) { m_isCreateNet = true; } KyConnectResourse resource; m_isPppoe = resource.isPppoeConnection(m_uuid); m_netDeviceResource = new KyNetworkDeviceResourse(this); m_wirelessConnOpration = new KyWirelessConnectOperation(this); m_resource = new KyWirelessNetResource(this); m_connectOperation = new KyConnectOperation(this); m_wiredConnOperation = new KyWiredConnectOperation(this); initUI(); loadPage(); initComponent(); getConInfo(m_info); startObjectThread(); pagePadding(name,isWlan); connect(qApp, &QApplication::paletteChanged, this, &NetDetail::onPaletteChanged); isCreateOk = !(m_isCreateNet && !isWlan); isDetailOk = !(m_name.isEmpty()); isIpv4Ok = true; isIpv6Ok = true; isSecuOk = false; if (!m_uuid.isEmpty() || (m_uuid.isEmpty() && m_info.secType == KYLIN_NM::NONE)) { isSecuOk = true; } qDebug() << interface << name << uuid << isActive << "isWlan" << isWlan << "isCreateNet" <isRunning()) { m_objectThread->quit(); m_objectThread->wait(); } } void NetDetail::onPaletteChanged() { QPalette pal = qApp->palette(); pal.setColor(QPalette::WindowText, pal.base().color()); this->setPalette(pal); #if 0 QGSettings * styleGsettings = nullptr; const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { styleGsettings = new QGSettings(style_id); QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = lightPalette(this); } } pal.setColor(QPalette::WindowText, pal.base().color()); this->setPalette(pal); setFramePalette(detailPage, pal); setFramePalette(ipv4Page, pal); setFramePalette(ipv6Page, pal); setFramePalette(securityPage, pal); setFramePalette(createNetPage, pal); QToolTip::setPalette(pal); #endif QPalette listwidget_pal(detailPage->m_listWidget->palette()); listwidget_pal.setColor(QPalette::Base, pal.base().color()); listwidget_pal.setColor(QPalette::AlternateBase, pal.alternateBase().color()); detailPage->m_listWidget->setAlternatingRowColors(true); detailPage->m_listWidget->setPalette(listwidget_pal); #if 0 if (styleGsettings != nullptr) { delete styleGsettings; styleGsettings = nullptr; } #endif } void NetDetail::currentRowChangeSlot(int row) { if (isActive) { if (row < 3) { stackWidget->setCurrentIndex(row); } else { if(isWlan) { stackWidget->setCurrentIndex(row); } else { stackWidget->setCurrentIndex(CONFIG_PAGE_NUM); } } } else { stackWidget->setCurrentIndex(row); } } void NetDetail::closeEvent(QCloseEvent *event) { Q_EMIT this->detailPageClose(m_deviceName, m_name, m_uuid); Q_EMIT this->createPageClose(m_deviceName); return KDialog::closeEvent(event); } void NetDetail::centerToScreen() { QRect desk_rect; QScreen *currentScreen = QGuiApplication::screenAt(QCursor::pos()); if (currentScreen) { desk_rect = currentScreen->geometry(); } else { desk_rect=QGuiApplication::primaryScreen()->geometry(); } int desk_x = desk_rect.width(); int desk_y = desk_rect.height(); int x = this->width(); int y = this->height(); this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); } void NetDetail::initUI() { QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(0,9,0,24); mainLayout->setSpacing(0); this->installEventFilter(this); pageFrame = new QFrame(this); centerWidget = new QWidget(this); bottomWidget = new QWidget(this); detailPage = new DetailPage(isWlan, m_name.isEmpty(), this); ipv4Page = new Ipv4Page(this); ipv6Page = new Ipv6Page(this); securityPage = new SecurityPage(this); createNetPage = new CreatNetPage(this); configPage = new ConfigPage(this); detailPage->setFixedWidth(PAGE_WIDTH); ipv4Page->setFixedWidth(PAGE_WIDTH); ipv6Page->setFixedWidth(PAGE_WIDTH); securityPage->setFixedWidth(PAGE_WIDTH); createNetPage->setFixedWidth(PAGE_WIDTH); configPage->setFixedWidth(PAGE_WIDTH); // 滚动区域 m_secuPageScrollArea = new QScrollArea(centerWidget); m_secuPageScrollArea->setFixedWidth(SCRO_WIDTH); m_secuPageScrollArea->setFrameShape(QFrame::NoFrame); m_secuPageScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_secuPageScrollArea->setWidget(securityPage); m_secuPageScrollArea->setWidgetResizable(true); m_ipv4ScrollArea = new QScrollArea(centerWidget); m_ipv4ScrollArea->setFixedWidth(SCRO_WIDTH); m_ipv4ScrollArea->setFrameShape(QFrame::NoFrame); m_ipv4ScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_ipv4ScrollArea->setWidget(ipv4Page); m_ipv4ScrollArea->setWidgetResizable(true); connect(ipv4Page, &Ipv4Page::scrollToBottom, this, [&](){ QTimer::singleShot(50,this,[=]() { m_ipv4ScrollArea->verticalScrollBar()->setValue(m_ipv4ScrollArea->verticalScrollBar()->maximum()); }); }); m_ipv6ScrollArea = new QScrollArea(centerWidget); m_ipv6ScrollArea->setFixedWidth(SCRO_WIDTH); m_ipv6ScrollArea->setFrameShape(QFrame::NoFrame); m_ipv6ScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_ipv6ScrollArea->setWidget(ipv6Page); m_ipv6ScrollArea->setWidgetResizable(true); connect(ipv6Page, &Ipv6Page::scrollToBottom, this, [&](){ QTimer::singleShot(50,this,[=]() { m_ipv6ScrollArea->verticalScrollBar()->setValue(m_ipv6ScrollArea->verticalScrollBar()->maximum()); }); }); m_configScrollArea = new QScrollArea(centerWidget); m_configScrollArea->setFixedWidth(SCRO_WIDTH); m_configScrollArea->setFrameShape(QFrame::NoFrame); m_configScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_configScrollArea->setWidget(configPage); m_configScrollArea->setWidgetResizable(true); m_createNetPageScrollArea = new QScrollArea(centerWidget); m_createNetPageScrollArea->setFixedWidth(SCRO_WIDTH); m_createNetPageScrollArea->setFrameShape(QFrame::NoFrame); m_createNetPageScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_createNetPageScrollArea->setWidget(createNetPage); m_createNetPageScrollArea->setWidgetResizable(true); stackWidget = new QStackedWidget(centerWidget); stackWidget->addWidget(detailPage); stackWidget->addWidget(m_ipv4ScrollArea); stackWidget->addWidget(m_ipv6ScrollArea); stackWidget->addWidget(m_secuPageScrollArea); stackWidget->addWidget(m_configScrollArea); stackWidget->addWidget(m_createNetPageScrollArea); // TabBar onPaletteChanged(); m_networkMode = NetworkModeType(NetworkModeConfig::getInstance()->getNetworkModeConfig(m_uuid)); m_netTabBar = new NetTabBar(this); m_netTabBar->addTab(tr("Detail")); //详情 m_netTabBar->addTab(tr("IPv4"));//Ipv4 KyConnectResourse resource; if (!m_isPppoe) { m_netTabBar->addTab(tr("IPv6"));//Ipv6 if (isWlan) { m_netTabBar->addTab(tr("Security"));//安全 m_netTabBar->setFixedWidth(WLAN_TAB_WIDTH); } else { m_netTabBar->setFixedWidth(LAN_TAB_WIDTH); } } else { m_netTabBar->setFixedWidth(PPPOE_TAB_WIDTH); } if (isActive && m_networkMode != DBUS_INVAILD && m_networkMode != NO_CONFIG) { m_netTabBar->addTab(tr("Config")); //配置 m_netTabBar->setFixedWidth(m_netTabBar->width() + TAB_WIDTH); } // TabBar关联选项卡页面 connect(m_netTabBar, SIGNAL(currentChanged(int)), this, SLOT(currentRowChangeSlot(int))); setNetTabToolTip(); confimBtn = new QPushButton(this); confimBtn->setText(tr("Confirm")); cancelBtn = new QPushButton(this); cancelBtn->setText(tr("Cancel")); forgetBtn = new QPushButton(this); confimBtn->setProperty("useButtonPalette", false); confimBtn->setProperty("isImportant", true); cancelBtn->setProperty("useButtonPalette", true); cancelBtn->setProperty("isImportant", false); forgetBtn->setProperty("useButtonPalette", true); forgetBtn->setProperty("isImportant", false); QHBoxLayout *pageLayout = new QHBoxLayout(pageFrame); pageLayout->setContentsMargins(0, 0, 0, 0); pageLayout->addWidget(m_netTabBar, Qt::AlignCenter); QVBoxLayout *centerlayout = new QVBoxLayout(centerWidget); centerlayout->setContentsMargins(CENTER_LAYOUT_MARGINS); // 右边距为0,为安全页滚动区域留出空间 centerlayout->addWidget(stackWidget); Divider *divider = new Divider(false, this); QHBoxLayout *bottomLayout = new QHBoxLayout(bottomWidget); bottomLayout->setContentsMargins(BOTTOM_LAYOUT_MARGINS); bottomLayout->setSpacing(BOTTOM_LAYOUT_SPACING); bottomLayout->addWidget(forgetBtn); bottomLayout->addStretch(); bottomLayout->addWidget(cancelBtn); bottomLayout->addWidget(confimBtn); bottomWidget->setMinimumHeight(PAGE_MIN_HEIGHT); mainLayout->addWidget(pageFrame); mainLayout->addSpacing(24); mainLayout->addWidget(centerWidget); mainLayout->addWidget(divider); mainLayout->addSpacing(16); mainLayout->addWidget(bottomWidget); mainWidget()->setLayout(mainLayout); this->setAutoFillBackground(true); } void NetDetail::loadPage() { //判断是否创建网络页面 if (m_isCreateNet && !isWlan) { pageFrame->hide(); stackWidget->setCurrentIndex(CREATE_NET_PAGE_NUM); this->setWindowTitle(tr("Add LAN Connect")); } else { stackWidget->setCurrentIndex(DETAIL_PAGE_NUM); this->setWindowTitle(m_name); if (isWlan && m_name.isEmpty()) { this->setWindowTitle(tr("Connect Hidden WLAN")); } } } void NetDetail::initComponent() { connect(cancelBtn, &QPushButton::clicked, this, [=] { close(); }); connect(confimBtn, SIGNAL(clicked()), this, SLOT(on_btnConfirm_clicked())); if (!m_uuid.isEmpty()) { if (isWlan) { forgetBtn->setText(tr("Forget this network")); } else { forgetBtn->setText(tr("Delete this network")); } forgetBtn->show(); connect(forgetBtn, SIGNAL(clicked()), this, SLOT(on_btnForget_clicked())); } else { forgetBtn->hide(); } connect(createNetPage, &CreatNetPage::setCreatePageState, this, [=](bool status) { isCreateOk = status; }); connect(detailPage, &DetailPage::setDetailPageState, this, [=](bool status) { isDetailOk = status; }); connect(ipv4Page, &Ipv4Page::setIpv4PageState, this, [=](bool status) { isIpv4Ok = status; }); connect(ipv6Page, &Ipv6Page::setIpv6PageState, this, [=](bool status) { isIpv6Ok = status; }); connect(securityPage, &SecurityPage::setSecuPageState, this, [=](bool status) { isSecuOk = status; }); const QByteArray id(THEME_SCHAME); if(QGSettings::isSchemaInstalled(id)){ QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); connect(fontSetting, &QGSettings::changed,[=](QString key) { if ("systemFont" == key || "systemFontSize" ==key) { setNetTabToolTip(); } else if ("themeColor" == key) { onPaletteChanged(); } }); } } void NetDetail::pagePadding(QString netName, bool isWlan) { //网络详情页填充 if(m_isCreateNet && !isWlan) { return; } detailPage->setSSID(netName); detailPage->setProtocol(m_info.strConType); detailPage->setSecType(m_info.strSecType); detailPage->setHz(m_info.strHz); detailPage->setChan(m_info.strChan); detailPage->setIpv4(m_info.strDynamicIpv4); detailPage->setIpv4Dns(m_info.strDynamicIpv4Dns); detailPage->setIpv6(m_info.strDynamicIpv6); detailPage->setMac(m_info.strMac); detailPage->setBandWidth(m_info.strBandWidth); detailPage->setAutoConnect(m_info.isAutoConnect); //ipv4页面填充 ipv4Page->setUuid(m_uuid); if (m_info.ipv4ConfigType == CONFIG_IP_MANUAL) { Q_EMIT checkCurrentIpv4Conflict(m_info.strIPV4Address); ipv4Page->setIpv4Config(m_info.ipv4ConfigType); ipv4Page->setIpv4(m_info.strIPV4Address); ipv4Page->setNetMask(m_info.strIPV4NetMask); // ipv4Page->setIpv4FirDns(m_info.strIPV4FirDns); // ipv4Page->setIpv4SecDns(m_info.strIPV4SecDns); ipv4Page->setGateWay(m_info.strIPV4GateWay); ipv4Page->setMulDns(m_info.ipv4DnsList);//只有在手动时才显示连接配置的dns信息。不然会造成自动时详情页面显示的dhcp的dns 这里显示手动配置的dns造成显示差异 } else { ipv4Page->setIpv4Config(m_info.ipv4ConfigType); } //ipv6页面填充 if (m_info.ipv6ConfigType == CONFIG_IP_MANUAL) { Q_EMIT checkCurrentIpv6Conflict(m_info.strIPV6Address); ipv6Page->setIpv6Config(m_info.ipv6ConfigType); ipv6Page->setIpv6(m_info.strIPV6Address); ipv6Page->setIpv6Perfix(m_info.iIPV6Prefix); // ipv6Page->setIpv6FirDns(m_info.strIPV6FirDns); // ipv6Page->setIpv6SecDns(m_info.strIPV6SecDns); ipv6Page->setGateWay(m_info.strIPV6GateWay); ipv6Page->setMulDns(m_info.ipv6DnsList); } else { ipv6Page->setIpv6Config(m_info.ipv6ConfigType); } //安全页面 if (isWlan) { securityPage->setSecurity(m_info.secType); qDebug() << "setSecurity" << m_info.secType; if (m_info.secType == WPA_AND_WPA2_ENTERPRISE) { if (m_info.enterpriseType == TLS) { securityPage->setTlsInfo(m_info.tlsInfo); } else if (m_info.enterpriseType == PEAP) { securityPage->setPeapInfo(m_info.peapInfo); } else if (m_info.enterpriseType == TTLS) { securityPage->setTtlsInfo(m_info.ttlsInfo); } else if (m_info.enterpriseType == LEAP) { securityPage->setLeapInfo(m_info.leapInfo); } else if (m_info.enterpriseType == PWD) { securityPage->setPwdInfo(m_info.pwdInfo); } else if (m_info.enterpriseType == FAST) { securityPage->setFastInfo(m_info.fastInfo); } else { qWarning() << "[NetDetail] unknown enterprise connection type" << m_info.enterpriseType; } } } //配置页面 if (isActive && m_networkMode != DBUS_INVAILD && m_networkMode != NO_CONFIG) { configPage->setConfigState(m_networkMode); } } //获取网路详情信息 void NetDetail::getConInfo(ConInfo &conInfo) { if (m_isCreateNet && !isWlan) { return; } getBaseInfo(conInfo); getStaticIpInfo(conInfo,isActive); getDynamicIpInfo(conInfo, isActive); } //详情ssid 带宽 物理地址 无线额外(安全性 频带 通道) void NetDetail::getBaseInfo(ConInfo &conInfo) { //有线无线公有 conInfo.strConName = m_name; QString hardAddress; int bandWith; m_netDeviceResource->getHardwareInfo(m_deviceName, hardAddress, bandWith); if (!hardAddress.isEmpty()) { conInfo.strBandWidth = QString("%1").arg(bandWith/1000) + "Mbps"; conInfo.strMac = hardAddress; } if (!isWlan) { conInfo.strConType = "802-3-ethernet"; if (m_isPppoe) { conInfo.strConType = "pppoe"; } } else { switch(mCategory) { case 1: case 2: conInfo.strConType = "802-11ax-wireless"; break; case 3: conInfo.strConType = "802-11be-wireless"; break; default : conInfo.strConType = "802-11-wireless"; break; } if (!isActive) { KyWirelessNetItem item; if (!m_resource->getWifiNetwork(m_deviceName, m_name, item)) { qDebug() << "getWifiNetWork failed device:" << m_deviceName << " name:" << m_name; return; } else { conInfo.strHz = QString::number(item.m_frequency); conInfo.strChan = QString::number(item.m_channel); //无线特有 conInfo.strSecType = item.m_secuType; if (conInfo.strSecType.isEmpty()) { conInfo.strSecType = tr("None"); } if (!item.m_isConfigured) { conInfo.secType = item.m_kySecuType; } } } else { uint iHz,iChan; QString strMac; m_netDeviceResource->getDeviceActiveAPInfo(m_deviceName, strMac, iHz, iChan, conInfo.strSecType); if (conInfo.strSecType.isEmpty()) { conInfo.strSecType = tr("None"); } conInfo.strHz = QString::number(iHz); conInfo.strChan = QString::number(iChan); } KyKeyMgmt type = m_wirelessConnOpration->getConnectKeyMgmt(m_uuid); if (!m_uuid.isEmpty()) { KyKeyMgmt type = m_wirelessConnOpration->getConnectKeyMgmt(m_uuid); if (type == WpaNone || type == Unknown) { conInfo.secType = KYLIN_NM::NONE; } else if (type == WpaPsk) { conInfo.secType = KYLIN_NM::WPA_AND_WPA2_PERSONAL; } else if (type == SAE) { conInfo.secType = KYLIN_NM::WPA3_PERSONAL; } else if (type == WpaEap) { conInfo.secType = KYLIN_NM::WPA_AND_WPA2_ENTERPRISE; } else { qDebug() << "KeyMgmt not support now " << type; } } initSecuData(); } } //详情ipv4 ipv6 ipv4Dns void NetDetail::getDynamicIpInfo(ConInfo &conInfo, bool bActived) { if (!bActived) { return; } //已激活的网络 详情页显示动态ipv4 ipv6 dns QString ipv4,ipv6; QList ipv4Dns,ipv6Dns; KyActiveConnectResourse *activeResourse = new KyActiveConnectResourse(this); activeResourse->getActiveConnectIpInfo(m_uuid,ipv4,ipv6); activeResourse->getActiveConnectDnsInfo(m_uuid,ipv4Dns,ipv6Dns); //Ipv6 if (!ipv6.isEmpty()) { conInfo.strDynamicIpv6 = ipv6; } //IPv4 if (!ipv4.isEmpty()) { //静态ip不为空的情况下,且在返回的连接中 if (!conInfo.strIPV4Address.isEmpty() && ipv4.contains(conInfo.strIPV4Address)) { conInfo.strDynamicIpv4 = conInfo.strIPV4Address; } else { QStringList ipv4List = ipv4.split(";"); if (!ipv4List.isEmpty()) { conInfo.strDynamicIpv4 = ipv4List.at(0).trimmed(); } } } if (!ipv4Dns.isEmpty()) { //conInfo.strDynamicIpv4Dns = ipv4Dns.at(0).toString(); QString dnsList; dnsList.clear(); for (QHostAddress str: ipv4Dns) { dnsList.append(str.toString()); dnsList.append("; "); } dnsList.chop(2); conInfo.strDynamicIpv4Dns = dnsList; } } //ipv4+ipv6页面 void NetDetail::getStaticIpInfo(ConInfo &conInfo, bool bActived) { KyConnectResourse *kyConnectResourse = new KyConnectResourse(this); KyConnectSetting connetSetting; kyConnectResourse->getConnectionSetting(m_uuid,connetSetting); connetSetting.dumpInfo(); conInfo.ipv4ConfigType = connetSetting.m_ipv4ConfigIpType; conInfo.ipv6ConfigType = connetSetting.m_ipv6ConfigIpType; conInfo.isAutoConnect = connetSetting.m_isAutoConnect; conInfo.ipv4DnsList = connetSetting.m_ipv4Dns; conInfo.ipv6DnsList = connetSetting.m_ipv6Dns; if (connetSetting.m_ipv4ConfigIpType == CONFIG_IP_MANUAL) { if (connetSetting.m_ipv4Address.size() > 0) { conInfo.strIPV4Address = connetSetting.m_ipv4Address.at(0).ip().toString(); conInfo.strIPV4NetMask = connetSetting.m_ipv4Address.at(0).netmask().toString(); conInfo.strIPV4GateWay = connetSetting.m_ipv4Address.at(0).gateway().toString(); } #if 0 if (connetSetting.m_ipv4Dns.size() == 1) { conInfo.strIPV4FirDns = connetSetting.m_ipv4Dns.at(0).toString(); } else if (connetSetting.m_ipv4Dns.size() > 1) { conInfo.strIPV4FirDns = connetSetting.m_ipv4Dns.at(0).toString(); conInfo.strIPV4SecDns = connetSetting.m_ipv4Dns.at(1).toString(); } #endif } if (connetSetting.m_ipv6ConfigIpType == CONFIG_IP_MANUAL) { if (connetSetting.m_ipv6Address.size() > 0) { conInfo.strIPV6Address = connetSetting.m_ipv6Address.at(0).ip().toString(); conInfo.iIPV6Prefix = ipv6Page->getPerfixLength(connetSetting.m_ipv6Address.at(0).netmask().toString()); conInfo.strIPV6GateWay = connetSetting.m_ipv6Address.at(0).gateway().toString(); } #if 0 if (connetSetting.m_ipv6Dns.size() == 1) { conInfo.strIPV6FirDns = connetSetting.m_ipv6Dns.at(0).toString(); } else if (connetSetting.m_ipv6Dns.size() > 1) { conInfo.strIPV6FirDns = connetSetting.m_ipv6Dns.at(0).toString(); conInfo.strIPV6SecDns = connetSetting.m_ipv6Dns.at(1).toString(); } #endif } if (!bActived) { conInfo.strDynamicIpv4 = conInfo.strIPV4Address.isEmpty() ? tr("Auto") : conInfo.strIPV4Address; conInfo.strDynamicIpv6 = conInfo.strIPV6Address.isEmpty() ? tr("Auto") : conInfo.strIPV6Address; conInfo.strDynamicIpv4Dns = conInfo.strIPV4FirDns.isEmpty() ? tr("Auto") : conInfo.strIPV4FirDns; } } void NetDetail::initSecuData() { QString password(""); int type = m_info.secType; switch (type) { case KYLIN_NM::NONE: break; case KYLIN_NM::WPA_AND_WPA2_PERSONAL: case KYLIN_NM::WPA3_PERSONAL: case KYLIN_NM::WPA_AND_WPA3: if (!m_uuid.isEmpty()) { NetworkManager::Setting::SecretFlags flag; if (m_wirelessConnOpration->getConnSecretFlags(m_uuid, flag)) { if (!flag) { password = m_wirelessConnOpration->getPsk(m_uuid); } } } m_info.strPassword = password; securityPage->setPsk(password); break; case KYLIN_NM::WPA_AND_WPA2_ENTERPRISE: if (!m_wirelessConnOpration->getEnterpiseEapMethod(m_uuid, m_info.enterpriseType)) { qDebug() << m_name << "not enterprise wifi"; } else if (m_info.enterpriseType == TLS) { initTlsInfo(m_info); } else if (m_info.enterpriseType == PEAP) { initPeapInfo(m_info); } else if (m_info.enterpriseType == TTLS) { initTtlsInfo(m_info); } else if (m_info.enterpriseType == LEAP) { initLeapInfo(m_info); } else if (m_info.enterpriseType == PWD) { initPwdInfo(m_info); } else if (m_info.enterpriseType == FAST) { initFastInfo(m_info); } else { qWarning() << "[NetDetail] unknown enterprise connection type" << m_info.enterpriseType; } break; default: break; } } void NetDetail::initTlsInfo(ConInfo &conInfo) { m_resource->getEnterPriseInfoTls(m_uuid, conInfo.tlsInfo); } void NetDetail::initPeapInfo(ConInfo &conInfo) { m_resource->getEnterPriseInfoPeap(m_uuid, conInfo.peapInfo); } void NetDetail::initTtlsInfo(ConInfo &conInfo) { m_resource->getEnterPriseInfoTtls(m_uuid, conInfo.ttlsInfo); } void NetDetail::initLeapInfo(ConInfo &conInfo) { m_resource->getEnterPriseInfoLeap(m_uuid, conInfo.leapInfo); } void NetDetail::initPwdInfo(ConInfo &conInfo) { m_resource->getEnterPriseInfoPwd(m_uuid, conInfo.pwdInfo); } void NetDetail::initFastInfo(ConInfo &conInfo) { m_resource->getEnterPriseInfoFast(m_uuid, conInfo.fastInfo); } //点击了保存更改网络设置的按钮 void NetDetail::on_btnConfirm_clicked() { qDebug() << "on_btnConfirm_clicked"; setNetdetailSomeEnable(false); QString meesage; if (!checkErrorMessage(meesage)) { WarningDialog dialog; dialog.setWarningMessage(meesage); dialog.exec(); setNetdetailSomeEnable(true); return; } if (m_isCreateNet) { if (!isWlan) { //新建有线连接 qDebug() << "Confirm create wired connect"; if (!createWiredConnect()) { setNetdetailSomeEnable(true); return; } } else { //新建无线连接 qDebug() << "Confirm create wireless connect"; if (!createWirelessConnect()) { setNetdetailSomeEnable(true); return; } } } else { //更新连接 qDebug() << "Confirm update connect"; if (!updateConnect()) { setNetdetailSomeEnable(true); return; } } close(); } //点击忘记网络 void NetDetail::on_btnForget_clicked() { qDebug() << "user choose forget connection uuid = " << m_uuid; m_connectOperation->deleteConnect(m_uuid); close(); } bool NetDetail::checkErrorMessage(QString &message) { if (m_isCreateNet && !isWlan) { if (!isCreateOk) { message = createNetPage->getErrorMessage(); return false; } } else { if (!isIpv4Ok) { message = ipv4Page->getErrorMessage(); return false; } if (!isIpv6Ok) { message = ipv6Page->getErrorMessage(); return false; } if (isWlan && !isSecuOk) { message = securityPage->getErrorMessage(); return false; } } return true; } #if 0 bool NetDetail::checkIpv4Conflict(QString ipv4Address) { showDesktopNotify(tr("start check IPv4 address conflict"), "networkwrong"); bool isConflict = false; KyIpv4Arping* ipv4Arping = new KyIpv4Arping(m_deviceName, ipv4Address); if (ipv4Arping->ipv4ConflictCheck() >= 0) { isConflict = ipv4Arping->ipv4IsConflict(); } else { qWarning() << "checkIpv4Conflict internal error"; } delete ipv4Arping; ipv4Arping = nullptr; return isConflict; } bool NetDetail::checkIpv6Conflict(QString ipv6address) { showDesktopNotify(tr("start check IPv6 address conflict"), "networkwrong"); bool isConflict = false; KyIpv6Arping* ipv46rping = new KyIpv6Arping(m_deviceName, ipv6address); if (ipv46rping->ipv6ConflictCheck() >= 0) { isConflict = ipv46rping->ipv6IsConflict(); } else { qWarning() << "checkIpv6Conflict internal error"; } delete ipv46rping; ipv46rping = nullptr; return isConflict; } #endif void NetDetail::updateWirelessPersonalConnect() { KyWirelessConnectSetting setting; securityPage->updateSecurityChange(setting); bool isPwdChanged = !(m_info.strPassword == setting.m_psk); m_wirelessConnOpration->updateWirelessPersonalConnect(m_uuid, setting, isPwdChanged); } void NetDetail::updateWirelessEnterPriseConnect(KyEapMethodType enterpriseType) { if (enterpriseType == TLS) { m_info.tlsInfo.devIfaceName = m_deviceName; securityPage->updateTlsChange(m_info.tlsInfo); m_wirelessConnOpration->updateWirelessEnterPriseTlsConnect(m_uuid, m_info.tlsInfo); } else if (enterpriseType == PEAP) { securityPage->updatePeapChange(m_info.peapInfo); m_wirelessConnOpration->updateWirelessEnterPrisePeapConnect(m_uuid, m_info.peapInfo); } else if (enterpriseType == TTLS) { securityPage->updateTtlsChange(m_info.ttlsInfo); m_wirelessConnOpration->updateWirelessEnterPriseTtlsConnect(m_uuid, m_info.ttlsInfo); } else if (enterpriseType == LEAP) { securityPage->updateLeapChange(m_info.leapInfo); m_wirelessConnOpration->updateWirelessEnterPriseLeapConnect(m_uuid, m_info.leapInfo); } else if (enterpriseType == PWD) { securityPage->updatePwdChange(m_info.pwdInfo); m_wirelessConnOpration->updateWirelessEnterPrisePwdConnect(m_uuid, m_info.pwdInfo); } else if (enterpriseType == FAST) { securityPage->updateFastChange(m_info.fastInfo); m_wirelessConnOpration->updateWirelessEnterPriseFastConnect(m_uuid, m_info.fastInfo); } else { qWarning() << "[NetDetail] unknown enterprise connection type" << enterpriseType; } } bool NetDetail::createWiredConnect() { KyWirelessConnectSetting connetSetting; connetSetting.setIfaceName(m_deviceName); createNetPage->constructIpv4Info(connetSetting); m_wiredConnOperation->createWiredConnect(connetSetting); return true; } bool NetDetail::createWirelessConnect() { KyWirelessConnectSetting connetSetting; KySecuType secuType; KyEapMethodType enterpriseType; securityPage->getSecuType(secuType, enterpriseType); //类型判断 if (!m_name.isEmpty()) { if (!checkWirelessSecurity(secuType)) { return false; } } //基本信息 QString ssid; if (m_name.isEmpty()) { detailPage->getSsid(ssid); } else { ssid = m_name; } connetSetting.setConnectName(ssid); connetSetting.setIfaceName(m_deviceName); if (detailPage->checkIsChanged(m_info)) { connetSetting.isAutoConnect = !m_info.isAutoConnect; } else { connetSetting.isAutoConnect = m_info.isAutoConnect; } qDebug() << "isAutoConnect" << connetSetting.isAutoConnect; connetSetting.m_ssid = ssid; // connetSetting.m_secretFlag = NetworkManager::Setting::None; //由于X.h的None与此处的None有歧义,此处直接使用值 connetSetting.m_secretFlag = NetworkManager::Setting::None; //ipv4 & ipv6 bool ipv4Change = ipv4Page->checkIsChanged(m_info, connetSetting); bool ipv6Change = ipv6Page->checkIsChanged(m_info, connetSetting); connetSetting.dumpInfo(); qDebug() << "ipv4Changed" << ipv4Change << "ipv6Change" << ipv6Change; //wifi安全性 if (secuType == WPA_AND_WPA2_ENTERPRISE) { connetSetting.m_type = WpaEap; if (enterpriseType == TLS) { m_info.tlsInfo.devIfaceName = m_deviceName; securityPage->updateTlsChange(m_info.tlsInfo); if (!m_name.isEmpty()) { qDebug() << "add new TLS connect"; m_wirelessConnOpration->addTlsConnect(connetSetting, m_info.tlsInfo); } else { qDebug() << "addAndConnect TLS connect"; m_wirelessConnOpration->addAndActiveWirelessEnterPriseTlsConnect(m_info.tlsInfo, connetSetting, m_deviceName, true); } } else if (enterpriseType == PEAP) { securityPage->updatePeapChange(m_info.peapInfo); if (!m_name.isEmpty()) { qDebug() << "add new PEAP connect"; m_wirelessConnOpration->addPeapConnect(connetSetting, m_info.peapInfo); } else { qDebug() << "addAndConnect PEAP connect"; m_wirelessConnOpration->addAndActiveWirelessEnterPrisePeapConnect(m_info.peapInfo, connetSetting, m_deviceName, true); } } else if (enterpriseType == TTLS) { securityPage->updateTtlsChange(m_info.ttlsInfo); if (!m_name.isEmpty()) { qDebug() << "add new TTLS connect"; m_wirelessConnOpration->addTtlsConnect(connetSetting, m_info.ttlsInfo); } else { qDebug() << "addAndConnect TTLS connect"; m_wirelessConnOpration->addAndActiveWirelessEnterPriseTtlsConnect(m_info.ttlsInfo, connetSetting, m_deviceName, true); } } else if (enterpriseType == LEAP) { securityPage->updateLeapChange(m_info.leapInfo); if (!m_name.isEmpty()) { qDebug() << "add new LEAP connect"; m_wirelessConnOpration->addLeapConnect(connetSetting, m_info.leapInfo); } else { qDebug() << "addAndConnect LEAP connect"; m_wirelessConnOpration->addAndActiveWirelessEnterPriseLeapConnect(m_info.leapInfo, connetSetting, m_deviceName, true); } } else if (enterpriseType == PWD) { securityPage->updatePwdChange(m_info.pwdInfo); if (!m_name.isEmpty()) { qDebug() << "add new PWD connect"; m_wirelessConnOpration->addPwdConnect(connetSetting, m_info.pwdInfo); } else { qDebug() << "addAndConnect PWD connect"; m_wirelessConnOpration->addAndActiveWirelessEnterPrisePwdConnect(m_info.pwdInfo, connetSetting, m_deviceName, true); } } else if (enterpriseType == FAST) { securityPage->updateFastChange(m_info.fastInfo); if (!m_name.isEmpty()) { qDebug() << "add new FAST connect"; m_wirelessConnOpration->addFastConnect(connetSetting, m_info.fastInfo); } else { qDebug() << "addAndConnect FAST connect"; m_wirelessConnOpration->addAndActiveWirelessEnterPriseFastConnect(m_info.fastInfo, connetSetting, m_deviceName, true); } } else { qWarning() << "[NetDetail] unknown enterprise connection type" << enterpriseType; } } else { securityPage->updateSecurityChange(connetSetting); if (!m_name.isEmpty()) { qDebug() << "add new personal connect"; m_wirelessConnOpration->addConnect(connetSetting); } else { qDebug() << "addAndConnect personal connect" << m_deviceName; m_wirelessConnOpration->addAndActiveWirelessConnect(m_deviceName, connetSetting, true); } } return true; } bool NetDetail::updateConnect() { KyConnectResourse *kyConnectResourse = new KyConnectResourse(this); KyConnectSetting connetSetting; KySecuType secuType; KyEapMethodType enterpriseType; kyConnectResourse->getConnectionSetting(m_uuid,connetSetting); bool securityChange = false; if (isWlan) { securityChange = securityPage->checkIsChanged(m_info); if(securityChange) { securityPage->getSecuType(secuType, enterpriseType); if (!checkWirelessSecurity(secuType)) { return false; } } } if(!m_uuid.isEmpty() && detailPage->checkIsChanged(m_info)) { m_wirelessConnOpration->setWirelessAutoConnect(m_uuid, !m_info.isAutoConnect); } bool ipv4Change = ipv4Page->checkIsChanged(m_info, connetSetting); bool ipv6Change = m_isPppoe ? false : ipv6Page->checkIsChanged(m_info, connetSetting); qDebug() << "ipv4Changed" << ipv4Change << "ipv6Change" << ipv6Change; if (ipv4Change || ipv6Change) { connetSetting.dumpInfo(); m_wiredConnOperation->updateWiredConnect(m_uuid, connetSetting); } qDebug() << "securityChange" << securityChange; if (securityChange) { if (secuType == WPA_AND_WPA2_ENTERPRISE) { updateWirelessEnterPriseConnect(enterpriseType); } else { updateWirelessPersonalConnect(); } } if (ipv4Change || ipv6Change || securityChange || ipv4Page->checkDnsSettingsIsChanged()) { if (isActive) { //信息变化 断开-重连 更新需要時間 不可以立即重連 // sleep(1); QEventLoop eventloop; QTimer::singleShot(1000, &eventloop, SLOT(quit())); eventloop.exec(); m_wirelessConnOpration->activateConnection(m_uuid, m_deviceName); } } if (m_networkMode != DBUS_INVAILD && m_networkMode != NO_CONFIG) { int configType = NetworkModeConfig::getInstance()->getNetworkModeConfig(m_uuid); bool configPageChange = configPage->checkIsChanged(configType); int currentConfigType = configPage->getConfigState(); // qDebug () << Q_FUNC_INFO << __LINE__<< configPageChange; if (configPageChange) { NetworkModeConfig::getInstance()->setNetworkModeConfig(m_uuid, m_deviceName, m_name, currentConfigType); // qDebug () <type() == QEvent::KeyPress) { QKeyEvent *mEvent = static_cast(event); if (mEvent->key() == Qt::Key_Enter || mEvent->key() == Qt::Key_Return) { if (confimBtn->isEnabled()) { Q_EMIT confimBtn->clicked(); } return true; } else if (mEvent->key() == Qt::Key_Escape) { close(); return true; } } return KDialog::eventFilter(w, event); } void NetDetail::setNetTabToolTip() { int tabCount = m_netTabBar->count(); for (int i = 0; i< tabCount; ++i) { QFontMetrics fontMetrics(m_netTabBar->font()); int fontSize = fontMetrics.horizontalAdvance(m_netTabBar->tabText(i)); if (fontSize > MAX_TAB_TEXT_LENGTH) { m_netTabBar->setTabToolTip(i, m_netTabBar->tabText(i)); } else { m_netTabBar->setTabToolTip(i, ""); } } } NetTabBar::NetTabBar(QWidget *parent) :KTabBar(KTabBarStyle::SegmentDark, parent) { } NetTabBar::~NetTabBar() { } QSize NetTabBar::sizeHint() const { QSize size = KTabBar::sizeHint(); size.setWidth(TAB_WIDTH); return size; } QSize NetTabBar::minimumTabSizeHint(int index) const { Q_UNUSED(index) QSize size = KTabBar::minimumTabSizeHint(index); size.setWidth(TAB_WIDTH); return size; } ThreadObject::ThreadObject(QString deviceName, QObject *parent) :m_devName(deviceName), QObject(parent) { m_isStop = false; } ThreadObject::~ThreadObject() { } void ThreadObject::stop() { m_isStop = true; } void ThreadObject::checkIpv4ConflictThread(const QString &ipv4Address) { if (m_isStop) { return; } bool isConflict = false; QDBusInterface dbusInterface(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, QDBusConnection::systemBus()); if(!dbusInterface.isValid()) { qWarning ()<< "check IPv4 conflict failed, init kylin.network.qt.systemdbus error"; Q_EMIT ipv4IsConflict(isConflict); return; } KyNetworkDeviceResourse resource; QStringList devList, devList1, devList2, macList; resource.getNetworkDeviceList(NetworkManager::Device::Type::Ethernet, devList1); resource.getNetworkDeviceList(NetworkManager::Device::Type::Wifi, devList2); devList << devList1 << devList2; for (int i = 0; i < devList.size(); ++i) { QString hardAddress; int band; resource.getHardwareInfo(devList.at(i), hardAddress, band); macList << hardAddress; } QDBusReply reply = dbusInterface.call("checkIpv4IsConflict", m_devName, ipv4Address, macList); if (reply.isValid()) { isConflict = reply.value(); } else { qWarning () << "check IPv4 conflict failed, dbus reply invalid"; } Q_EMIT ipv4IsConflict(isConflict); } void ThreadObject::checkIpv6ConflictThread(const QString &ipv6Address) { if (m_isStop) { return; } bool isConflict = false; QDBusInterface dbusInterface(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, QDBusConnection::systemBus()); if(!dbusInterface.isValid()) { qWarning () << "check IPv6 conflict failed, init kylin.network.qt.systemdbus error"; } else { QDBusReply reply = dbusInterface.call("checkIpv6IsConflict", m_devName, ipv6Address); if (reply.isValid()) { isConflict = reply.value(); } else { qWarning () << "check IPv6 conflict failed, dbus reply invalid"; } } Q_EMIT ipv6IsConflict(isConflict); } kylin-nm/src/frontend/netdetails/customtabstyle.h0000664000175000017500000000256415167651420021251 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef CUSTOMTABSTYLE_H #define CUSTOMTABSTYLE_H #include #include #include #include #include class CustomTabStyle : public QProxyStyle { public: CustomTabStyle(); QSize sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const; void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const; }; #endif // CUSTOMTABSTYLE_H kylin-nm/src/frontend/netdetails/dnssettingwidget.h0000664000175000017500000000245515167651420021554 0ustar fengfeng#ifndef DNSSETTINGWIDGET_H #define DNSSETTINGWIDGET_H #include #include #include #include #include #include #include #include "divider.h" using namespace kdk; class DnsSettingWidget : public KDialog { Q_OBJECT public: explicit DnsSettingWidget(QString timeout = "", QString retry = "", QString tactic = "", QWidget *parent = nullptr); void getDnsSettings(QString& timeout, QString& retry, QString& tactic) { timeout = QString::number(m_timeoutComboBox->currentData().toInt()); retry = QString::number(m_retryComboBox->currentData().toInt()); tactic = m_tacticComboBox->currentData().toString(); } private: QWidget* m_titleWidget; QWidget* m_centerWidget; QWidget* m_bottomWidget; QString m_timeout; QString m_retry; QString m_tactic; QLabel* m_titleLabel; QLabel* m_tacticLabel; QLabel* m_timeoutLabel; QLabel* m_retryLabel; QComboBox* m_tacticComboBox; QComboBox* m_timeoutComboBox; QComboBox* m_retryComboBox; Divider *m_bottomDivider = nullptr; QPushButton *m_cancelBtn; QPushButton *m_confirmBtn; void initUi(); void initConnect(); private Q_SLOTS: void onPaletteChanged(); }; #endif // DNSSETTINGWIDGET_H kylin-nm/src/frontend/netdetails/detailpage.cpp0000664000175000017500000003362515167651420020623 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "detailpage.h" #include #include #define MAX_NAME_LENGTH 32 #define MAX_LABEL_WIDTH 250 #define MAX_SSID_WIDTH 133 #define NET_DETAIL_CENTER_X 260 #define NET_DETAIL_CENTER_Y 194 extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); DetailPage::DetailPage(bool isWlan, bool isCreate, QWidget *parent) : m_IsWlan(isWlan), m_IsCreate(isCreate), QFrame(parent) { // this->setFrameShape(QFrame::Shape::StyledPanel); this->setMaximumWidth(960); initUI(); if (isCreate) { connect(m_SSIDEdit, &LineEdit::textEdited, this, &DetailPage::setEnableOfSaveBtn); } setInteractionFlag(); } DetailPage::~DetailPage() { if (m_copiedTip != nullptr) { delete m_copiedTip; m_copiedTip = nullptr; } } void DetailPage::setSSID(const QString &ssid) { if (m_IsCreate) { return; } m_formerSSID = ssid; QFontMetrics fontMetrics(m_SSIDLabel->font()); int fontSize = fontMetrics.horizontalAdvance(ssid); if (fontSize > MAX_SSID_WIDTH) { this->m_SSIDLabel->setText(fontMetrics.elidedText(ssid, Qt::ElideRight, MAX_SSID_WIDTH)); this->setToolTip(ssid); } else { this->m_SSIDLabel->setText(ssid); this->setToolTip(""); } } void DetailPage::setProtocol(const QString &protocol) { this->m_Protocol->setText(protocol); } void DetailPage::setSecType(const QString &secType) { this->m_SecType->setText(secType); } void DetailPage::setHz(const QString &hz) { this->m_Hz->setText(hz); } void DetailPage::setChan(const QString &chan) { this->m_Chan->setText(chan); } void DetailPage::setBandWidth(const QString &brandWidth) { this->m_BandWidth->setText(brandWidth); } void DetailPage::setIpv4(const QString &ipv4) { this->m_IPV4->setText(ipv4); } void DetailPage::setIpv4Dns(const QString &ipv4Dns) { this->m_IPV4Dns->setLabelText(ipv4Dns); } void DetailPage::setIpv6(const QString &ipv6) { m_formerIPV6 = ipv6; this->m_IPV6->setLabelText(ipv6); } void DetailPage::setMac(const QString &mac) { this->m_Mac->setText(mac); } void DetailPage::setAutoConnect(bool flag) { if (!m_IsWlan) { return; } this->m_forgetNetBox->setChecked(flag); } void DetailPage::getSsid(QString &ssid) { if (m_IsCreate) { ssid = m_SSIDEdit->text(); } else { ssid = m_SSIDLabel->text(); } } bool DetailPage::checkIsChanged(const ConInfo info) { if (!m_IsWlan) { return false; } if (info.isAutoConnect != m_forgetNetBox->isChecked()) { return true; } else { return false; } } void DetailPage::addDetailItem(QListWidget *listWidget, QWidget *detailWidget) { QListWidgetItem *listWidgetItem = new QListWidgetItem(listWidget); listWidgetItem->setSizeHint(QSize(listWidget->width(),36)); listWidgetItem->setFlags(Qt::NoItemFlags); listWidget->addItem(listWidgetItem); listWidget->setItemWidget(listWidgetItem, detailWidget); } void DetailPage::newCopiedTip() { //设置“复制成功”消息弹窗格式 m_copiedTip = new KBallonTip(this); m_copiedTip->setTipType(Normal); m_copiedTip->setContentsMargins(16, 14, 16, 14); m_copiedTip->adjustSize(); m_copiedTip->setAttribute(Qt::WA_TranslucentBackground, true); m_copiedTip->setText(tr("Copied successfully!")); QPalette pal = m_copiedTip->palette(); pal.setColor(QPalette::Window, qApp->palette().window().color()); pal.setColor(QPalette::WindowText, qApp->palette().windowText().color()); m_copiedTip->setPalette(pal); } void DetailPage::setInteractionFlag() { if (m_SSIDLabel != nullptr) { m_SSIDLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); m_SSIDLabel->setCursor(Qt::IBeamCursor); } //文字部分响应鼠标的可选择状态 m_Protocol->setTextInteractionFlags(Qt::TextSelectableByMouse); m_SecType->setTextInteractionFlags(Qt::TextSelectableByMouse); m_Hz->setTextInteractionFlags(Qt::TextSelectableByMouse); m_Chan->setTextInteractionFlags(Qt::TextSelectableByMouse); m_BandWidth->setTextInteractionFlags(Qt::TextSelectableByMouse); m_IPV6->setTextInteractionFlags(Qt::TextSelectableByMouse); m_IPV4->setTextInteractionFlags(Qt::TextSelectableByMouse); m_IPV4Dns->setTextInteractionFlags(Qt::TextSelectableByMouse); m_Mac->setTextInteractionFlags(Qt::TextSelectableByMouse); //鼠标移入指针变成光标 m_Protocol->setCursor(Qt::IBeamCursor); m_SecType->setCursor(Qt::IBeamCursor); m_Hz->setCursor(Qt::IBeamCursor); m_Chan->setCursor(Qt::IBeamCursor); m_BandWidth->setCursor(Qt::IBeamCursor); m_IPV6->setCursor(Qt::IBeamCursor); m_IPV4->setCursor(Qt::IBeamCursor); m_IPV4Dns->setCursor(Qt::IBeamCursor); m_Mac->setCursor(Qt::IBeamCursor); m_IPV4Dns->setScaledContents(true); } void DetailPage::initUI() { m_layout = new QVBoxLayout(this); m_layout->setContentsMargins(0,0,0,0); m_layout->setSpacing(0); QWidget *mDetailFrame = new QFrame(this); mDetailFrame->setFixedHeight(362); m_DetailLayout = new QVBoxLayout(mDetailFrame); m_DetailLayout->setContentsMargins(0,0,0,0); m_listWidget = new QListWidget(mDetailFrame); m_listWidget->setFrameShape(QFrame::Shape::NoFrame); m_listWidget->setBackgroundRole(QPalette::Base); m_listWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus); m_DetailLayout->addWidget(m_listWidget); m_listWidget->setFrameShape(QFrame::Shape::StyledPanel); if (!m_IsCreate) { m_SSIDLabel = new QLabel(this); m_SSIDLabel->adjustSize(); m_SSIDLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_netCopyButton = new QPushButton(this); m_netCopyButton->setIcon(QIcon::fromTheme("edit-copy-symbolic")); m_netCopyButton->setToolTip(tr("Copy all")); //设置按钮背景颜色-透明 QPalette btnPal = m_netCopyButton->palette(); QColor color = qApp->palette().color(QPalette::WindowText); color.setAlphaF(0); btnPal.setColor(QPalette::Button, color); m_netCopyButton->setPalette(btnPal); m_ssidWidget = new DetailWidget(qobject_cast(m_SSIDLabel), m_listWidget, m_netCopyButton); connect(m_netCopyButton, &QPushButton::clicked, this, &DetailPage::on_btnCopyNetDetail_clicked); newCopiedTip(); // mSSID->setStyleSheet("background:transparent;border-width:0px;border-style:none"); // mSSID->setFocusPolicy(Qt::NoFocus); } else { // mSSID->setStyleSheet("border-width:1px;;border-style:solid;border-color:black;border-radius:2px"); m_SSIDEdit = new LineEdit(this); m_SSIDEdit->setMaximumWidth(MAX_LABEL_WIDTH); m_SSIDEdit->setAlignment(Qt::AlignRight); m_SSIDEdit->setStyleSheet("border-top:0px solid;border-bottom:1px solid;border-left:0px solid;border-right: 0px solid;background:transparent"); m_SSIDEdit->setPlaceholderText(tr("Please input SSID:")); QRegularExpression nameRx("^.{0,32}$"); QValidator *validator = new QRegularExpressionValidator(nameRx, this); m_SSIDEdit->setValidator(validator); m_ssidWidget = new DetailWidget(qobject_cast(m_SSIDEdit), m_listWidget); } m_ssidWidget->setKey(tr("SSID:")); m_Protocol = new QLabel(this); m_protocolWidget = new DetailWidget(qobject_cast(m_Protocol), m_listWidget); m_protocolWidget->setKey(tr("Protocol:")); m_SecType = new QLabel(this); m_secTypeWidget = new DetailWidget(qobject_cast(m_SecType)); m_secTypeWidget->setKey(tr("Security Type:")); m_Hz = new QLabel(this); m_hzWidget = new DetailWidget(qobject_cast(m_Hz)); m_hzWidget->setKey(tr("Hz:")); m_Chan = new QLabel(this); m_chanelWidget = new DetailWidget(qobject_cast(m_Chan)); m_chanelWidget->setKey(tr("Chan:")); m_BandWidth = new QLabel(this); m_bandwidthWidget = new DetailWidget(qobject_cast(m_BandWidth), m_listWidget); m_bandwidthWidget->setKey(tr("BandWidth:")); m_IPV4 = new QLabel(this); m_ipv4Widget = new DetailWidget(qobject_cast(m_IPV4), m_listWidget); m_ipv4Widget->setKey(tr("IPv4:")); m_IPV4Dns = new FixLabel(this); m_IPV4Dns->setFixedWidth(MAX_LABEL_WIDTH); m_IPV4Dns->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_ipv4DnsWidget = new DetailWidget(qobject_cast(m_IPV4Dns), m_listWidget); m_ipv4DnsWidget->setKey(tr("IPv4 DNS:")); m_IPV6 = new FixLabel(this); m_IPV6->setFixedWidth(MAX_LABEL_WIDTH); m_IPV6->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_ipv6Widget = new DetailWidget(qobject_cast(m_IPV6), m_listWidget); m_ipv6Widget->setKey(tr("IPv6:")); m_Mac = new QLabel(this); m_macWidget = new DetailWidget(qobject_cast(m_Mac), m_listWidget); m_macWidget->setKey(tr("Mac:")); if (m_IsWlan) { m_autoConnect = new QLabel(this); m_forgetNetBox = new QCheckBox(this); m_autoConnect->setText(tr("Auto Connection")); m_autoConWidget = new QWidget(this); m_AutoLayout = new QHBoxLayout(m_autoConWidget); QSpacerItem *horizontalSpacer; horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); m_AutoLayout->addSpacing(20); m_AutoLayout->addWidget(m_forgetNetBox); m_AutoLayout->addWidget(m_autoConnect); m_AutoLayout->addSpacerItem(horizontalSpacer); } this->addDetailItem(m_listWidget, m_ssidWidget); this->addDetailItem(m_listWidget, m_protocolWidget); if (m_IsWlan) { this->addDetailItem(m_listWidget, m_secTypeWidget); this->addDetailItem(m_listWidget, m_hzWidget); this->addDetailItem(m_listWidget, m_chanelWidget); } this->addDetailItem(m_listWidget, m_bandwidthWidget); this->addDetailItem(m_listWidget, m_ipv6Widget); this->addDetailItem(m_listWidget, m_ipv4Widget); this->addDetailItem(m_listWidget, m_ipv4DnsWidget); this->addDetailItem(m_listWidget, m_macWidget); QPalette mpal(m_listWidget->palette()); mpal.setColor(QPalette::Base, qApp->palette().base().color()); mpal.setColor(QPalette::AlternateBase, qApp->palette().alternateBase().color()); m_listWidget->setAlternatingRowColors(true); // m_listWidget->setAutoFillBackground(true); m_listWidget->setPalette(mpal); m_layout->addWidget(mDetailFrame); if (m_IsWlan) { // m_layout->addLayout(m_AutoLayout); m_layout->addWidget(m_autoConWidget); } m_layout->addStretch(); } void DetailPage::setEnableOfSaveBtn() { bool saveEnable = true; if (m_IsCreate) { saveEnable = !m_SSIDEdit->text().isEmpty(); } Q_EMIT setDetailPageState(saveEnable); } //获取列表信息 void DetailPage::on_btnCopyNetDetail_clicked() { QStringList netDetailList; QString ssidCopy = tr("SSID:"); QString protocolCopy = tr("Protocol:"); QString securityCopy = tr("Security Type:"); QString hzCopy= tr ("Hz:"); QString chanCopy= tr ("Chan:"); QString bandwithCopy = tr("BandWidth:"); QString ipv4Copy = tr("IPv4:"); QString ipv4dnsCopy = tr("IPv4 DNS:"); QString ipv6Copy = tr("IPv6:"); QString macCopy = tr("Mac:"); QString netDetailCopyText; ssidCopy.append(m_formerSSID); protocolCopy.append(this->m_Protocol->text()); netDetailList.append(ssidCopy); netDetailList.append(protocolCopy); if(m_IsWlan) { securityCopy.append(this->m_SecType->text()); hzCopy.append(this->m_Hz->text()); chanCopy.append(this->m_Chan->text()); netDetailList.append(securityCopy); netDetailList.append(hzCopy); netDetailList.append(chanCopy); } bandwithCopy += this->m_BandWidth->text(); ipv6Copy += m_formerIPV6; ipv4Copy += this->m_IPV4->text(); ipv4dnsCopy += this->m_IPV4Dns->getText(); macCopy += this->m_Mac->text(); netDetailList.append(bandwithCopy); netDetailList.append(ipv6Copy); netDetailList.append(ipv4Copy); netDetailList.append(ipv4dnsCopy); netDetailList.append(macCopy); // qDebug() << netDetailList; //设置剪贴板内容 netDetailCopyText = netDetailList.join("\n"); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(netDetailCopyText); //设置“复制成功”弹窗位置并显示 if (m_copiedTip != nullptr) { delete m_copiedTip; newCopiedTip(); } //offset为窗口偏移量,在不同语言环境下,返回的KBallonTip的width是恒定的, //故而无法通过width来判断中心位置,只能引入各个偏移量来解决此问题 int offset = 0; QLocale locale = QLocale::system(); QPoint position = mapToGlobal(this->pos()); if (locale.name() == "nm_MN") { offset = -45; } if (locale.name() == "bo_CN") { offset = -50; } double x = (position.x() + NET_DETAIL_CENTER_X - m_copiedTip->width() + offset); double y = (position.y() + NET_DETAIL_CENTER_Y - m_copiedTip->height()); m_copiedTip->move(x, y); m_copiedTip->showInfo(); } kylin-nm/src/frontend/netdetails/netdetails.pri0000664000175000017500000000134715167646234020673 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/configpage.h \ $$PWD/coninfo.h \ $$PWD/creatnetpage.h \ $$PWD/customtabstyle.h \ $$PWD/detailpage.h \ $$PWD/detailwidget.h \ $$PWD/ipv4page.h \ $$PWD/ipv6page.h \ $$PWD/joinhiddenwifipage.h \ $$PWD/multiplednswidget.h \ $$PWD/netdetail.h \ $$PWD/securitypage.h \ $$PWD/dnssettingwidget.h SOURCES += \ $$PWD/configpage.cpp \ $$PWD/creatnetpage.cpp \ $$PWD/customtabstyle.cpp \ $$PWD/detailpage.cpp \ $$PWD/detailwidget.cpp \ $$PWD/ipv4page.cpp \ $$PWD/ipv6page.cpp \ $$PWD/joinhiddenwifipage.cpp \ $$PWD/multiplednswidget.cpp \ $$PWD/netdetail.cpp \ $$PWD/securitypage.cpp \ $$PWD/dnssettingwidget.cpp kylin-nm/src/frontend/netdetails/ipv4page.h0000664000175000017500000000707315167651420017706 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef IPV4PAGE_H #define IPV4PAGE_H #include #include #include #include #include #include #include #include #include #include //#include "kylinconnectsetting.h" #include "klabel.h" #include "coninfo.h" #include "multiplednswidget.h" #include "divider.h" class Ipv4Page : public QFrame { Q_OBJECT public: Ipv4Page(QWidget *parent = nullptr); void setIpv4Config(KyIpConfigType ipv4Config); void setIpv4(const QString &ipv4); void setNetMask(const QString &netMask); void setMulDns(const QList &dns); void setGateWay(const QString &gateWay); void setUuid(QString uuid) { if (m_dnsWidget != nullptr) { m_dnsWidget->setUuid(uuid); } } bool checkIsChanged(const ConInfo info, KyConnectSetting &setting); bool checkDnsSettingsIsChanged(); void startLoading(); void stopLoading(); void showIpv4AddressConflict(bool isConflict); QString getErrorMessage(); private: QComboBox *ipv4ConfigCombox; LineEdit *ipv4addressEdit; LineEdit *netMaskEdit; LineEdit *gateWayEdit; QFormLayout *m_detailLayout; QVBoxLayout *mvBoxLayout; QLabel *m_configLabel; QLabel *m_addressLabel; QLabel *m_maskLabel; QLabel *m_gateWayLabel; QLabel *m_configEmptyLabel; KLabel *m_addressHintLabel; KLabel *m_maskHintLabel; QLabel *m_gateWayEmptyLabel; QLabel *m_dnsEmptyLabel; MultipleDnsWidget *m_dnsWidget = nullptr; QLabel *m_statusLabel = nullptr; QList m_loadIcons; QTimer *m_iconTimer = nullptr; int m_currentIconIndex =0; QLabel *m_iconLabel; KLabel *m_textLabel; QString m_errorMessage; //kylin 网络设置控制接口 bool m_ipv4addressCtrl = false; bool m_netMaskCtrl = false; bool m_gateWayCtrl = false; bool m_dnsWayCtrl = false; private: void initUI(); void initComponent(); void setLineEnabled(bool check); void configSave(); bool getTextEditState(QString text); bool netMaskIsValide(QString text); QString getNetMaskText(QString text); bool checkConnectBtnIsEnabled(); void initConflictHintLable(); void initLoadingIcon(); void initNetCtrl(); void updateUi(); private Q_SLOTS: void setEnableOfSaveBtn(); void configChanged(int index); void onAddressTextChanged(); void onNetMaskTextChanged(); void onAddressEditFinished(); void updateIcon(); void updateNetCtrl(QString modName, QVariantMap value); Q_SIGNALS: void setIpv4PageState(bool); void ipv4EditFinished(const QString &address); void scrollToBottom(); }; #endif // IPV4PAGE_H kylin-nm/src/frontend/netdetails/netdetail.h0000664000175000017500000001432215167651420020133 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef NETDETAIL_H #define NETDETAIL_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "detailpage.h" #include "ipv4page.h" #include "ipv6page.h" #include "securitypage.h" #include "creatnetpage.h" #include "configpage.h" #include "coninfo.h" #include "tab-pages/tabpage.h" #include "kwidget.h" #include "ktabbar.h" #include "kdialog.h" #include "networkmodeconfig.h" using namespace kdk; #define TAB_WIDTH 60 #define TAB_HEIGHT 36 #define TAB_HEIGHT_TABLET 48 class WarningDialog : public KDialog { Q_OBJECT public: explicit WarningDialog(QWidget *parent = nullptr); void setWarningMessage(QString); private: void initUI(); QLabel* warningLabel = nullptr; QLabel* warningTitle = nullptr; QLabel* warningText = nullptr; QPushButton* confirmButton = nullptr; }; class NetTabBar : public KTabBar { Q_OBJECT public: explicit NetTabBar(QWidget *parent = nullptr); ~NetTabBar(); protected: QSize sizeHint() const; QSize minimumTabSizeHint(int index) const; }; class ThreadObject : public QObject { Q_OBJECT public: ThreadObject(QString deviceName, QObject *parent = nullptr); ~ThreadObject(); void stop(); private: QString m_devName; volatile bool m_isStop; public Q_SLOTS: void checkIpv4ConflictThread(const QString &ipv4Address); void checkIpv6ConflictThread(const QString &ipv6Address); Q_SIGNALS: bool ipv4IsConflict(bool isConflict); bool ipv6IsConflict(bool isConflict); }; class NetDetail : public KDialog { Q_OBJECT public: NetDetail(QString interface, QString name, QString uuid, bool isActive, bool isWlan, bool isCreateNet,int category, QWidget *parent = nullptr); ~NetDetail(); void closeEvent(QCloseEvent *event); bool eventFilter(QObject *w, QEvent *event); private: void initUI(); void centerToScreen(); void initComponent(); void getConInfo(ConInfo &conInfo); void loadPage(); void pagePadding(QString netName, bool isWlan); void initSecuData(); void initTlsInfo(ConInfo &conInfo); void initPeapInfo(ConInfo &conInfo); void initTtlsInfo(ConInfo &conInfo); void initLeapInfo(ConInfo &conInfo); void initPwdInfo(ConInfo &conInfo); void initFastInfo(ConInfo &conInfo); void updateWirelessPersonalConnect(); void updateWirelessEnterPriseConnect(KyEapMethodType enterpriseType); //详情ssid 带宽 物理地址 无线额外(安全性 频带 通道) void getBaseInfo(ConInfo &conInfo); //详情ipv4 ipv6 ipv4Dns void getDynamicIpInfo(ConInfo &conInfo, bool bActived); //ipv4+ipv6页面 void getStaticIpInfo(ConInfo &conInfo, bool bActived); bool checkErrorMessage(QString&); // bool checkIpv4Conflict(QString ipv4Address); // bool checkIpv6Conflict(QString ipv6Address); bool createWiredConnect(); bool createWirelessConnect(); bool updateConnect(); bool checkWirelessSecurity(KySecuType secuType); void showDesktopNotify(const QString &message, QString soundName); void setNetdetailSomeEnable(bool on); void startObjectThread(); void setNetTabToolTip(); private: KyNetworkDeviceResourse *m_netDeviceResource = nullptr; KyConnectOperation* m_connectOperation = nullptr; KyWirelessConnectOperation *m_wirelessConnOpration = nullptr; KyWiredConnectOperation *m_wiredConnOperation = nullptr; KyWirelessNetResource *m_resource = nullptr; QStackedWidget * stackWidget; DetailPage * detailPage; Ipv4Page * ipv4Page; Ipv6Page * ipv6Page; SecurityPage * securityPage; CreatNetPage * createNetPage; ConfigPage * configPage; QWidget * centerWidget; QWidget * bottomWidget; QScrollArea * m_secuPageScrollArea; QScrollArea * m_ipv4ScrollArea; QScrollArea * m_ipv6ScrollArea; QScrollArea * m_configScrollArea; QScrollArea * m_createNetPageScrollArea; QPushButton * cancelBtn; QPushButton * forgetBtn; QPushButton * confimBtn; QFrame * pageFrame; NetTabBar *m_netTabBar = nullptr; QString m_name; QString m_uuid; QString m_deviceName; bool isWlan; bool m_isCreateNet; bool isActive; bool isHideWlan; bool m_isPppoe = false; bool isCreateOk; bool isDetailOk; bool isIpv4Ok; bool isIpv6Ok; bool isSecuOk; bool isConfirmBtnEnable; int mCategory; ConInfo m_info; ThreadObject *m_object; QThread *m_objectThread; NetworkModeType m_networkMode = DBUS_INVAILD; private Q_SLOTS: void on_btnConfirm_clicked(); void on_btnForget_clicked(); void onPaletteChanged(); protected Q_SLOTS: void currentRowChangeSlot(int row); Q_SIGNALS: void detailPageClose(QString, QString, QString); void createPageClose(QString); void currentChanged(int); void checkCurrentIpv4Conflict(const QString &address); void checkCurrentIpv6Conflict(const QString &address); }; #endif // NETDETAIL_H kylin-nm/src/frontend/netdetails/joinhiddenwifipage.cpp0000664000175000017500000002544215167651420022351 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "joinhiddenwifipage.h" #include #include #include "kwindowsystem_export.h" #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" #define WINDOW_WIDTH 480 #define MIN_WINDOW_HEIGHT 368 #define EAPMIN_WINDOW_HEIGHT 524 #define TLS_WINDOW_HEIGHT 580 #define LAYOUT_MARGINS 0, 0, 0, 0 #define TOP_LAYOUT_MARGINS 24, 12, 24, 16 #define CENTER_LAYOUT_MARGINS 24, 0, 24, 8 #define BOTTOM_LAYOUT_MARGINS 24, 24, 24, 24 #define LAYOUT_SPACING 16 #define LABEL_MIN_WIDTH 146 #define LABEL_MAX_WIDTH 434 #define MAX_NAME_LENGTH 32 #define SCROAREA_WIDTH 480 #define MEDIUM_WEIGHT_VALUE 57 JoinHiddenWiFiPage::JoinHiddenWiFiPage(QString devName, KDialog *parent) :m_devName(devName), KDialog(parent) { m_wirelessConnOpration = new KyWirelessConnectOperation(this); initUI(); initComponent(); setAttribute(Qt::WA_DeleteOnClose); KX11Extras::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager); setJoinBtnEnable(); } JoinHiddenWiFiPage::~JoinHiddenWiFiPage() { } void JoinHiddenWiFiPage::closeEvent(QCloseEvent *event) { Q_EMIT this->hiddenWiFiPageClose(m_devName); return QWidget::closeEvent(event); } void JoinHiddenWiFiPage::initUI() { m_topWidget = new QWidget(this); m_centerWidget = new QWidget(this); m_bottomWidget = new QWidget(this); m_secuWidget = new SecurityPage(false, this); m_secuWidget->setSecurity(KySecuType::WPA_AND_WPA2_PERSONAL); m_descriptionLabel = new FixLabel(this); m_descriptionLabel->setFixedWidth(LABEL_MAX_WIDTH); m_nameLabel = new FixLabel(this); m_nameLabel->setFixedWidth(LABEL_MIN_WIDTH); m_nameEdit =new LineEdit(this); m_bottomDivider = new Divider(false, this); m_showListBtn = new KBorderlessButton(this); m_cancelBtn =new QPushButton(this); m_joinBtn =new QPushButton(this); m_hiddenWifiScrollArea = new QScrollArea(this); m_hiddenWifiScrollArea->setFrameShape(QFrame::NoFrame); m_hiddenWifiScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); QPalette pa = m_hiddenWifiScrollArea->palette(); pa.setBrush(QPalette::Window, Qt::transparent); m_hiddenWifiScrollArea->setPalette(pa); m_pageLayout = new QVBoxLayout(this); m_pageLayout->setContentsMargins(LAYOUT_MARGINS); m_pageLayout->setSpacing(0); m_pageLayout->addWidget(m_topWidget); m_pageLayout->addWidget(m_hiddenWifiScrollArea); m_pageLayout->addWidget(m_bottomDivider); m_pageLayout->addWidget(m_bottomWidget); this->mainWidget()->setLayout(m_pageLayout); m_topLayout = new QHBoxLayout(m_topWidget); m_topLayout->setContentsMargins(TOP_LAYOUT_MARGINS); m_topLayout->setSpacing(0); m_topLayout->addWidget(m_descriptionLabel); m_topLayout->addStretch(); QWidget *ssidWidget = new QWidget(this); QHBoxLayout *ssidLayout = new QHBoxLayout(ssidWidget); ssidLayout->setContentsMargins(LAYOUT_MARGINS); ssidLayout->setSpacing(0); m_nameLabel->setMinimumWidth(LABEL_MIN_WIDTH); ssidLayout->addWidget(m_nameLabel); ssidLayout->addWidget(m_nameEdit); m_centerVBoxLayout = new QVBoxLayout(m_centerWidget); m_centerVBoxLayout->setContentsMargins(CENTER_LAYOUT_MARGINS); m_centerVBoxLayout->setSpacing(0); m_centerVBoxLayout->addWidget(ssidWidget); m_centerVBoxLayout->addSpacing(LAYOUT_SPACING); m_centerVBoxLayout->addWidget(m_secuWidget); m_centerWidget->setFixedWidth(SCROAREA_WIDTH); m_hiddenWifiScrollArea->setFixedWidth(SCROAREA_WIDTH); m_hiddenWifiScrollArea->setWidget(m_centerWidget); m_hiddenWifiScrollArea->setWidgetResizable(true); //底部按钮 m_bottomLayout = new QHBoxLayout(m_bottomWidget); m_bottomLayout->setContentsMargins(BOTTOM_LAYOUT_MARGINS); m_bottomLayout->setSpacing(LAYOUT_SPACING); m_bottomLayout->addWidget(m_showListBtn); m_bottomLayout->addStretch(); m_bottomLayout->addWidget(m_cancelBtn); m_bottomLayout->addWidget(m_joinBtn); //请输入您想要加入的网络信息 m_descriptionLabel->setLabelText(tr("Please enter the network information")); QFont font = m_descriptionLabel->font(); font.setWeight(QFont::Medium);//qt6使用枚举 m_descriptionLabel->setFont(font); m_nameLabel->setLabelText(tr("Network name(SSID)")); //网络名(SSID) m_showListBtn->setText(tr("Show Network List")); //显示网络列表 m_cancelBtn->setText(tr("Cancel")); m_joinBtn->setText(tr("Join")); m_joinBtn->setProperty("useButtonPalette", false); m_joinBtn->setProperty("isImportant", true); m_cancelBtn->setProperty("useButtonPalette", true); m_cancelBtn->setProperty("isImportant", false); QRegularExpression nameRx("^.{0,32}$"); QValidator *validator = new QRegularExpressionValidator(nameRx, this); m_nameEdit->setValidator(validator); m_nameEdit->setPlaceholderText(tr("Required")); //必填 this->setWindowTitle(tr("Find and Join WLAN")); this->setWindowIcon(QIcon::fromTheme("kylin-network")); this->setFixedWidth(WINDOW_WIDTH); this->setFixedHeight(MIN_WINDOW_HEIGHT); // onPaletteChanged(); } void JoinHiddenWiFiPage::initComponent() { connect(m_cancelBtn, &QPushButton::clicked, this, [=] { close(); }); connect(m_joinBtn, SIGNAL(clicked()), this, SLOT(onBtnJoinClicked())); connect(m_showListBtn, SIGNAL(clicked()), this, SLOT(onBtnShowListClicked())); connect(m_secuWidget, &SecurityPage::secuTypeChanged, this, &JoinHiddenWiFiPage::onSecuTypeChanged); connect(m_secuWidget, &SecurityPage::eapTypeChanged, this, &JoinHiddenWiFiPage::onEapTypeChanged); connect(m_secuWidget, &SecurityPage::setSecuPageState, this, [ = ](bool status) { m_isSecuOk = status; setJoinBtnEnable(); }); connect(m_nameEdit, &LineEdit::textChanged, this, &JoinHiddenWiFiPage::setJoinBtnEnable); #if 0 connect(qApp, &QApplication::paletteChanged, this, &JoinHiddenWiFiPage::onPaletteChanged); const QByteArray id(THEME_SCHAME); if(QGSettings::isSchemaInstalled(id)){ QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); connect(fontSetting, &QGSettings::changed,[=](QString key) { if ("themeColor" == key) { onPaletteChanged(); } }); } #endif } void JoinHiddenWiFiPage::setJoinBtnEnable() { if (!m_nameEdit->text().isEmpty() && m_isSecuOk) { m_isJoinBtnEnable = true; } else { m_isJoinBtnEnable = false; } m_joinBtn->setEnabled(m_isJoinBtnEnable); } void JoinHiddenWiFiPage::onBtnJoinClicked() { KyWirelessConnectSetting connSettingInfo; //基本信息 connSettingInfo.m_ssid = m_nameEdit->text(); connSettingInfo.setConnectName(connSettingInfo.m_ssid); connSettingInfo.setIfaceName(m_devName); connSettingInfo.m_secretFlag =NetworkManager::Setting::SecretFlagType::None; KySecuType secuType; KyEapMethodType eapType; m_secuWidget->getSecuType(secuType, eapType); if (secuType == WPA_AND_WPA2_ENTERPRISE) { if (eapType == TLS) { m_info.tlsInfo.devIfaceName = m_devName; m_secuWidget->updateTlsChange(m_info.tlsInfo); m_wirelessConnOpration->addAndActiveWirelessEnterPriseTlsConnect(m_info.tlsInfo, connSettingInfo, m_devName, true); } else if (eapType == PEAP) { m_secuWidget->updatePeapChange(m_info.peapInfo); m_wirelessConnOpration->addAndActiveWirelessEnterPrisePeapConnect(m_info.peapInfo, connSettingInfo, m_devName, true); } else if (eapType == TTLS) { m_secuWidget->updateTtlsChange(m_info.ttlsInfo); m_wirelessConnOpration->addAndActiveWirelessEnterPriseTtlsConnect(m_info.ttlsInfo, connSettingInfo, m_devName, true); } else if (eapType == LEAP) { m_secuWidget->updateLeapChange(m_info.leapInfo); m_wirelessConnOpration->addAndActiveWirelessEnterPriseLeapConnect(m_info.leapInfo, connSettingInfo, m_devName, true); } else if (eapType == PWD) { m_secuWidget->updatePwdChange(m_info.pwdInfo); m_wirelessConnOpration->addAndActiveWirelessEnterPrisePwdConnect(m_info.pwdInfo, connSettingInfo, m_devName, true); } else if (eapType == FAST) { m_secuWidget->updateFastChange(m_info.fastInfo); m_wirelessConnOpration->addAndActiveWirelessEnterPriseFastConnect(m_info.fastInfo, connSettingInfo, m_devName, true); } } else { m_secuWidget->updateSecurityChange(connSettingInfo); m_wirelessConnOpration->addAndActiveWirelessConnect(m_devName, connSettingInfo, true); } close(); } void JoinHiddenWiFiPage::onBtnShowListClicked() { QDBusInterface sidebarIfc("org.ukui.Sidebar", "/org/ukui/Sidebar", "org.ukui.Sidebar", QDBusConnection::sessionBus()); sidebarIfc.call("shortcutWidgetActive", "org.ukui.shortcut.network", false); } void JoinHiddenWiFiPage::onSecuTypeChanged(const KySecuType &type) { if (type != KySecuType::WPA_AND_WPA2_ENTERPRISE) { this->setFixedHeight(MIN_WINDOW_HEIGHT); } } void JoinHiddenWiFiPage::onEapTypeChanged(const KyEapMethodType &type) { if (type == KyEapMethodType::TLS || type == KyEapMethodType::FAST) { this->setFixedHeight(TLS_WINDOW_HEIGHT); } else { this->setFixedHeight(EAPMIN_WINDOW_HEIGHT); } } #if 0 void JoinHiddenWiFiPage::onPaletteChanged() { QPalette pal = qApp->palette(); QGSettings * styleGsettings = nullptr; const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { styleGsettings = new QGSettings(style_id); QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = lightPalette(this); } } this->setPalette(pal); setFramePalette(m_secuWidget, pal); setFramePalette(m_hiddenWifiScrollArea, pal); if (styleGsettings != nullptr) { delete styleGsettings; styleGsettings = nullptr; } } #endif kylin-nm/src/frontend/netdetails/configpage.cpp0000664000175000017500000001045415167651420020621 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "configpage.h" #include #define VERTICAL_SPACING 24 #define KSC_FIREWALL_NOCONFIG -1 #define KSC_FIREWALL_PUBLIC 0 #define KSC_FIREWALL_PRIVATE 1 ConfigPage::ConfigPage(QWidget *parent) { initUi(); initComponent(); } void ConfigPage::initUi() { m_descriptionLabel = new QLabel(this); m_publicButton = new QRadioButton(this); m_privateButton = new QRadioButton(this); m_publicLabel = new QLabel(this); m_privateLabel = new QLabel(this); m_congigBtn = new KBorderlessButton(this); QWidget *centerWidget = new QWidget(this); QFormLayout *formLayout = new QFormLayout(centerWidget); formLayout->setContentsMargins(0, 0, 0, 0); formLayout->setVerticalSpacing(VERTICAL_SPACING); formLayout->addRow(m_publicButton, m_publicLabel); formLayout->addRow(m_privateButton, m_privateLabel); m_vBoxLayout = new QVBoxLayout(this); m_vBoxLayout->setContentsMargins(0, 0, 0, 0); m_vBoxLayout->setSpacing(VERTICAL_SPACING); m_vBoxLayout->addWidget(m_descriptionLabel); m_vBoxLayout->addWidget(centerWidget); m_vBoxLayout->addWidget(m_congigBtn); m_vBoxLayout->addStretch(); //网络配置文件类型 m_descriptionLabel->setText(tr("Network profile type")); m_descriptionLabel->setAlignment(Qt::AlignLeft); //公用(推荐) 网络中的设备不可发现此电脑。一般情况下适用于公共场所中的网络,如机场或咖啡店等等。 m_publicLabel->setText(tr("Public(recommended) Devices on the network cannot discover this computer. Generally, " "it is suitable for networks in public places, such as airports or coffee shops, etc.")); m_publicLabel->setWordWrap(true); //专用 网络中的设备可发现此电脑。一般情况下适用于家庭或工作单位的网络,您认识并信任网络上的个人和设备。 m_privateLabel->setText(tr("Private Devices on the network can discover this computer. Generally applicable to a network " "at home or work where you know and trust the individuals and devices on the network.")); m_privateLabel->setWordWrap(true); //配置防火墙和安全设置 m_congigBtn->setText(tr("Config firewall and security settings")); QPalette btnPal; QColor btnColor = palette().highlight().color(); btnPal.setColor(QPalette::ButtonText, btnColor); m_congigBtn->setPalette(btnPal); } void ConfigPage::initComponent() { connect(m_congigBtn, &KBorderlessButton::clicked, this, &ConfigPage::onConfigButtonClicked); } void ConfigPage::setConfigState(int type) { if (type == KSC_FIREWALL_PUBLIC) { m_publicButton->setChecked(true); } else if (type == KSC_FIREWALL_PRIVATE) { m_privateButton->setChecked(true); } } bool ConfigPage::checkIsChanged(int type) { if (type == KSC_FIREWALL_PUBLIC && m_publicButton->isChecked()) { return false; } else if (type == KSC_FIREWALL_PRIVATE && m_privateButton->isChecked()) { return false; } else { return true; } } int ConfigPage::getConfigState() { if (m_publicButton->isChecked()) { return KSC_FIREWALL_PUBLIC; } else if (m_privateButton->isChecked()) { return KSC_FIREWALL_PRIVATE; } return KSC_FIREWALL_NOCONFIG; } void ConfigPage::onConfigButtonClicked() { qDebug() << "show ksc defender net protect"; QProcess process; process.startDetached("/usr/sbin/ksc-defender --firewall"); } kylin-nm/src/frontend/netdetails/dnssettingwidget.cpp0000664000175000017500000001262715167651420022111 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "dnssettingwidget.h" #include #include #include #include #include "coninfo.h" #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" #define BOTTOM_LAYOUT_MARGINS 24, 16, 24, 24 #define LAYOUT_SPACING 16 DnsSettingWidget::DnsSettingWidget(QString timeout, QString retry, QString tactic, QWidget *parent) :m_timeout(timeout), m_retry(retry), m_tactic(tactic), KDialog(parent) { this->setFixedSize(420, 420); initUi(); initConnect(); onPaletteChanged(); } void DnsSettingWidget::initUi() { m_titleWidget = new QWidget(this); m_centerWidget = new QWidget(this); m_bottomWidget = new QWidget(this); m_titleLabel = new QLabel(this); m_titleLabel->setContentsMargins(24,14,0,0); m_titleLabel->setText(tr("DNS Server Advanced Settings")); m_tacticLabel = new QLabel(this); m_tacticLabel->setText(tr("Tactic")); m_timeoutLabel = new QLabel(this); m_timeoutLabel->setText(tr("Timeout")); m_retryLabel = new QLabel(this); m_retryLabel->setText(tr("Retry Count")); m_tacticComboBox = new QComboBox(this); m_tacticComboBox->addItem(tr("order"), "order"); m_tacticComboBox->addItem(tr("rotate"), "rotate"); m_tacticComboBox->addItem(tr("concurrency"), "concurrency"); m_tacticComboBox->setCurrentIndex(m_tacticComboBox->findData(m_tactic)); m_timeoutComboBox = new QComboBox(this); for (int i = 0; i < 30; ++i) { m_timeoutComboBox->insertItem(i, QString::number(i+1) + tr(" s"), QString::number(i+1)); } m_timeoutComboBox->setCurrentIndex(m_timeoutComboBox->findData(m_timeout.toInt())); m_retryComboBox = new QComboBox(this); for (int i = 0; i < 4; ++i) { m_retryComboBox->insertItem(i, QString::number(i+1) + tr(" times"), QString::number(i+1)); } m_retryComboBox->setCurrentIndex(m_retryComboBox->findData(m_retry.toInt())); m_bottomDivider = new Divider(false, this); m_cancelBtn = new QPushButton(this); m_cancelBtn->setText(tr("Cancel")); m_confirmBtn = new QPushButton(this); m_confirmBtn->setText(tr("Confirm")); QVBoxLayout* mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(0,0,0,0); mainLayout->setSpacing(0); mainLayout->addWidget(m_titleWidget); mainLayout->addWidget(m_titleLabel, Qt::AlignLeft); mainLayout->addWidget(m_centerWidget); mainLayout->addSpacing(115); mainLayout->addWidget(m_bottomDivider); mainLayout->addWidget(m_bottomWidget); this->mainWidget()->setLayout(mainLayout); //中间页面 QFormLayout* centerLayout = new QFormLayout(m_centerWidget); centerLayout->setContentsMargins(24,10,24,0); centerLayout->setSpacing(16); centerLayout->addRow(m_tacticLabel, m_tacticComboBox); centerLayout->addRow(m_timeoutLabel, m_timeoutComboBox); centerLayout->addRow(m_retryLabel, m_retryComboBox); //底部按钮 QHBoxLayout* bottomLayout = new QHBoxLayout(m_bottomWidget); bottomLayout->setContentsMargins(BOTTOM_LAYOUT_MARGINS); bottomLayout->setSpacing(LAYOUT_SPACING); bottomLayout->addStretch(); bottomLayout->addWidget(m_cancelBtn); bottomLayout->addWidget(m_confirmBtn); this->setWindowFlags(Qt::Dialog); } void DnsSettingWidget::initConnect() { connect(m_cancelBtn, &QPushButton::released, this, [=](){ reject(); }); connect(m_confirmBtn, &QPushButton::released, this, [=](){ m_timeout = m_timeoutComboBox->currentData().toString(); m_tactic = m_tacticComboBox->currentData().toString(); m_retry = m_retryComboBox->currentData().toString(); accept(); }); connect(qApp, &QApplication::paletteChanged, this, &DnsSettingWidget::onPaletteChanged); } void DnsSettingWidget::onPaletteChanged() { QPalette pal = qApp->palette(); QGSettings * styleGsettings = nullptr; const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { styleGsettings = new QGSettings(style_id); QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = lightPalette(this); } } this->setPalette(pal); QList comboBoxList = this->findChildren(); for (int i = 0; i < comboBoxList.count(); ++i) { comboBoxList.at(i)->setPalette(pal); if (comboBoxList.at(i)->view()) { comboBoxList.at(i)->view()->setPalette(pal); } } if (styleGsettings != nullptr) { delete styleGsettings; styleGsettings = nullptr; } } kylin-nm/src/frontend/connectivity/0000775000175000017500000000000015167651420016371 5ustar fengfengkylin-nm/src/frontend/connectivity/connectivitypage.h0000664000175000017500000000231515167651420022116 0ustar fengfeng#ifndef CONNECTIVITYPAGE_H #define CONNECTIVITYPAGE_H #include #include #include #include #include #include #include #include #include "divider.h" #include "kylinconnectresource.h" class ConnectivityPage : public QDialog { Q_OBJECT public: explicit ConnectivityPage(QString uri = "", QWidget *parent = nullptr); protected: void closeEvent(QCloseEvent *event); private: QScrollArea *m_scrollArea; QWidget* m_warningWidget; QWidget* m_centerWidget; QWidget* m_editWidget; QWidget* m_bottomWidget; QString m_uri; QPushButton *m_confirmBtn; QLabel *m_icon; QLabel *m_statusText; QLabel *m_text; QLabel *m_publicTextLabel; QLabel *m_intranetTextLabel; QRadioButton *m_publicNetworkButton; QRadioButton *m_intranetButton; QLineEdit *m_uriEdit; QLabel* m_warningLabel; KyConnectResourse* m_connectResource; void initUi(); void initConnect(); void centerToScreen(); private Q_SLOTS: void setWarning(NetworkManager::Connectivity connectivity); void checkUri(); Q_SIGNALS: void pageClose(); }; #endif // CONNECTIVITYPAGE_H kylin-nm/src/frontend/connectivity/connectivitypage.cpp0000664000175000017500000002261315167651420022454 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "connectivitypage.h" #include #include #include #include #include #include #include #include #include #include #include "windowmanager/windowmanager.h" #include "kwindowsystem_export.h" #include "kylinutil.h" #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" #define BOTTOM_LAYOUT_MARGINS 24, 16, 24, 24 #define LAYOUT_SPACING 16 ConnectivityPage::ConnectivityPage(QString uri, QWidget *parent) :m_uri(uri), QDialog(parent) { this->setAttribute(Qt::WA_DeleteOnClose, true); this->setFixedSize(380, 369); this->setWindowTitle(tr("Network connectivity detection")); setAttribute(Qt::WA_DeleteOnClose, false); KX11Extras::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager); centerToScreen(); m_connectResource = new KyConnectResourse(this); initUi(); initConnect(); NetworkManager::Connectivity connectivity; m_connectResource->getConnectivity(connectivity); setWarning(connectivity); m_publicNetworkButton->setChecked(m_uri.isEmpty()); m_intranetButton->setChecked(!m_uri.isEmpty()); if (!m_uri.isEmpty()) { checkUri(); } } void ConnectivityPage::initUi() { m_scrollArea = new QScrollArea(this); m_scrollArea->setFixedWidth(380); m_scrollArea->setFrameShape(QFrame::NoFrame); m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_scrollArea->setContentsMargins(0,0,0,0); m_icon = new QLabel(this); m_statusText = new QLabel(this); m_statusText->setWordWrap(true); //如访问 Internet 受限,请切换网络 IP 连通性检测方式后再试。 m_text = new QLabel(this); m_text->setText(tr("If access to the Internet is restricted, please switch the network IP connectivity detection method and try again.")); m_text->setWordWrap(true); m_text->adjustSize(); // m_text->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_publicTextLabel = new QLabel(this); m_intranetTextLabel = new QLabel(this); m_publicNetworkButton = new QRadioButton(this); m_intranetButton = new QRadioButton(this); m_publicTextLabel->setText(tr("Public network (default)")); m_publicTextLabel->setWordWrap(true); m_intranetTextLabel->setText(tr("Local area network (intranet)")); m_intranetTextLabel->setWordWrap(true); QWidget *radioBtnWidget = new QWidget(this); QFormLayout *formLayout = new QFormLayout(radioBtnWidget); formLayout->setContentsMargins(0, 0, 0, 0); formLayout->setVerticalSpacing(12); formLayout->addRow(m_publicNetworkButton, m_publicTextLabel); formLayout->addRow(m_intranetButton, m_intranetTextLabel); m_uriEdit = new QLineEdit(this); m_uriEdit->setText(m_uri); m_warningLabel = new QLabel(this); QPalette hintTextColor; hintTextColor.setColor(QPalette::WindowText, Qt::red); m_warningLabel->setPalette(hintTextColor); m_warningLabel->setWordWrap(true); m_confirmBtn = new QPushButton(this); m_confirmBtn->setText(tr("Confirm")); m_warningWidget = new QWidget(this); m_warningWidget->adjustSize(); m_editWidget = new QWidget(this); m_centerWidget = new QWidget(this); m_centerWidget->setFixedWidth(380); m_bottomWidget = new QWidget(this); QHBoxLayout* warningLayout = new QHBoxLayout(m_warningWidget); warningLayout->setContentsMargins(0, 0, 0, 24); warningLayout->setSpacing(8); warningLayout->addWidget(m_icon); warningLayout->addWidget(m_statusText); warningLayout->addStretch(); QVBoxLayout* editLayout = new QVBoxLayout(m_editWidget); editLayout->setContentsMargins(22,0,0,0); editLayout->setSpacing(0); editLayout->addWidget(m_uriEdit); editLayout->addWidget(m_warningLabel); QVBoxLayout* mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(0,0,0,0); mainLayout->setSpacing(0); mainLayout->addWidget(m_scrollArea); mainLayout->addWidget(m_bottomWidget); this->setLayout(mainLayout); //中间页面 QVBoxLayout *vLayout = new QVBoxLayout(m_centerWidget); vLayout->setContentsMargins(25, 17, 23, 0); vLayout->setSpacing(0); vLayout->addWidget(m_warningWidget); vLayout->addWidget(m_text); vLayout->addSpacing(10); vLayout->addWidget(radioBtnWidget); vLayout->addWidget(m_editWidget); //底部按钮 QHBoxLayout* bottomLayout = new QHBoxLayout(m_bottomWidget); bottomLayout->setContentsMargins(BOTTOM_LAYOUT_MARGINS); bottomLayout->setSpacing(LAYOUT_SPACING); bottomLayout->addStretch(); bottomLayout->addWidget(m_confirmBtn); m_scrollArea->setWidget(m_centerWidget); m_scrollArea->setWidgetResizable(true); this->setWindowFlags(Qt::Dialog); } void ConnectivityPage::initConnect() { connect(m_confirmBtn, &QPushButton::released, this, [=](){ if (m_publicNetworkButton->isChecked()) { setConnectivityCheckSpareUriByGDbus(""); } else { setConnectivityCheckSpareUriByGDbus(m_uriEdit->text()); } close(); }); connect(m_publicNetworkButton, &QRadioButton::toggled, [&](bool checked){ if (checked) { m_uriEdit->clear(); m_uriEdit->setDisabled(true); m_confirmBtn->setEnabled(true); if (m_warningLabel) { m_warningLabel->clear(); m_warningLabel->hide(); } } }); connect(m_intranetButton, &QRadioButton::toggled, [&](bool checked){ if (checked) { checkUri(); m_uriEdit->setDisabled(false); m_uriEdit->setFocus(); } }); connect(m_uriEdit, &QLineEdit::textChanged, this ,&ConnectivityPage::checkUri); connect(m_connectResource, &KyConnectResourse::connectivityChanged, this, &ConnectivityPage::setWarning); } void ConnectivityPage::centerToScreen() { QRect desk_rect; QScreen *currentScreen = QGuiApplication::screenAt(QCursor::pos()); if (currentScreen) { desk_rect = currentScreen->geometry(); } else { desk_rect=QGuiApplication::primaryScreen()->geometry(); } int desk_x = desk_rect.width(); int desk_y = desk_rect.height(); int x = this->width(); int y = this->height(); this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); } void ConnectivityPage::setWarning(NetworkManager::Connectivity connectivity) { if (NetworkManager::Connectivity::Full == connectivity) { //网络已连接,可正常访问 Internet 。 m_icon->setPixmap(QIcon::fromTheme("ukui-dialog-success").pixmap(16,16)); m_statusText->setText(tr("The network is connected and can access the Internet normally.")); } else if (NetworkManager::Connectivity::Limited == connectivity || NetworkManager::Connectivity::Portal == connectivity) { //网络已连接,访问 Internet 受限。 m_icon->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(16,16)); m_statusText->setText(tr("The network is connected and access to the Internet is restricted.")); } else { qWarning() << "network status is " << connectivity << "should not show this page"; } } void ConnectivityPage::checkUri() { QString text = m_uriEdit->text(); //locationbar input data if (text.isEmpty()) { m_confirmBtn->setEnabled(false); m_warningLabel->setText(tr("Please enter the local area network (intranet) detection address")); m_warningLabel->show(); return; } int pos = 0; QRegularExpression rx; //url regular expression rx.setPattern("(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]"); QRegularExpressionValidator rv; rv.setRegularExpression(rx); //Test for a match between the url and the regular expression QValidator::State rvState = rv.validate(text, pos); if (rvState == QValidator::Acceptable) { m_confirmBtn->setEnabled(true); m_warningLabel->clear(); m_warningLabel->hide(); } else { m_confirmBtn->setEnabled(false); m_warningLabel->setText(tr("Format error")); m_warningLabel->show(); } } void ConnectivityPage::closeEvent(QCloseEvent *event) { Q_EMIT pageClose(); return QWidget::closeEvent(event); } kylin-nm/src/frontend/connectivity/connectivity.pri0000664000175000017500000000017515167646234021635 0ustar fengfengINCLUDEPATH += $$PWD FORMS += \ HEADERS += \ $$PWD/connectivitypage.h \ SOURCES += \ $$PWD/connectivitypage.cpp \ kylin-nm/src/frontend/networkmode/0000775000175000017500000000000015167651420016211 5ustar fengfengkylin-nm/src/frontend/networkmode/firewalldialog.cpp0000664000175000017500000001255315167651420021710 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "firewalldialog.h" #include #include #include "windowmanager/windowmanager.h" #include #include "kwindowsystem_export.h" #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" #define ICON_SIZE 16,16 FirewallDialog::FirewallDialog(QWidget *parent): KDialog(parent), m_uwin(nullptr) { initUI(); this->setWindowIcon(QIcon::fromTheme("kylin-network")); this->setFixedSize(480, 204); KX11Extras::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager); setAttribute(Qt::WA_DeleteOnClose); // centerToScreen(); connect(qApp, &QApplication::paletteChanged, this, &FirewallDialog::onPaletteChanged); m_uwin = new UkuiWindowHelper(this); m_uwin->setSkipTaskBar(true); } FirewallDialog::~FirewallDialog() { if (m_uwin) { delete m_uwin; } } void FirewallDialog::initUI() { m_iconLabel = new QLabel(this); m_contentLabel = new FixLabel(this); m_suggestLabel = new FixLabel(this); m_PublicBtn = new QPushButton(this); m_PrivateBtn = new QPushButton(this); m_dialogLayout = new QVBoxLayout(this); m_contentLabel->setFixedWidth(405); m_suggestLabel->setFixedWidth(405); QWidget *contentWidget = new QWidget(this); QGridLayout *contentLayout = new QGridLayout(contentWidget); contentLayout->setHorizontalSpacing(0); contentLayout->setContentsMargins(0, 0, 0, 0); contentLayout->addWidget(m_iconLabel, 0, 0); contentLayout->addWidget(m_contentLabel, 0, 1); contentLayout->addWidget(m_suggestLabel, 1, 1); m_iconLabel->setFixedWidth(24); QWidget *btnWidget = new QWidget(this); QHBoxLayout *btnLayout = new QHBoxLayout(btnWidget); btnLayout->setContentsMargins(0, 0, 0, 0); btnLayout->setSpacing(16); btnLayout->addStretch(); btnLayout->addWidget(m_PublicBtn); btnLayout->addWidget(m_PrivateBtn); m_dialogLayout->setContentsMargins(22, 16, 22, 24); m_dialogLayout->setSpacing(0); m_dialogLayout->addWidget(contentWidget); m_dialogLayout->addStretch(); m_dialogLayout->addWidget(btnWidget); QIcon icon = QIcon::fromTheme("dialog-info"); m_iconLabel->setPixmap(icon.pixmap(ICON_SIZE)); QFont font = m_contentLabel->font(); font.setWeight(QFont::Medium); m_contentLabel->setFont(font); //是否允许此网络上的其他设备发现这台电脑? m_contentLabel->setLabelText(tr("Allow other devices on this network to discover this computer?")); //不建议在公共网络上开启此功能 m_suggestLabel->setLabelText(tr("It is not recommended to enable this feature on public networks")); m_PublicBtn->setText(tr("Not allowed (recommended)")); m_PrivateBtn->setText(tr("Allowed")); this->closeButton(); this->mainWidget()->setLayout(m_dialogLayout); onPaletteChanged(); connect(m_PublicBtn, &QPushButton::clicked, this, &FirewallDialog::setPublicNetMode); connect(m_PrivateBtn, &QPushButton::clicked, this, &FirewallDialog::setPrivateNetMode); } void FirewallDialog::centerToScreen() { QRect desk_rect; QScreen *currentScreen = QGuiApplication::screenAt(QCursor::pos()); if (currentScreen) { desk_rect = currentScreen->geometry(); } else { desk_rect=QGuiApplication::primaryScreen()->geometry(); } int desk_x = desk_rect.width(); int desk_y = desk_rect.height(); int x = this->width(); int y = this->height(); this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); } void FirewallDialog::onPaletteChanged() { QPalette pal = qApp->palette(); QGSettings * styleGsettings = nullptr; const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { styleGsettings = new QGSettings(style_id); QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = lightPalette(this); } } this->setPalette(pal); if (styleGsettings != nullptr) { delete styleGsettings; styleGsettings = nullptr; } } bool FirewallDialog::event(QEvent *event) { if (event->type() == QEvent::Enter || event->type() == QEvent::Paint || event->type() == QEvent::MouseButtonPress) { QPalette tooltipPal = this->palette(); tooltipPal.setColor(QPalette::ToolTipBase, this->palette().toolTipBase().color()); tooltipPal.setColor(QPalette::ToolTipText, this->palette().toolTipText().color()); QToolTip::setPalette(tooltipPal); } return QWidget::event(event); } kylin-nm/src/frontend/networkmode/networkmodeconfig.cpp0000664000175000017500000002713415167651420022450 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "networkmodeconfig.h" #include "firewalldialog.h" #include "utils.h" #include #define LOG_FLAG "[NetworkMode]" bool checkLiveMode() { QFile file("/proc/cmdline"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug()<<"Can't open the file /proc/cmdline!"; file.close(); file.remove(); return false; } QString result_info = file.readAll(); file.close(); file.remove(); int index = result_info.indexOf("security"); if (index >= 0) { QString str = result_info.mid(index); if (str.contains("live")) { return true; } } return false; } NetworkModeConfig *NetworkModeConfig::m_netModeInstance = nullptr; NetworkModeConfig *NetworkModeConfig::getInstance() { if (m_netModeInstance == NULL) { m_netModeInstance = new NetworkModeConfig(); } return m_netModeInstance; } NetworkModeConfig::NetworkModeConfig(QObject *parent) : QObject(parent) { m_dbusInterface = new QDBusInterface("com.ksc.defender", "/firewall", "com.ksc.defender.firewall", QDBusConnection::systemBus()); if(!m_dbusInterface->isValid()) { qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } } int NetworkModeConfig::getNetworkModeConfig(QString uuid) { if (uuid.isEmpty()) { qWarning()<< /*LOG_FLAG <<*/ "uuid is empty, so can not get network mode config"; return NO_CONFIG; } if(m_dbusInterface == nullptr || !m_dbusInterface->isValid()) { qWarning () << "com.ksc.defender dbus is invalid"; return DBUS_INVAILD; } QDBusReply reply = m_dbusInterface->call("get_networkModeConfig", uuid); if (reply.isValid()) { return reply.value(); } else { qWarning() << "call get_networkModeConfig failed" << reply.error().message(); } return NO_CONFIG; } void NetworkModeConfig::setNetworkModeConfig(QString uuid, QString cardName, QString ssid, int mode) { if(m_dbusInterface == nullptr || !m_dbusInterface->isValid()) { qWarning () << "com.ksc.defender dbus is invalid"; return; } QDBusReply reply = m_dbusInterface->call("set_networkModeConfig", uuid, cardName, ssid, mode); if (reply.isValid()) { qDebug() << "set_networkModeConfig" << ssid << uuid << cardName << mode << ",result" << reply.value(); } else { qWarning() << "call set_networkModeConfig" << reply.error().message(); } } int NetworkModeConfig::breakNetworkConnect(QString uuid, QString cardName, QString ssid) { if(m_dbusInterface == nullptr || !m_dbusInterface->isValid()) { qWarning () << "com.ksc.defender dbus is invalid"; return -1; } QDBusReply reply = m_dbusInterface->call("break_networkConnect", uuid, cardName, ssid); if (reply.isValid()) { qDebug() << "break_networkConnect" << ssid << uuid << cardName << ",result" << reply.value(); return reply.value(); } else { qWarning() << "call break_networkConnect failed" << reply.error().message(); return -1; } } //安全中心-网络防火墙模式配置 NetworkMode::NetworkMode(QObject *parent) :QObject(parent) { qRegisterMetaType("NetworkManager::Device::State"); qRegisterMetaType("NetworkManager::Device::StateChangeReason"); m_activatedConnectResource = new KyActiveConnectResourse(this); connect(m_activatedConnectResource, &KyActiveConnectResourse::stateChangeReason, this, &NetworkMode::onConnectionStateChanged); } void NetworkMode::initWiredNetworkMode() { qDebug()<< LOG_FLAG << "initWiredNetworkMode"; QStringList wiredDevList; KyNetworkDeviceResourse deviceResource; deviceResource.getNetworkDeviceList(NetworkManager::Device::Type::Ethernet, wiredDevList); if (wiredDevList.isEmpty()) { return; } for (auto devName : wiredDevList) { QList activedList; m_activatedConnectResource->getActiveConnectionList(devName, NetworkManager::ConnectionSettings::Wired, activedList); if (activedList.isEmpty()) { continue; } int configType = NetworkModeConfig::getInstance()->getNetworkModeConfig(activedList.at(0)->m_connectUuid); if (configType == DBUS_INVAILD) { return; } else if (configType == NO_CONFIG) { //已连接网络无配置 默认公有配置 NetworkModeConfig::getInstance()->setNetworkModeConfig(activedList.at(0)->m_connectUuid, devName, activedList.at(0)->m_connectName, KSC_FIREWALL_PUBLIC); } else { NetworkModeConfig::getInstance()->setNetworkModeConfig(activedList.at(0)->m_connectUuid, devName, activedList.at(0)->m_connectName, configType); } } } void NetworkMode::initWirelessNetworkMode() { qDebug()<< LOG_FLAG << "initWirelessNetworkMode"; QStringList wirelessDevList; KyNetworkDeviceResourse deviceResource; deviceResource.getNetworkDeviceList(NetworkManager::Device::Type::Wifi, wirelessDevList); if (wirelessDevList.isEmpty()) { return; } for (auto devName : wirelessDevList) { KyWirelessNetItem wirelessNetItem; KyWirelessNetResource wirelessNetResource; bool ret = wirelessNetResource.getActiveWirelessNetItem(devName, wirelessNetItem); if (ret == true) { int configType = NetworkModeConfig::getInstance()->getNetworkModeConfig(wirelessNetItem.m_connectUuid); if (configType == DBUS_INVAILD) { return; } else if (configType == NO_CONFIG) { //已连接网络无配置 默认公有配置 NetworkModeConfig::getInstance()->setNetworkModeConfig(wirelessNetItem.m_connectUuid, devName, wirelessNetItem.m_connName, KSC_FIREWALL_PUBLIC); } else { NetworkModeConfig::getInstance()->setNetworkModeConfig(wirelessNetItem.m_connectUuid, devName, wirelessNetItem.m_connName, configType); } } } } void NetworkMode::setFirstConnectNetworkMode(QString uuid, QString deviceName, QString ssid) { NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PUBLIC); //默认公有配置 if (checkLiveMode()) { return; } QSettings setting(CONFIG_FILE_PATH, QSettings::IniFormat); if (!setting.value(FIRE_WALL_PERMISSION_SHOW).toBool()) { if (setting.value(AUTO_FIRE_WALL_PERMIITTED).toBool()) { NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PRIVATE); } else { NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PUBLIC); } return; } FirewallDialog *fireWallDialog = new FirewallDialog(); fireWallDialog->setUuid(uuid); fireWallDialog->setWindowTitle(ssid); connect(fireWallDialog, &FirewallDialog::setPrivateNetMode, this, [=](){ fireWallDialog->hide(); NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PRIVATE); }); connect(fireWallDialog, &FirewallDialog::setPublicNetMode, this, [=](){ fireWallDialog->hide(); NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PUBLIC); }); connect(m_activatedConnectResource, &KyActiveConnectResourse::stateChangeReason, fireWallDialog, &FirewallDialog::closeMyself); fireWallDialog->show(); fireWallDialog->centerToScreen(); } void NetworkMode::onConnectionStateChanged(QString uuid, NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason) { if (state == NetworkManager::ActiveConnection::State::Activated) { QString deviceName = ""; QString ssid = ""; int configType = NetworkModeConfig::getInstance()->getNetworkModeConfig(uuid); KyConnectResourse connectResource; //有线网络连接 if (connectResource.isWiredConnection(uuid)) { KyConnectItem *p_newItem = nullptr; p_newItem = m_activatedConnectResource->getActiveConnectionByUuid(uuid); if (nullptr == p_newItem) { //删除此网络 qDebug()<< LOG_FLAG << "delete wired connect:" << uuid << ", call break_networkConnect"; NetworkModeConfig::getInstance()->breakNetworkConnect(uuid, "", ""); return; } deviceName = p_newItem->m_ifaceName; ssid = p_newItem->m_connectName; if (configType == NO_CONFIG) { //首次连接的网络 setFirstConnectNetworkMode(uuid, deviceName, ssid); } else if (configType == KSC_FIREWALL_PUBLIC) { NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PUBLIC); } else if (configType == KSC_FIREWALL_PRIVATE) { NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PRIVATE); } } //无线网络连接 if (connectResource.isWirelessConnection(uuid)) { KyWirelessNetResource wirelessNetResource; wirelessNetResource.getSsidByUuid(uuid, ssid); wirelessNetResource.getDeviceByUuid(uuid, deviceName); if (ssid.isEmpty()) { //忘记此网络 qDebug()<< LOG_FLAG << "forgrt wireless connect:" << uuid <<", call break_networkConnect"; NetworkModeConfig::getInstance()->breakNetworkConnect(uuid, "", ""); } if (configType == NO_CONFIG) { setFirstConnectNetworkMode(uuid, deviceName, ssid); } else if (configType == KSC_FIREWALL_PUBLIC) { NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PUBLIC); } else if (configType == KSC_FIREWALL_PRIVATE) { NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PRIVATE); } } } else if (state == NetworkManager::ActiveConnection::State::Deactivated) { NetworkModeConfig::getInstance()->breakNetworkConnect(uuid, "", ""); } } kylin-nm/src/frontend/networkmode/firewalldialog.h0000664000175000017500000000412415167651420021350 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef FIREWALLDIALOG_H #define FIREWALLDIALOG_H #include #include #include #include #include #include #include #include "coninfo.h" #include "kwidget.h" #include "kdialog.h" #include "kylable.h" #include "ukuiwindowhelper/ukuiwindowhelper.h" using namespace kdk; class FirewallDialog : public KDialog { Q_OBJECT public: FirewallDialog(QWidget *parent = nullptr); ~FirewallDialog(); void setUuid(QString uuid) { m_uuid = uuid; } void centerToScreen(); private: void initUI(); QString m_uuid; QLabel * m_iconLabel = nullptr; FixLabel * m_contentLabel = nullptr; FixLabel * m_suggestLabel = nullptr; QVBoxLayout *m_dialogLayout = nullptr; QPushButton *m_PublicBtn = nullptr; QPushButton *m_PrivateBtn = nullptr; UkuiWindowHelper *m_uwin; Q_SIGNALS: void setPublicNetMode(); void setPrivateNetMode(); protected: bool event(QEvent *event) override; private Q_SLOTS: void onPaletteChanged(); public Q_SLOTS: void closeMyself(QString uuid, int status) { if (uuid == m_uuid && status == 4) { this->close(); } } }; #endif // FIREWALLDIALOG_H kylin-nm/src/frontend/networkmode/networkmodeconfig.h0000664000175000017500000000526515167651420022116 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef NETWORKMODECONFIG_H #define NETWORKMODECONFIG_H #include #include #include #include #include "kylinactiveconnectresource.h" #include "kylinconnectresource.h" #include "kywirelessnetresource.h" #define CONFIG_FILE_PATH QString(QDir::homePath() + "/.config/ukui/kylin-nm.conf") #define AUTO_FIRE_WALL_PERMIITTED "conf/autoFireWallPermitted" #define FIRE_WALL_PERMISSION_SHOW "conf/firewallPermissionShow" enum NetworkModeType { DBUS_INVAILD = -2, NO_CONFIG = -1, KSC_FIREWALL_PUBLIC = 0, KSC_FIREWALL_PRIVATE }; class NetworkModeConfig : public QObject { Q_OBJECT public: static NetworkModeConfig *getInstance(); //安全中心-获取网络模式配置 int getNetworkModeConfig(QString uuid); //安全中心-设置网络模式配置 void setNetworkModeConfig(QString uuid, QString cardName, QString ssid, int mode); //安全中心-解除连接(用于防火墙处从正在使用的网络中删除) int breakNetworkConnect(QString uuid, QString cardName, QString ssid); static NetworkModeConfig *m_netModeInstance; private: explicit NetworkModeConfig(QObject *parent = nullptr); QDBusInterface *m_dbusInterface = nullptr; }; class NetworkMode : public QObject { Q_OBJECT public: NetworkMode(QObject *parent = 0); ~NetworkMode() = default; void initWiredNetworkMode(); void initWirelessNetworkMode(); private: KyActiveConnectResourse *m_activatedConnectResource = nullptr; void setFirstConnectNetworkMode(QString uuid, QString deviceName, QString ssid); private Q_SLOTS: void onConnectionStateChanged(QString uuid, NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason); }; #endif // NETWORKMODECONFIG_H kylin-nm/src/frontend/networkmode/networkmode.pri0000664000175000017500000000025415167646234021273 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/firewalldialog.h \ $$PWD/networkmodeconfig.h SOURCES += \ $$PWD/firewalldialog.cpp \ $$PWD/networkmodeconfig.cpp kylin-nm/src/frontend/customstyle.h0000664000175000017500000000763115167646234016435 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef CUSTOMSTYLE_H #define CUSTOMSTYLE_H #include #include #include #include #include #include #include class CustomStyle : public QProxyStyle { Q_OBJECT public: explicit CustomStyle(const QString &proxyStyleName = "windows"); ~CustomStyle() = default; virtual QSize sizeFromContents(QStyle::ContentsType type, const QStyleOption *option, const QSize &contentsSize, const QWidget *widget = nullptr) const; virtual void drawControl(QStyle::ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = nullptr) const; // virtual void drawComplexControl(QStyle::ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget = nullptr) const; // virtual void drawItemPixmap(QPainter *painter, const QRect &rectangle, int alignment, const QPixmap &pixmap) const; // virtual void drawItemText(QPainter *painter, const QRect &rectangle, int alignment, const QPalette &palette, bool enabled, const QString &text, QPalette::ColorRole textRole = QPalette::NoRole) const; // virtual void drawPrimitive(QStyle::PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = nullptr) const; // virtual QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *option) const; // virtual QStyle::SubControl hitTestComplexControl(QStyle::ComplexControl control, const QStyleOptionComplex *option, const QPoint &position, const QWidget *widget = nullptr) const; // virtual QRect itemPixmapRect(const QRect &rectangle, int alignment, const QPixmap &pixmap) const; // virtual QRect itemTextRect(const QFontMetrics &metrics, const QRect &rectangle, int alignment, bool enabled, const QString &text) const; // //virtual int layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2, Qt::Orientation orientation, const QStyleOption *option, const QWidget *widget); // virtual int pixelMetric(QStyle::PixelMetric metric, const QStyleOption *option = nullptr, const QWidget *widget = nullptr) const; // virtual void polish(QWidget *widget); // virtual void polish(QApplication *application); // virtual void polish(QPalette &palette); // virtual void unpolish(QWidget *widget); // virtual void unpolish(QApplication *application); // virtual QIcon standardIcon(QStyle::StandardPixmap standardIcon, const QStyleOption *option, const QWidget *widget) const; // virtual QPalette standardPalette() const; // virtual int styleHint(QStyle::StyleHint hint, const QStyleOption *option = nullptr, const QWidget *widget = nullptr, QStyleHintReturn *returnData = nullptr) const; // virtual QRect subControlRect(QStyle::ComplexControl control, const QStyleOptionComplex *option, QStyle::SubControl subControl, const QWidget *widget = nullptr) const; // virtual QRect subElementRect(QStyle::SubElement element, const QStyleOption *option, const QWidget *widget = nullptr) const; }; #endif // CUSTOMSTYLE_H kylin-nm/src/frontend/wificonfigdialog.cpp0000664000175000017500000001553615167651420017675 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "wificonfigdialog.h" #include "ui_wificonfigdialog.h" #include "utils.h" #include #include #include #include #include #include WiFiConfigDialog::WiFiConfigDialog(QWidget *parent) : QDialog(parent), ui(new Ui::WiFiConfigDialog) { ui->setupUi(this); initTransparentState(); //初始化窗口透明度的GSetting方法 this->setWindowFlags(Qt::FramelessWindowHint); //Qt::WindowStaysOnTopHint this->setWindowTitle(tr("WLAN Authentication"));//"Wifi 认证" this->setAttribute(Qt::WA_TranslucentBackground); this->setWindowIcon(QIcon::fromTheme("kylin-network", QIcon(":/res/x/setup.png")) ); QPainterPath path; auto rect = this->rect(); rect.adjust(1, 1, -1, -1); path.addRoundedRect(rect, 6, 6); setProperty("blurRegion", QRegion(path.toFillPolygon().toPolygon())); KWindowEffects::enableBlurBehind(this->windowHandle(), true, QRegion(path.toFillPolygon().toPolygon())); ui->lbTitle->setText(tr("Input WLAN Information Please")); //输入Wi-Fi名称和密码后点击确定 ui->lbWifiId->setText(tr("WLAN ID:")); //Wi-Fi连接名称: ui->lbWifiName->setText(tr("WLAN Name:")); //Wi-Fi名称: ui->lbWifiPassord->setText(tr("Password:")); //Wi-Fi密码: ui->btnCancel->setText(tr("Cancl")); ui->btnOk->setText(tr("Ok")); ui->leWifiId->setContextMenuPolicy(Qt::NoContextMenu); ui->leWiFiName->setContextMenuPolicy(Qt::NoContextMenu); ui->leWifiPassword->setContextMenuPolicy(Qt::NoContextMenu); ui->leWifiPassword ->setEchoMode(QLineEdit::Password); ui->checkBoxPwd->setStyleSheet(checkBoxQss); ui->checkBoxPwd->setFocusPolicy(Qt::NoFocus); ui->leWifiId->setContextMenuPolicy(Qt::NoContextMenu); //禁止LineEdit的右键菜单 ui->leWiFiName->setContextMenuPolicy(Qt::NoContextMenu); ui->leWifiPassword->setContextMenuPolicy(Qt::NoContextMenu); this->setEnableOfBtn(); this->setFixedSize(474, 320); } WiFiConfigDialog::~WiFiConfigDialog() { delete ui; } void WiFiConfigDialog::paintEvent(QPaintEvent *event) { double trans = this->getTransparentData(); QStyleOption opt; opt.initFrom(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); QRect rect = this->rect(); p.setRenderHint(QPainter::Antialiasing); // 反锯齿; p.setBrush(opt.palette.color(QPalette::Base)); p.setOpacity(trans); p.setPen(Qt::NoPen); p.drawRoundedRect(rect, 6, 6); QWidget::paintEvent(event); } //创建获取窗口透明度信息的GSetting的对象 void WiFiConfigDialog::initTransparentState() { if (QGSettings::isSchemaInstalled("org.ukui.control-center.personalise")) { m_transparency_gsettings = new QGSettings("org.ukui.control-center.personalise"); } } //使用GSetting获取当前窗口应该使用的透明度 double WiFiConfigDialog::getTransparentData() { if (!m_transparency_gsettings) { return 0.7; } QStringList keys = m_transparency_gsettings->keys(); if (keys.contains("transparency")) { double tp = m_transparency_gsettings->get("transparency").toDouble(); return tp; } else { return 0.7; } } void WiFiConfigDialog::on_btnCancel_clicked() { ui->leWiFiName->setText(""); ui->leWifiPassword->setText(""); hide(); } void WiFiConfigDialog::on_btnOk_clicked() { QFuture < void > future1 = QtConcurrent::run([=](){ this->toConfigWifi(); }); hide(); } void WiFiConfigDialog::toConfigWifi() { QString connName = ui->leWiFiName->text(); QString password = ui->leWifiPassword->text(); QString strConntype = "nmcli connection modify '" + connName + "' wifi-sec.psk-flags 0"; Utils::m_system(strConntype.toUtf8().data()); QString tmpPath = "/tmp/kylin-nm-btoutput-" + QDir::home().dirName(); QString cmdStr = "export LANG='en_US.UTF-8';export LANGUAGE='en_US';nmcli device wifi connect '" + connName + "' password '" + password + "' > " + tmpPath; Utils::m_system(cmdStr.toUtf8().data()); QFile file(tmpPath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug()<<"Can't open the file /tmp/kylin-nm-btoutput in function toConfigWifi !"; } QString line = file.readLine(); file.close(); qDebug()<<"connect_wifi_result: "<< line; if (line.indexOf("successfully") != -1) { QString strConntype = "nmcli connection modify '" + connName + "' wifi-sec.psk-flags 2"; system(strConntype.toUtf8().data()); } else { QString cmd = "export LANG='en_US.UTF-8';export LANGUAGE='en_US';nmcli connection delete '" + ui->leWifiId->text() + "'"; int status = system(cmd.toUtf8().data()); qDebug()<<"executed cmd="< #include #endif enum IconActiveType { NOT_CONNECTED = 0, LAN_CONNECTED, LAN_CONNECTED_INTRANET, WLAN_CONNECTED, WLAN_CONNECTED_INTRANET, LAN_CONNECTED_LIMITED, WLAN_CONNECTED_LIMITED, ACTIVATING, }; const QByteArray TRANSPARENCY_GSETTINGS = "org.ukui.control-center.personalise"; class LanPage; class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QString display, QWidget *parent = nullptr); void showMainwindow(); void hideMainwindow(); void setWiredDefaultDevice(QString deviceName); void setWirelessDefaultDevice(QString deviceName); //for dbus void getWirelessList(QString devName, QList &list); void getWiredList(QString devName, QList &list); //开启热点 void activeWirelessAp(const QString apName, const QString apPassword, const QString wirelessBand, const QString apDevice); //断开热点 void deactiveWirelessAp(const QString apName, const QString uuid); //获取热点 void getStoredApInfo(QStringList &list); void getApInfoBySsid(QString devName, QString ssid, QStringList &list); //获取热点path void getApConnectionPath(QString &path, QString uuid); //获取热点ActivePath void getActiveConnectionPath(QString &path, QString uuid); //有线连接断开 void activateWired(const QString& devName, const QString& connUuid); void deactivateWired(const QString& devName, const QString& connUuid, bool concise = false); void deleteWiredConnect(int type, const QString& connUuid); void setWiredDeviceAutoconnect(const QString& devName, bool state); //无线连接断开 void activateWireless(const QString& devName, const QString& ssid); void deactivateWireless(const QString& devName, const QString& ssid); void deleteWireleeConnect(int type, const QString& connUuid); //无线总开关 void setWirelessSwitchEnable(bool enable); void setWiredEnableStatus(bool enable); void setWiredDeviceEnable(const QString& devName, bool enable); //唤起属性页 根据网卡类型 参数2 为ssid/uuid void showPropertyWidget(QString devName, QString ssid); //唤起新建有线连接界面 void showCreateWiredConnectWidget(const QString devName); //唤起加入其他无线网络界面 void showAddOtherWlanWidget(QString devName); void getWirelessDeviceCap(QMap &map); void passwordConnect(QString devName, QString ssid, QString type, QString psk, bool autoConnect); void rescan(); bool getWirelessSwitchBtnState(); bool getWiredEnabledState(); int getDeviceConnectivity(const QString deviceName); bool getCableStateByDevice(const QString &deviceName); Q_SIGNALS: //设备插拔 void deviceStatusChanged(); void wirelessDeviceStatusChanged(); //设备名称变化 void deviceNameChanged(QString oldName, QString newName, int type); void wirelessSwitchBtnChanged(bool state); void wiredEnabledChanged(bool state); void wiredMainSwitchBtnChanged(bool state); //有线无线列表更新(有线增删、无线增加减少) void lanAdd(QString devName, QStringList info); void lanRemove(QString dbusPath); void lanUpdate(QString devName, QStringList info); void wlanAdd(QString devName, QStringList info); void wlanRemove(QString devName,QString ssid); void wlanactiveConnectionStateChanged(QString devName, QString ssid, QString uuid, int status); void lanActiveConnectionStateChanged(QString devName, QString uuid, int status); void activateFailed(QString errorMessage); void deactivateFailed(QString errorMessage); //热点断开 void hotspotDeactivated(QString devName, QString ssid); void hotspotActivated(QString devName, QString ssid, QString uuid, QString activePath, QString settingPath); void hotspotDeactivating(QString devName, QString ssid); void hotspotActivating(QString devName, QString ssid); //信号强度变化 void signalStrengthChange(QString devName, QString ssid, int strength); //安全性变化 void secuTypeChange(QString devName, QString ssid, QString secuType); void mainWindowVisibleChanged(const bool &visible); //列表排序 void timeToUpdate(); void deviceConnectivityChanged(QString devName, int connectivity); public Q_SLOTS: protected: void keyPressEvent(QKeyEvent *event); void paintEvent(QPaintEvent *event); bool eventFilter(QObject *watched, QEvent *event); private: void firstlyStart(); //一级启动 void secondaryStart(); //二级启动 bool m_loadFinished = false; //是否二级启动已执行完 QTimer * m_secondaryStartTimer = nullptr; //执行二级启动的倒计时 void initPlatform(); void initWindowProperties(); void initTransparency(); void paintWithTrans(); void initPanelGSettings(); void initUI(); void initDbusConnnect(); void registerTrayIcon(); void initTrayIcon(); void resetTrayIconTool(); void initWindowTheme(); void resetWindowTheme(); void showByWaylandHelper(); void slideWindowByPanelPosition(); void setCentralWidgetType(IconActiveType iconStatus); void assembleTrayIconTooltip(QMap &map, QString &tip); void setThemePalette(); void initNetCtrl(); void netCtrlDiscon(QMap lanMap,QMap wlanMap); void kylinAgentInit(); double m_transparency=1.0; //透明度 QGSettings * m_transGsettings; //透明度配置文件 int currentIconIndex=0; QList loadIcons; QTimer *iconTimer = nullptr; //主窗口的主要构成控件 QTabWidget * m_centralWidget = nullptr; QHBoxLayout * m_tabBarLayout = nullptr; QLabel * m_lanLabel = nullptr; QLabel * m_wlanLabel = nullptr; LanPage * m_lanWidget = nullptr; WlanPage * m_wlanWidget = nullptr; ConnectivityPage* m_connectivityPage = nullptr; //监听主题的Gsettings QGSettings * m_styleGsettings = nullptr; //获取任务栏位置和大小 QGSettings *m_panelGSettings = nullptr; int m_panelPosition; int m_panelSize; int m_panelType; int m_settingsIslandPosition; int m_topbarSize; //获取和重置窗口位置 void resetWindowPosition(); //QDBusInterface * m_positionInterface = nullptr; //托盘图标,托盘图标右键菜单 QSystemTrayIcon * m_trayIcon = nullptr; QMenu * m_trayIconMenu = nullptr; QAction * m_showMainwindowAction = nullptr; QAction * m_showSettingsAction = nullptr; QAction * m_showConnectivityPageAction = nullptr; bool m_lanIsLoading = false; bool m_wlanIsLoading = false; bool m_isShowInCenter = false; IconActiveType iconStatus = IconActiveType::NOT_CONNECTED; QMap m_createPagePtrMap; NetworkMode *m_networkMode; QString m_display; uint m_intervalTime = 100; uint m_registerCount = 0; inline void updateTrayiconMenuStyle() { QPalette pal = this->palette(); //托盘watcher异常时的规避方案 bug#214664 if (m_trayIconMenu != nullptr) { pal.setColor(QPalette::Base, pal.color(QPalette::Base)); //处理Wayland环境setPalette(pal)不生效问题 pal.setColor(QPalette::Text, pal.color(QPalette::Text)); m_trayIconMenu->setPalette(pal); } } //网络界面配置 QMap getModuleHideStatus(); void initDisplayConfig(); bool m_lan_display_flag = true; bool m_wlan_display_flag = true; public Q_SLOTS: void onShowMainWindow(int type); void updateNetCtrl(QString modName,QVariantMap value); void keyRingInit(); void keyRingClear(); private Q_SLOTS: void onTransChanged(); void onTrayIconActivated(QSystemTrayIcon::ActivationReason reason); void onShowMainwindowActionTriggled(); void onShowSettingsActionTriggled(); void onThemeChanged(const QString &key); void onRefreshTrayIcon(); void onSetTrayIconLoading(); void onConnectStatusToChangeTrayIcon(int state); void onLanConnectStatusToChangeTrayIcon(int state); void onWlanConnectStatusToChangeTrayIcon(int state); void onConnectivityChanged(NetworkManager::Connectivity connectivity); void onConnectivityCheckSpareUriChanged(); void onTimeUpdateTrayIcon(); void onTabletModeChanged(bool mode); void onRefreshTrayIconTooltip(); void onPrimaryScreenChanged(); void onShowKylinNMSlot(QString display, int type); //唤起属性页 根据网卡类型 参数2 为ssid/uuid void onShowPropertyWidgetSlot(QString display, QString devName, QString ssid); //唤起新建有线连接界面 void onShowCreateWiredConnectWidgetSlot(QString display, QString devName); //唤起加入其他无线网络界面 void onShowAddOtherWlanWidgetSlot(QString display, QString devName); void showControlCenter(); }; #endif // MAINWINDOW_H kylin-nm/src/frontend/wificonfigdialog.ui0000664000175000017500000000542615167651420017525 0ustar fengfeng WiFiConfigDialog 0 0 474 320 Dialog 60 30 290 30 60 140 90 30 60 200 90 30 190 140 240 30 190 200 241 30 220 260 96 36 330 260 96 36 60 80 121 30 190 80 240 30 400 211 18 9 kylin-nm/src/frontend/tools/0000775000175000017500000000000015167651420015013 5ustar fengfengkylin-nm/src/frontend/tools/divider.cpp0000664000175000017500000000406015167651420017145 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "divider.h" #include #include #include "../netdetails/coninfo.h" #include "themepalette.h" #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" Divider::Divider(bool useDarkPal, QWidget * parent) :m_useDarkPal(useDarkPal), QFrame(parent) { this->setFixedHeight(1); connect(qApp, &QApplication::paletteChanged, this ,&Divider::onPaletteChanged); onPaletteChanged(); } void Divider::onPaletteChanged() { QPalette pal = qApp->palette(); QGSettings * styleGsettings = nullptr; const QByteArray styleId(THEME_SCHAME); if (QGSettings::isSchemaInstalled(styleId) && m_useDarkPal) { styleGsettings = new QGSettings(styleId, QByteArray(), this); QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = themePalette(true, this); } } m_color = pal.color(QPalette::BrightText); m_color.setAlphaF(0.08); } void Divider::paintEvent(QPaintEvent * e) { QPainter p(this); p.save(); p.setBrush(m_color); p.setPen(Qt::transparent); p.drawRoundedRect(this->rect(), 6, 6); p.restore(); return QFrame::paintEvent(e); } kylin-nm/src/frontend/tools/radioitembutton.cpp0000664000175000017500000002303515167651420020733 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "radioitembutton.h" #include #include #include #include #include #include "themepalette.h" #define FLASH_SPEED 100 #define TIMEOUT_TIMER 90*1000 #define BUTTON_SIZE 36,36 #define ICON_SIZE 16,16 #define BACKGROUND_COLOR QColor(0,0,0,0) #define FOREGROUND_COLOR_NORMAL_INACTIVE_LIGHT QColor(230,230,230,255) #define FOREGROUND_COLOR_NORMAL_INACTIVE_DARK QColor(55,55,55,255) #define FOREGROUND_COLOR_PRESS_INACTIVE_LIGHT QColor(217,217,217,255) #define FOREGROUND_COLOR_PRESS_INACTIVE_DARK QColor(70,70,70,255) #define FOREGROUND_COLOR_NORMAL_ACTIVE QColor(55,144,250,255) #define FOREGROUND_COLOR_PRESS_ACTIVE QColor(36,109,212,255) #define COLOR_BRIGHT_TEXT this->palette().brightText().color() #define COLOR_HIGH_LIGHT this->palette().highlight().color() #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" QColor mixColor(const QColor &c1, const QColor &c2, qreal bias); RadioItemButton::RadioItemButton(QWidget *parent) : QPushButton(parent) { this->setAutoFillBackground(false); m_iconLabel = new QLabel(this); this->setFixedSize(BUTTON_SIZE); m_iconLabel->setFixedSize(BUTTON_SIZE); m_iconLabel->setAlignment(Qt::AlignCenter); m_iconLabel->setProperty("useIconHighlightEffect", 0x2); setActive(false); const QByteArray id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(id)) { m_styleGSettings = new QGSettings(id); connect(m_styleGSettings, &QGSettings::changed, this, [=](QString key){ if ("themeColor" == key) { onPaletteChanged(); } }); } onPaletteChanged(); //JXJ_TODO loading动画 connect(this, &RadioItemButton::requestStartLoading, this, &RadioItemButton::onLoadingStarted); connect(this , &RadioItemButton::requestStopLoading, this, &RadioItemButton::onLoadingStopped); connect(qApp, &QApplication::paletteChanged, this, &RadioItemButton::onPaletteChanged); } RadioItemButton::~RadioItemButton() { if (m_styleGSettings != nullptr) { delete m_styleGSettings; m_styleGSettings = nullptr; } } void RadioItemButton::startLoading() { Q_EMIT this->requestStartLoading(); } void RadioItemButton::stopLoading() { Q_EMIT this->requestStopLoading(); } //设置图标 void RadioItemButton::setButtonIcon(const QIcon &icon) { if (icon.isNull()) { return; } m_pixmap = icon.pixmap(ICON_SIZE); // m_iconLabel->setPixmap(m_pixmap); } //显示默认图标 void RadioItemButton::setDefaultPixmap() { m_iconLabel->setPixmap(m_pixmap); } //根据连接状态更改图标颜色 void RadioItemButton::setActive(const bool &isActive) { m_isActivated = isActive; refreshButtonIcon(); } void RadioItemButton::onLoadingStarted() { #define ANIMATION_SPEED 0.5*1000 #define START_ROTATION 0 #define END_ROTATION 360 #define ANIMATION_LOOP -1 //无限旋转 if (!m_iconLabel) { qWarning() << "Start loading failed, iconLabel is null pointer!" << Q_FUNC_INFO << __LINE__; } if (!m_animation) { m_animation = new QVariantAnimation(m_iconLabel); } m_animation->setDuration(ANIMATION_SPEED); m_animation->setStartValue(START_ROTATION); m_animation->setEndValue(END_ROTATION); m_animation->setLoopCount(ANIMATION_LOOP); connect(m_animation, &QVariantAnimation::valueChanged, this, &RadioItemButton::onAnimationValueChanged); m_animation->start(); } void RadioItemButton::onLoadingStopped() { if (!m_animation) { qWarning() << "Stop loading failed, m_animation is null pointer!" << Q_FUNC_INFO << __LINE__; return; } else { m_iconLabel->setPixmap(m_pixmap); m_animation->stop(); Q_EMIT this->animationStoped(); } } void RadioItemButton::onPaletteChanged() { QPalette pal = qApp->palette(); QGSettings * styleGsettings = nullptr; const QByteArray styleId(THEME_SCHAME); if (QGSettings::isSchemaInstalled(styleId)) { styleGsettings = new QGSettings(styleId, QByteArray(), this); QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = themePalette(true, this); } } pal.setColor(QPalette::Base, pal.color(QPalette::Base)); //解决Wayland环境this->setPalette(pal)不生效问题 pal.setColor(QPalette::BrightText, pal.color(QPalette::BrightText)); pal.setColor(QPalette::Highlight, pal.color(QPalette::Highlight)); this->setPalette(pal); refreshButtonIcon(); } void RadioItemButton::onAnimationValueChanged(const QVariant& value) { if (!m_iconLabel) { return; } QTransform t; t.rotate(value.toReal()); m_iconLabel->setPixmap(QIcon::fromTheme("ukui-loading-0-symbolic").pixmap(ICON_SIZE).transformed(t)); } void RadioItemButton::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); pal.setColor(QPalette::Base, BACKGROUND_COLOR); pal.setColor(QPalette::Text, m_backgroundColor); QPainterPath cPath; cPath.addRect(0, 0, this->width(), this->height()); cPath.addEllipse(0, 0, this->width(), this->width()); QPainterPath innerPath; innerPath.addEllipse(0, 0, this->width(), this->width()); QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); painter.setBrush(pal.color(QPalette::Base)); painter.drawPath(cPath); painter.fillPath(innerPath, pal.color(QPalette::Text)); } void RadioItemButton::mousePressEvent(QMouseEvent *event) { if (m_isActivated) { // m_backgroundColor = qApp->palette().highlight().color(); m_backgroundColor = mixColor(COLOR_HIGH_LIGHT, COLOR_BRIGHT_TEXT, 0.2); } else { m_backgroundColor = COLOR_BRIGHT_TEXT; m_backgroundColor.setAlphaF(0.21); } this->update(); return QPushButton::mousePressEvent(event); } void RadioItemButton::mouseReleaseEvent(QMouseEvent *event) { if (m_isActivated) { m_backgroundColor = COLOR_HIGH_LIGHT; } else { m_backgroundColor = COLOR_BRIGHT_TEXT; m_backgroundColor.setAlphaF(0.12); } this->update(); return QPushButton::mouseReleaseEvent(event); } void RadioItemButton::enterEvent(QEnterEvent *event) { if (m_isActivated) { m_backgroundColor = COLOR_HIGH_LIGHT; } else { m_backgroundColor = COLOR_BRIGHT_TEXT; m_backgroundColor.setAlphaF(0.15); } this->update(); return QPushButton::enterEvent(event); } void RadioItemButton::leaveEvent(QEvent *event) { if (m_isActivated) { m_backgroundColor = COLOR_HIGH_LIGHT; } else { m_backgroundColor = COLOR_BRIGHT_TEXT; m_backgroundColor.setAlphaF(0.12); } this->update(); return QPushButton::leaveEvent(event); } void RadioItemButton::refreshButtonIcon() { if (m_isActivated) { m_backgroundColor = COLOR_HIGH_LIGHT; m_iconLabel->setPixmap(loadSvg(m_pixmap, PixmapColor::WHITE)); } else { m_backgroundColor = COLOR_BRIGHT_TEXT; m_backgroundColor.setAlphaF(0.12); if (this->palette().base().color().red() > MIDDLE_COLOR) { m_iconLabel->setPixmap(m_pixmap); } else { m_iconLabel->setPixmap(loadSvg(m_pixmap, PixmapColor::WHITE)); } } return; } const QPixmap RadioItemButton::loadSvg(const QPixmap &source, const PixmapColor &cgColor) { QImage img = source.toImage(); for (int x = 0; x < img.width(); x++) { for (int y = 0; y < img.height(); y++) { auto color = img.pixelColor(x, y); if (color.alpha() > 0) { switch (cgColor) { case PixmapColor::WHITE: color.setRed(255); color.setGreen(255); color.setBlue(255); img.setPixelColor(x, y, color); break; case PixmapColor::BLACK: color.setRed(0); color.setGreen(0); color.setBlue(0); img.setPixelColor(x, y, color); break; case PixmapColor::GRAY: color.setRed(152); color.setGreen(163); color.setBlue(164); img.setPixelColor(x, y, color); break; case PixmapColor::BLUE: color.setRed(61); color.setGreen(107); color.setBlue(229); img.setPixelColor(x, y, color); break; default: return source; break; } } } } return QPixmap::fromImage(img); } kylin-nm/src/frontend/tools/divider.h0000664000175000017500000000231515167651420016613 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef DIVIDER_H #define DIVIDER_H #include class Divider : public QFrame { public: Divider(bool useDarkPal = false, QWidget * parent = nullptr); ~Divider() = default; private: bool m_useDarkPal; QColor m_color; private Q_SLOTS: void onPaletteChanged(); protected: void paintEvent(QPaintEvent * e); }; #endif // DIVIDER_H kylin-nm/src/frontend/tools/infobutton.h0000664000175000017500000000265015167651420017356 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef INFOBUTTON_H #define INFOBUTTON_H #include #include class InfoButton : public QPushButton { Q_OBJECT public: explicit InfoButton(QWidget * parent = nullptr); ~InfoButton() = default; protected: void enterEvent(QEvent *event); void leaveEvent(QEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); private: void initUI(); private: QColor m_backgroundColor; QColor m_foregroundColor; private Q_SLOTS: void onPaletteChanged(); }; #endif // INFOBUTTON_H kylin-nm/src/frontend/tools/infobutton.cpp0000664000175000017500000001013015167651420017701 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "infobutton.h" #include #include #include #include #include #include "themepalette.h" #define BUTTON_SIZE 36,36 #define ICON_SIZE 16,16 #define BACKGROUND_COLOR QColor(0,0,0,0) #define FOREGROUND_COLOR_NORMAL this->palette().text().color() #define FOREGROUND_COLOR_BRIGHTTEXT this->palette().brightText().color() #define FOREGROUND_COLOR_HIGHLIGHT this->palette().highlight().color() #define OUTER_PATH 8,10,16,16 #define INNER_PATH 9,11,14,14 #define TEXT_POS 14,7,16,16,0 #define BUTTON_SIZE 36,36 #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" QColor mixColor(const QColor &c1, const QColor &c2, qreal bias); InfoButton::InfoButton(QWidget *parent) : QPushButton(parent) { this->setFixedSize(BUTTON_SIZE); initUI(); connect(qApp, &QApplication::paletteChanged, this, &InfoButton::onPaletteChanged); const QByteArray id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(id)) { QGSettings * styleGsettings = new QGSettings(id, QByteArray(), this); connect(styleGsettings, &QGSettings::changed, this, [=](QString key){ if ("themeColor" == key) { onPaletteChanged(); } }); } onPaletteChanged(); } void InfoButton::initUI() { this->setFixedSize(BUTTON_SIZE); this->setIcon(QIcon::fromTheme("preferences-system-details-symbolic")); this->setProperty("useButtonPalette", true); this->setFlat(true); m_backgroundColor = BACKGROUND_COLOR; m_foregroundColor = FOREGROUND_COLOR_NORMAL; } void InfoButton::onPaletteChanged() { QPalette pal = qApp->palette(); QGSettings * styleGsettings = nullptr; const QByteArray styleId(THEME_SCHAME); if (QGSettings::isSchemaInstalled(styleId)) { styleGsettings = new QGSettings(styleId, QByteArray(), this); QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = themePalette(true, this); } } pal.setColor(QPalette::Base, pal.color(QPalette::Base));//解决Wayland环境this->setPalette(pal)不生效问题 pal.setColor(QPalette::Text, pal.color(QPalette::Text)); pal.setColor(QPalette::Highlight, pal.color(QPalette::Highlight)); pal.setColor(QPalette::BrightText, pal.color(QPalette::BrightText)); this->setPalette(pal); m_foregroundColor = FOREGROUND_COLOR_NORMAL; this->repaint(); } void InfoButton::enterEvent(QEvent *event) { // m_foregroundColor = FOREGROUND_COLOR_HOVER; m_foregroundColor = FOREGROUND_COLOR_HIGHLIGHT; this->update(); } void InfoButton::leaveEvent(QEvent *event) { m_foregroundColor = FOREGROUND_COLOR_NORMAL; this->update(); } void InfoButton::mousePressEvent(QMouseEvent *event) { // m_foregroundColor = FOREGROUND_COLOR_PRESS; m_foregroundColor = mixColor(FOREGROUND_COLOR_HIGHLIGHT, FOREGROUND_COLOR_BRIGHTTEXT, 0.2); this->update(); return QPushButton::mousePressEvent(event); } void InfoButton::mouseReleaseEvent(QMouseEvent *event) { // m_foregroundColor = FOREGROUND_COLOR_HOVER; m_foregroundColor = mixColor(FOREGROUND_COLOR_HIGHLIGHT, FOREGROUND_COLOR_BRIGHTTEXT, 0.2); this->update(); return QPushButton::mouseReleaseEvent(event); } kylin-nm/src/frontend/tools/listitemedit.cpp0000664000175000017500000000367015167651420020225 0ustar fengfeng /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "listitemedit.h" ListItemEdit::ListItemEdit(const QRegularExpression &rx, QObject *parent) : m_regExp(rx), QStyledItemDelegate(parent) { } QWidget *ListItemEdit::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { QLineEdit *editor = new QLineEdit(parent); editor->setValidator(new QRegularExpressionValidator(m_regExp, parent)); return editor; } void ListItemEdit::setEditorData(QWidget *editor, const QModelIndex &index) const { QLineEdit *lineEdit = static_cast (editor); QString text = index.model()->data(index, Qt::EditRole).toString(); lineEdit->setText(text); } void ListItemEdit::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QLineEdit *lineEdit = static_cast (editor); QString text = lineEdit->text(); model->setData(index, text, Qt::EditRole); } void ListItemEdit::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { editor->setGeometry(option.rect); } kylin-nm/src/frontend/tools/listitemedit.h0000664000175000017500000000352115167651420017665 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef LISTITEMEDIT_H #define LISTITEMEDIT_H #include #include #include class ListItemEdit: public QStyledItemDelegate { Q_OBJECT public: ListItemEdit(const QRegularExpression &rx, QObject *parent = nullptr); ~ListItemEdit() = default; //创建一个控件 virtual QWidget *createEditor (QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; //将数据设置到控件中 virtual void setEditorData (QWidget *editor, const QModelIndex &index) const; //将控件中的数据更新到对应的model中 virtual void setModelData (QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; //更新控件位置 void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override; private: QRegularExpression m_regExp; }; #endif // LISTITEMEDIT_H kylin-nm/src/frontend/tools/kylable.h0000664000175000017500000000342015167651420016606 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLABLE_H #define KYLABLE_H #include #include #include "themepalette.h" class FixLabel : public QLabel { Q_OBJECT public: explicit FixLabel(QWidget *parent = 0); public: void setLabelText(QString text); QString getText(); private Q_SLOTS: void changedLabelSlot(); private: QString mStr; protected: bool event(QEvent *event) override; }; class KyLable : public QLabel { Q_OBJECT public: explicit KyLable(QWidget *parent = nullptr); ~KyLable() = default; protected: void paintEvent(QPaintEvent *event); void enterEvent(QEvent *event); void leaveEvent(QEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); private: QColor m_foregroundColor; void setPressColor(); void setHoverColor(); void setNormalColor(); private Q_SLOTS: void onPaletteChanged(); }; #endif // KYLABLE_H kylin-nm/src/frontend/tools/kylable.cpp0000664000175000017500000001075115167651420017146 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylable.h" #include #include #include #include #include #include #define FOREGROUND_COLOR_NORMAL this->palette().text().color() static inline qreal mixQreal(qreal a, qreal b, qreal bias) { return a + (b - a) * bias; } QColor mixColor(const QColor &c1, const QColor &c2, qreal bias) { if (bias <= 0.0) { return c1; } if (bias >= 1.0) { return c2; } if (qIsNaN(bias)) { return c1; } qreal r = mixQreal(c1.redF(), c2.redF(), bias); qreal g = mixQreal(c1.greenF(), c2.greenF(), bias); qreal b = mixQreal(c1.blueF(), c2.blueF(), bias); qreal a = mixQreal(c1.alphaF(), c2.alphaF(), bias); return QColor::fromRgbF(r, g, b, a); } FixLabel::FixLabel(QWidget *parent) : QLabel(parent) { const QByteArray id("org.ukui.style"); QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); if(QGSettings::isSchemaInstalled(id)){ connect(fontSetting, &QGSettings::changed,[=](QString key) { if ("systemFont" == key || "systemFontSize" ==key) { changedLabelSlot(); } }); } } void FixLabel::setLabelText(QString text) { mStr = text; changedLabelSlot(); } QString FixLabel::getText(){ return mStr; } void FixLabel::changedLabelSlot() { QFontMetrics fontMetrics(this->font()); int fontSize = fontMetrics.horizontalAdvance(mStr); if (fontSize > this->width()) { setText(fontMetrics.elidedText(mStr, Qt::ElideRight, this->width())); setToolTip(mStr); } else { setText(mStr); setToolTip(""); } } bool FixLabel::event(QEvent *event) { if (event->type() == QEvent::Paint) { QPalette tooltipPal = this->palette(); tooltipPal.setColor(QPalette::ToolTipBase, this->palette().toolTipBase().color()); tooltipPal.setColor(QPalette::ToolTipText, this->palette().toolTipText().color()); QToolTip::setPalette(tooltipPal); } return QWidget::event(event); } KyLable::KyLable(QWidget *parent) : QLabel(parent) { connect(qApp, &QApplication::paletteChanged, this, &KyLable::onPaletteChanged); onPaletteChanged(); } void KyLable::onPaletteChanged() { m_foregroundColor = FOREGROUND_COLOR_NORMAL; this->repaint(); } void KyLable::setPressColor() { QColor hightlight = this->palette().color(QPalette::Active,QPalette::Highlight); QColor mix = this->palette().color(QPalette::Active,QPalette::BrightText); m_foregroundColor = mixColor(hightlight, mix, 0.2); } void KyLable::setHoverColor() { // QColor hightlight = this->palette().color(QPalette::Active,QPalette::Highlight); // QColor mix = this->palette().color(QPalette::Active,QPalette::BrightText); // m_foregroundColor = mixColor(hightlight, mix, 0.2); m_foregroundColor = this->palette().color(QPalette::Active,QPalette::Highlight); } void KyLable::setNormalColor() { m_foregroundColor = FOREGROUND_COLOR_NORMAL; } void KyLable::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); pal.setColor(QPalette::WindowText, m_foregroundColor); this->setPalette(pal); return QLabel::paintEvent(event); } void KyLable::enterEvent(QEvent *event) { setHoverColor(); this->update(); } void KyLable::leaveEvent(QEvent *event) { setNormalColor(); this->update(); } void KyLable::mousePressEvent(QMouseEvent *event) { setPressColor(); this->update(); return QLabel::mousePressEvent(event); } void KyLable::mouseReleaseEvent(QMouseEvent *event) { setHoverColor(); this->update(); return QLabel::mouseReleaseEvent(event); } kylin-nm/src/frontend/tools/switchbutton.h0000664000175000017500000000327115167651420017724 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include #include #include class SwitchButton : public QWidget { Q_OBJECT public: explicit SwitchButton(QWidget *parent = nullptr); void setSwitchStatus(bool check); bool getSwitchStatus(); void setEnabled(bool enabled); bool getEnabled(); private: QColor m_colorActive; QColor m_colorInactive; int m_bIsOn = 1; QTimer *m_cTimer; float m_fWidth; float m_fHeight; float m_fCurrentValue; void paintEvent(QPaintEvent *event); void mousePressEvent(QMouseEvent *event); void enterEvent(QEnterEvent *event); void leaveEvent(QEvent *event); bool m_enabled = true; Q_SIGNALS: void clicked(); void switchStatusChanged(); private Q_SLOTS: void startAnimation(); }; #endif // SWITCHBUTTON_H kylin-nm/src/frontend/tools/radioitembutton.h0000664000175000017500000000440215167651420020375 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef NETBUTTON_H #define NETBUTTON_H #include #include #include #include #include #include #define MIDDLE_COLOR 178 class RadioItemButton : public QPushButton { Q_OBJECT public: RadioItemButton(QWidget * parent = nullptr); ~RadioItemButton(); void startLoading(); void stopLoading(); void setButtonIcon(const QIcon &icon); void setDefaultPixmap(); void setActive(const bool &isActive); enum PixmapColor { WHITE = 0, BLACK, GRAY, BLUE, }; const QPixmap loadSvg(const QPixmap &source, const PixmapColor &color); Q_SIGNALS: void requestStartLoading(); void requestStopLoading(); void animationStoped(); protected: void paintEvent(QPaintEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void enterEvent(QEnterEvent *event); void leaveEvent(QEvent *event); private: bool m_isActivated = false; QLabel * m_iconLabel = nullptr; QColor m_backgroundColor; QVariantAnimation * m_animation = nullptr; QPixmap m_pixmap; QGSettings *m_styleGSettings = nullptr; void refreshButtonIcon(); private Q_SLOTS: void onLoadingStarted(); void onLoadingStopped(); void onPaletteChanged(); void onAnimationValueChanged(const QVariant& value); }; #endif // NETBUTTON_H kylin-nm/src/frontend/tools/tools.pri0000664000175000017500000000067315167646234016704 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/divider.h \ $$PWD/infobutton.h \ $$PWD/listitemedit.h \ $$PWD/loadingdiv.h \ $$PWD/radioitembutton.h \ $$PWD/switchbutton.h \ $$PWD/kylable.h \ $$PWD/themepalette.h SOURCES += \ $$PWD/divider.cpp \ $$PWD/infobutton.cpp \ $$PWD/listitemedit.cpp \ $$PWD/loadingdiv.cpp \ $$PWD/radioitembutton.cpp \ $$PWD/switchbutton.cpp \ $$PWD/kylable.cpp kylin-nm/src/frontend/tools/switchbutton.cpp0000664000175000017500000001111615167651420020254 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see setInterval(5); if(m_bIsOn == 1) { m_fCurrentValue = m_fWidth - 16 - 4; } else { m_fCurrentValue = 4; } connect(m_cTimer, SIGNAL(timeout()), this, SLOT(startAnimation())); } void SwitchButton::setSwitchStatus(bool check) { if (!m_enabled) return; if(check == true) { m_bIsOn = 1; } else { m_bIsOn = 0; } Q_EMIT this->switchStatusChanged(); m_cTimer->start(); //开始播放动画 } bool SwitchButton::getSwitchStatus() { if (m_bIsOn == 1) return true; return false; } void SwitchButton::setEnabled(bool enabled) { m_enabled = enabled; update(); return; } bool SwitchButton::getEnabled() { return m_enabled; } /* 播放按钮开启关闭动画 */ void SwitchButton::startAnimation() { //滑动按钮动作播放 int pos = 4; int size = m_fWidth - 16; if(m_bIsOn) { m_fCurrentValue ++; //往右滑动 if(m_fCurrentValue >= size - pos) { //到达边界停下来 m_fCurrentValue = size - pos; m_cTimer->stop(); } } else { m_fCurrentValue --; if(m_fCurrentValue <= pos) { //到达最小值,停止继续前进 m_fCurrentValue = pos; m_cTimer->stop(); } } update(); } /* 按钮按下处理 */ void SwitchButton::mousePressEvent(QMouseEvent *event) { Q_UNUSED(event); if (m_enabled) { m_bIsOn = !m_bIsOn; } Q_EMIT clicked(); return QWidget::mousePressEvent(event); } void SwitchButton::enterEvent(QEnterEvent *event) { if (m_enabled && m_bIsOn) { m_colorActive = COLOR_ACTIVE_HOVER; } else if (m_enabled && !m_bIsOn) { m_colorInactive = COLOR_INACTIVE_HOVER; } this->update(); return QWidget::enterEvent(event); } void SwitchButton::leaveEvent(QEvent *event) { if (m_enabled && m_bIsOn) { m_colorActive = COLOR_ACTIVE; } else if (m_enabled && !m_bIsOn) { m_colorInactive = COLOR_INACTIVE; } this->update(); return QWidget::leaveEvent(event); } /* 绘制滑动按钮主体 */ void SwitchButton::paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); painter.setRenderHint(QPainter::SmoothPixmapTransform); painter.setRenderHint(QPainter::Antialiasing); //抗锯齿效果 painter.setPen(Qt::NoPen); if(m_bIsOn && m_enabled) { painter.save(); painter.setBrush(m_colorActive); QRectF active_rect = QRectF(0,0,m_fWidth,m_fHeight); painter.drawRoundedRect(active_rect, 0.5 * m_fHeight, 0.5 * m_fHeight); //画开启状态 } else { painter.save(); painter.setBrush(m_colorInactive); QRectF inactive_rect = QRectF(0 ,0,m_fWidth,m_fHeight); painter.drawRoundedRect(inactive_rect, 0.5 * m_fHeight, 0.5 * m_fHeight); //画关闭状态 } painter.restore(); painter.save(); if (!m_enabled) { painter.setBrush(COLOR_UNABLE); // QRectF enableRect = QRectF(30, 10, 8, 4); // painter.drawRoundedRect(enableRect, 2, 2); } else { painter.setBrush(Qt::white); } painter.drawEllipse(m_fCurrentValue,4, 16, 16); painter.restore(); } kylin-nm/src/frontend/tools/loadingdiv.h0000664000175000017500000000235715167646234017322 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include #include #include #include #include class LoadingDiv : public QWidget { Q_OBJECT public: explicit LoadingDiv(QWidget *parent = nullptr); Q_SIGNALS: void toStopLoading(); public Q_SLOTS: void switchAnimStep(); void startLoading(); void stopLoading(); private: QLabel *loadingGif = nullptr; QTimer *switchTimer = nullptr; int currentPage; int countCurrentTime; }; #endif // LOADINGDIV_H kylin-nm/src/frontend/tools/loadingdiv.cpp0000664000175000017500000000450315167646234017650 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #define FRAMESPEED 60 //帧与帧之间的间隔时间(ms) #define ALLTIME 40*1000 //等待动画持续总时间 //加载动画控件'loadingGif' LoadingDiv::LoadingDiv(QWidget *parent) : QWidget(parent) { this->resize(480, 538); this->loadingGif = new QLabel(this); this->loadingGif->resize(96, 96); this->loadingGif->move(this->width()/2 - 96/2 + 41/2 - 40, this->height()/2 + 20); this->loadingGif->show(); this->switchTimer = new QTimer(this); //QTimer对象,控制等待动画播放 connect(switchTimer, SIGNAL(timeout()), this, SLOT(switchAnimStep())); this->raise(); this->hide(); } //加载动画控件'loadingGif' void LoadingDiv::switchAnimStep() { //另外一种加载方法 QString qpmQss = ":/res/s/conning-b/"; qpmQss.append(QString::number(this->currentPage)); qpmQss.append(".png"); loadingGif->setPixmap(QPixmap(qpmQss)); loadingGif->setProperty("useIconHighlightEffect", true); loadingGif->setProperty("iconHighlightEffectMode", true); this->currentPage --; if (this->currentPage < 1) { this->currentPage = 12; //循环播放 } this->countCurrentTime += FRAMESPEED; if (this->countCurrentTime >= ALLTIME) { Q_EMIT this->toStopLoading(); //发出信号停止主界面和托盘区的等待动画 } } //开始播放动画 void LoadingDiv::startLoading() { this->currentPage = 12; this->countCurrentTime = 0; this->switchTimer->start(FRAMESPEED); this->show(); } //结束播放动画 void LoadingDiv::stopLoading() { this->switchTimer->stop(); this->hide(); } kylin-nm/src/frontend/tools/themepalette.h0000664000175000017500000002273615167646234017666 0ustar fengfeng#ifndef THEMEPALETTE_H #define THEMEPALETTE_H #include #include static QPalette themePalette(bool isDark, QWidget *widget) { QPalette palette = qApp->palette(); //ukui-light palette UKUI3.1 QColor windowText_at(38, 38, 38), windowText_iat(0, 0, 0, 255 * 0.55), windowText_dis(0, 0, 0, 255 * 0.3), button_at(230, 230, 230), button_iat(230, 230, 230), button_dis(233, 233, 233), light_at(255, 255, 255), light_iat(255, 255, 255), light_dis(242, 242, 242), midlight_at(218, 218, 218), midlight_iat(218, 218, 218), midlight_dis(230, 230, 230), dark_at(77, 77, 77), dark_iat(77, 77, 77), dark_dis(64, 64, 64), mid_at(115, 115, 115), mid_iat(115, 115, 115), mid_dis(102, 102, 102), text_at(38, 38, 38), text_iat(38, 38, 38), text_dis(0, 0, 0, 255 * 0.3), brightText_at(0, 0, 0), brightText_iat(0, 0, 0), brightText_dis(0, 0, 0), buttonText_at(38, 38, 38), buttonText_iat(38, 38, 38), buttonText_dis(179, 179, 179), base_at(255, 255, 255), base_iat(245, 245, 245), base_dis(237, 237, 237), window_at(245, 245, 245), window_iat(237, 237, 237), window_dis(230, 230, 230), shadow_at(0, 0, 0, 255 * 0.16), shadow_iat(0, 0, 0, 255 * 0.16), shadow_dis(0, 0, 0, 255 * 0.21), highLight_at(55, 144, 250), highLight_iat(55, 144, 250), highLight_dis(233, 233, 233), highLightText_at(255, 255, 255), highLightText_iat(255, 255, 255), highLightText_dis(179, 179, 179), link_at(55, 144, 250), link_iat(55, 144, 250), link_dis(55, 144, 250), linkVisited_at(114, 46, 209), linkVisited_iat(114, 46, 209), linkVisited_dis(114, 46, 209), alternateBase_at(245, 245, 245), alternateBase_iat(245, 245, 245), alternateBase_dis(245, 245, 245), noRale_at(240, 240, 240), noRole_iat(240, 240, 240), noRole_dis(217, 217, 217), toolTipBase_at(255, 255, 255), toolTipBase_iat(255, 255, 255), toolTipBase_dis(255, 255, 255), toolTipText_at(38, 38, 38), toolTipText_iat(38, 38, 38), toolTipText_dis(38, 38, 38), placeholderText_at(0, 0, 0, 255 * 0.35), placeholderText_iat(0, 0, 0, 255 * 0.35), placeholderText_dis(0, 0, 0, 255 * 0.3); //ukui-dark if (isDark) { windowText_at.setRgb(217, 217, 217); windowText_iat.setRgb(255, 255, 255, 255 * 0.55); windowText_dis.setRgb(255, 255, 255, 255 * 0.3); button_at.setRgb(55, 55, 59); button_iat.setRgb(55, 55, 59); button_dis.setRgb(46, 46, 46); light_at.setRgb(255, 255, 255); light_iat.setRgb(255, 255, 255); light_dis.setRgb(242, 242, 242); midlight_at.setRgb(95, 95, 98); midlight_iat.setRgb(95, 95, 98); midlight_dis.setRgb(79, 79, 82); dark_at.setRgb(38, 38, 38); dark_iat.setRgb(38, 38, 38); dark_dis.setRgb(26, 26, 26); mid_at.setRgb(115, 115, 115); mid_iat.setRgb(115, 115, 115); mid_dis.setRgb(102, 102, 102); text_at.setRgb(217, 217, 217); text_iat.setRgb(217, 217, 217); text_dis.setRgb(255, 255, 255, 255 * 0.3); brightText_at.setRgb(255, 255, 255); brightText_iat.setRgb(255, 255, 255); brightText_dis.setRgb(255, 255, 255); buttonText_at.setRgb(217, 217, 217); buttonText_iat.setRgb(217, 217, 217); buttonText_dis.setRgb(76, 76, 79); base_at.setRgb(29, 29, 29); base_iat.setRgb(28, 28, 28); base_dis.setRgb(36, 36, 36); window_at.setRgb(35, 36, 38); window_iat.setRgb(26, 26, 26); window_dis.setRgb(18, 18, 18); shadow_at.setRgb(0, 0, 0, 255 * 0.16); shadow_iat.setRgb(0, 0, 0, 255 * 0.16); shadow_dis.setRgb(0, 0, 0, 255 * 0.21); highLight_at.setRgb(55, 144, 250); highLight_iat.setRgb(55, 144, 250); highLight_dis.setRgb(46, 46, 46); highLightText_at.setRgb(255, 255, 255); highLightText_iat.setRgb(255, 255, 255); highLightText_dis.setRgb(77, 77, 77); link_at.setRgb(55, 144, 250); link_iat.setRgb(55, 144, 250); link_dis.setRgb(55, 144, 250); linkVisited_at.setRgb(114, 46, 209); linkVisited_iat.setRgb(114, 46, 209); linkVisited_dis.setRgb(114, 46, 209); alternateBase_at.setRgb(38, 38, 38); alternateBase_iat.setRgb(38, 38, 38); alternateBase_dis.setRgb(38, 38, 38); noRale_at.setRgb(51, 51, 51); noRole_iat.setRgb(51, 51, 51); noRole_dis.setRgb(60, 60, 60); toolTipBase_at.setRgb(38, 38, 38); toolTipBase_iat.setRgb(38, 38, 38); toolTipBase_dis.setRgb(38, 38, 38); toolTipText_at.setRgb(217, 217, 217); toolTipText_iat.setRgb(217, 217, 217); toolTipText_dis.setRgb(217, 217, 217); placeholderText_at.setRgb(255, 255, 255, 255 * 0.35); placeholderText_iat.setRgb(255, 255, 255, 255 * 0.35); placeholderText_dis.setRgb(255, 255, 255, 255 * 0.3); } palette.setColor(QPalette::Active, QPalette::WindowText, windowText_at); palette.setColor(QPalette::Inactive, QPalette::WindowText, windowText_iat); palette.setColor(QPalette::Disabled, QPalette::WindowText, windowText_dis); palette.setColor(QPalette::Active, QPalette::Button, button_at); palette.setColor(QPalette::Inactive, QPalette::Button, button_iat); palette.setColor(QPalette::Disabled, QPalette::Button, button_dis); palette.setColor(QPalette::Active, QPalette::Light, light_at); palette.setColor(QPalette::Inactive, QPalette::Light, light_iat); palette.setColor(QPalette::Disabled, QPalette::Light, light_dis); palette.setColor(QPalette::Active, QPalette::Midlight, midlight_at); palette.setColor(QPalette::Inactive, QPalette::Midlight, midlight_iat); palette.setColor(QPalette::Disabled, QPalette::Midlight, midlight_dis); palette.setColor(QPalette::Active, QPalette::Dark, dark_at); palette.setColor(QPalette::Inactive, QPalette::Dark, dark_iat); palette.setColor(QPalette::Disabled, QPalette::Dark, dark_dis); palette.setColor(QPalette::Active, QPalette::Mid, mid_at); palette.setColor(QPalette::Inactive, QPalette::Mid, mid_iat); palette.setColor(QPalette::Disabled, QPalette::Mid, mid_dis); palette.setColor(QPalette::Active, QPalette::Text, text_at); palette.setColor(QPalette::Inactive, QPalette::Text, text_iat); palette.setColor(QPalette::Disabled, QPalette::Text, text_dis); palette.setColor(QPalette::Active, QPalette::BrightText, brightText_at); palette.setColor(QPalette::Inactive, QPalette::BrightText, brightText_iat); palette.setColor(QPalette::Disabled, QPalette::BrightText, brightText_dis); palette.setColor(QPalette::Active, QPalette::ButtonText, buttonText_at); palette.setColor(QPalette::Inactive, QPalette::ButtonText, buttonText_iat); palette.setColor(QPalette::Disabled, QPalette::ButtonText, buttonText_dis); palette.setColor(QPalette::Active, QPalette::Base, base_at); palette.setColor(QPalette::Inactive, QPalette::Base, base_iat); palette.setColor(QPalette::Disabled, QPalette::Base, base_dis); palette.setColor(QPalette::Active, QPalette::Window, window_at); palette.setColor(QPalette::Inactive, QPalette::Window, window_iat); palette.setColor(QPalette::Disabled, QPalette::Window, window_dis); palette.setColor(QPalette::Active, QPalette::Shadow, shadow_at); palette.setColor(QPalette::Inactive, QPalette::Shadow, shadow_iat); palette.setColor(QPalette::Disabled, QPalette::Shadow, shadow_dis); palette.setColor(QPalette::Active, QPalette::HighlightedText, highLightText_at); palette.setColor(QPalette::Inactive, QPalette::HighlightedText, highLightText_iat); palette.setColor(QPalette::Disabled, QPalette::HighlightedText, highLightText_dis); palette.setColor(QPalette::Active, QPalette::AlternateBase, alternateBase_at); palette.setColor(QPalette::Inactive, QPalette::AlternateBase, alternateBase_iat); palette.setColor(QPalette::Disabled, QPalette::AlternateBase, alternateBase_dis); palette.setColor(QPalette::Active, QPalette::NoRole, noRale_at); palette.setColor(QPalette::Inactive, QPalette::NoRole, noRole_iat); palette.setColor(QPalette::Disabled, QPalette::NoRole, noRole_dis); palette.setColor(QPalette::Active, QPalette::ToolTipBase, toolTipBase_at); palette.setColor(QPalette::Inactive, QPalette::ToolTipBase, toolTipBase_iat); palette.setColor(QPalette::Disabled, QPalette::ToolTipBase, toolTipBase_dis); palette.setColor(QPalette::Active, QPalette::ToolTipText, toolTipText_at); palette.setColor(QPalette::Inactive, QPalette::ToolTipText, toolTipText_iat); palette.setColor(QPalette::Disabled, QPalette::ToolTipText, toolTipText_dis); #if (QT_VERSION >= QT_VERSION_CHECK(5,12,0)) palette.setColor(QPalette::Active, QPalette::PlaceholderText, placeholderText_at); palette.setColor(QPalette::Inactive, QPalette::PlaceholderText, placeholderText_iat); palette.setColor(QPalette::Disabled, QPalette::PlaceholderText, placeholderText_dis); #endif return palette; } #endif // THEMEPALETTE_H kylin-nm/src/frontend/list-items/0000775000175000017500000000000015167651420015745 5ustar fengfengkylin-nm/src/frontend/list-items/list-items.pri0000664000175000017500000000050415167646234020561 0ustar fengfengINCLUDEPATH += $$PWD FORMS += \ $$PWD/oneconnform.ui \ $$PWD/onelancform.ui HEADERS += \ $$PWD/lanlistitem.h \ $$PWD/listitem.h \ $$PWD/wlanlistitem.h \ $$PWD/wlanmoreitem.h SOURCES += \ $$PWD/lanlistitem.cpp \ $$PWD/listitem.cpp \ $$PWD/wlanlistitem.cpp \ $$PWD/wlanmoreitem.cpp kylin-nm/src/frontend/list-items/wlanmoreitem.cpp0000664000175000017500000000264515167651420021163 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "wlanmoreitem.h" WlanMoreItem::WlanMoreItem(QWidget *parent) : ListItem(parent) { setObjectName(WMI_OB_NAME); m_netButton->setVisible(false); // m_infoButton->setVisible(false); m_nameLabel->setLabelMaximumWidth(326); m_nameLabel->setLabelText(tr("Add Others...")); } WlanMoreItem::~WlanMoreItem() { } void WlanMoreItem::onNetButtonClicked() { Q_EMIT hiddenWlanClicked(); } void WlanMoreItem::onNetButtonReleased() { } void WlanMoreItem::onRightButtonClicked() { // Todo } void WlanMoreItem::onMenuTriggered(QAction *action) { } kylin-nm/src/frontend/list-items/wlanlistitem.cpp0000664000175000017500000006232015167651420021170 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "wlanlistitem.h" #include #include #include #define EMPTY_SSID "EMPTY_SSID" #define LOG_FLAG "[WlanListItem]" #define WAIT_US 10*1000 #define NAMELABLE_MAX_WIDTH_HOVER 166 #define NAMELABLE_MAX_WIDTH_ACTIVATED 142 #define NAMELABLE_MAX_WIDTH_DEACTIVATED 276 const QString ENTERPRICE_TYPE = "802.1X"; const QString WPA1_AND_WPA2 = "WPA"; const QString WPA3 = "WPA3"; WlanListItem::WlanListItem(KyWirelessNetItem &wirelessNetItem, QString device, bool isApMode, bool isShowWifi6Plus, QWidget *parent) : WlanListItem(wirelessNetItem, device, parent) { m_isApMode = isApMode; m_isShowWifi6Plus = isShowWifi6Plus; refreshIcon(false); // 额外刷新一次图标,因为WlanListItem执行时,m_isApMode尚未赋值 } WlanListItem::WlanListItem(KyWirelessNetItem &wirelessNetItem, QString device, bool isShowWifi6Plus, QWidget *parent) : ListItem(parent) { m_wlanDevice = device; m_wirelessNetItem = wirelessNetItem; m_isShowWifi6Plus = isShowWifi6Plus; qDebug()<<"[WlanPage] wlan list item is created." << m_wirelessNetItem.m_NetSsid; initWlanUI(); setExpanded(false); // connect(this->m_infoButton, &InfoButton::clicked, this, &WlanListItem::onInfoButtonClicked); connect(m_hoverButton, &FixPushButton::clicked, this, &WlanListItem::onNetButtonClicked); m_wirelessConnectOperation = new KyWirelessConnectOperation(this); m_deviceResource = new KyNetworkDeviceResourse(this); } WlanListItem::WlanListItem(QWidget *parent) : ListItem(parent) { m_wirelessNetItem.m_NetSsid = EMPTY_SSID; qDebug()<<"[WlanPage] wlan list item is created." << m_wirelessNetItem.m_NetSsid; m_netButton->setButtonIcon(QIcon::fromTheme("network-wireless-offline-symbolic")); m_netButton->setActive(false); const QString name = tr("Not connected"); setExpanded(false); this->setName(name); // this->m_netButton->setEnabled(false); // this->m_infoButton->hide(); } WlanListItem::~WlanListItem() { qDebug()<<"[WlanPage] wlan list item is deleted." << m_wirelessNetItem.m_NetSsid; } QString WlanListItem::getSsid() { return m_wirelessNetItem.m_NetSsid; } QString WlanListItem::getUuid() { return m_wirelessNetItem.m_connectUuid; } QString WlanListItem::getPath() { return m_wirelessNetItem.m_connDbusPath; } void WlanListItem::setSignalStrength(const int &signal) { m_wirelessNetItem.m_signalStrength = signal; if (Activated == m_connectState) { refreshIcon(true); } else if (Deactivated == m_connectState) { refreshIcon(false); } } int WlanListItem::getSignalStrength() { return m_wirelessNetItem.m_signalStrength; } bool WlanListItem::isConfigured() { return m_wirelessNetItem.m_isConfigured; } void WlanListItem::setWlanState(const int &state) { // m_wirelessNetItem.m_state = state; //ZJP_TODO 后端接口待补全 refreshIcon(false); } void WlanListItem::setExpanded(const bool &expanded) { if (!m_pwdFrame || !m_autoConnectFrame) { this->setFixedHeight(NORMAL_HEIGHT); return; } m_pwdFrame->setVisible(expanded); m_autoConnectFrame->setVisible(expanded); if (expanded) { m_pwdLineEdit->setFocus(); setFixedHeight(EXPANDED_HEIGHT); m_hoverButton->hide(); m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_DEACTIVATED); } else { setFixedHeight(NORMAL_HEIGHT); } Q_EMIT this->itemHeightChanged(expanded, m_wirelessNetItem.m_NetSsid); } void WlanListItem::resizeEvent(QResizeEvent *event) { this->blockSignals(true); if (this->height() == EXPANDED_HEIGHT) { this->setExpanded(true); } else { this->setExpanded(false); } this->blockSignals(false); return ListItem::resizeEvent(event); } void WlanListItem::onRightButtonClicked() { qDebug()<< LOG_FLAG <<"onRightButtonClicked"; if (!m_menu) { return; } m_menu->clear(); if (Activated == m_connectState || Activating == m_connectState) { m_menu->addAction(new QAction(tr("Disconnect"), this)); } else if (Deactivated == m_connectState) { m_menu->addAction(new QAction(tr("Connect"), this)); qDebug() << "add connect action"; } else { return; } if (m_wirelessNetItem.m_isConfigured) { m_menu->addAction(new QAction(tr("Property"), this)); m_menu->addAction(new QAction(tr("Forget"), this)); } m_menu->popup(cursor().pos()); } void WlanListItem::enterEvent(QEvent *event) { //qDebug()<< LOG_FLAG <<"enterEvent" << m_wirelessNetItem.m_NetSsid; if (m_pwdFrame != nullptr && !m_pwdFrame->isVisible()) { if (Deactivated != m_connectState) { m_hoverButton->setProperty("useButtonPalette", true); m_hoverButton->setProperty("isImportant", false); m_hoverButton->setButtonText(tr("Disconnect")); } else { m_hoverButton->setProperty("isImportant", true); m_hoverButton->setProperty("useButtonPalette", false); m_hoverButton->setButtonText(tr("Connect")); } m_hoverButton->show(); m_lbLoadUp->hide(); m_lbLoadDown->hide(); m_lbLoadDownImg->hide(); m_lbLoadUpImg->hide(); } m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_HOVER); return ListItem::enterEvent(event); } void WlanListItem::leaveEvent(QEvent *event) { //qDebug()<< LOG_FLAG <<"leaveEvent"<< m_wirelessNetItem.m_NetSsid; m_hoverButton->hide(); if (m_connectState == Activated || m_connectState == Deactivating) { m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_ACTIVATED); m_lbLoadUp->show(); m_lbLoadDown->show(); m_lbLoadDownImg->show(); m_lbLoadUpImg->show(); } else { m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_DEACTIVATED); } return ListItem::leaveEvent(event); } bool WlanListItem::eventFilter(QObject *watched, QEvent *event) { if (watched == m_autoConnectCheckBox) { if (event->type() == QEvent::FocusIn) { m_pwdLineEdit->setFocus(); } } return QFrame::eventFilter(watched, event); } void WlanListItem::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { if (m_pwdFrame && m_pwdFrame->isVisible() && m_pwdLineEdit->text().length() >= PWD_LENGTH_LIMIT) { onConnectButtonClicked(); } } return QFrame::keyPressEvent(event); } void WlanListItem::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); if (m_pwdLineEdit != nullptr) { pal.setColor(QPalette::Base, pal.color(QPalette::Base)); pal.setColor(QPalette::Text, pal.color(QPalette::Text)); m_pwdLineEdit->setPalette(pal); } return QWidget::paintEvent(event); } void WlanListItem::initWlanUI() { m_hasPwd = (m_wirelessNetItem.m_secuType.isEmpty() || m_wirelessNetItem.m_secuType == "") ? false : true; //设置显示的Wlan名称 // this->setName((m_wirelessNetItem.m_connName != "") ? m_wirelessNetItem.m_connName : m_wirelessNetItem.m_NetSsid); this->setName(m_wirelessNetItem.m_NetSsid); //刷新左侧按钮图标 refreshIcon(false); this->onPaletteChanged(); #define PWD_AREA_HEIGHT 36 #define CONNECT_BUTTON_WIDTH 96 #define FRAME_CONTENT_MARGINS 56,0,16,4 #define FRAME_SPACING 8 #define LINEEDIT_WIDTH 220 #define PWD_CONTENT_MARGINS 8,0,34,0 #define SHOW_PWD_BUTTON_SIZE 24,24 #define PWD_LAYOUT_MARGINS 8,0,8,0 //密码输入区域的UI m_pwdFrame = new QFrame(this); m_pwdFrameLyt = new QHBoxLayout(m_pwdFrame); m_pwdFrameLyt->setContentsMargins(FRAME_CONTENT_MARGINS); m_pwdFrameLyt->setSpacing(FRAME_SPACING); m_pwdFrame->setLayout(m_pwdFrameLyt); m_pwdLineEdit = new KPasswordEdit(m_pwdFrame); m_pwdLineEdit->setFixedWidth(LINEEDIT_WIDTH); m_pwdLineEdit->setProperty("needTranslucent", true); m_pwdLineEdit->setClearButtonEnabled(false); //禁用ClearBtn按钮 m_pwdLineEdit->setAttribute(Qt::WA_InputMethodEnabled, true); //打开输入法 // m_pwdLineEdit->setAttribute(Qt::WA_InputMethodEnabled, false); // m_pwdLineEdit->setContextMenuPolicy(Qt::NoContextMenu); QRegularExpression rx("^[A-Za-z0-9`~!@#$%^&*()_-+=<>,.\\\/ ]+$"); QRegularExpressionValidator *latitude = new QRegularExpressionValidator(rx, this); m_pwdLineEdit->setValidator(latitude); m_pwdLineEdit->setMaxLength(PWD_LENGTH_MAX); m_pwdLineEdit->installEventFilter(this); connect(m_pwdLineEdit, &QLineEdit::textChanged, this, &WlanListItem::onPwdEditorTextChanged); m_pwdLineEdit->setFixedHeight(PWD_AREA_HEIGHT); m_pwdFrameLyt->addWidget(m_pwdLineEdit); m_connectButton = new FixPushButton(m_pwdFrame); m_connectButton->setProperty("isImportant", true); m_connectButton->setProperty("needTranslucent", true); m_connectButton->setFixedSize(CONNECT_BUTTON_WIDTH, PWD_AREA_HEIGHT); m_connectButton->setButtonText(tr("Connect")); m_connectButton->setEnabled(false); connect(m_connectButton, &QPushButton::clicked, this, &WlanListItem::onConnectButtonClicked); m_pwdFrameLyt->addWidget(m_connectButton); m_pwdFrameLyt->addStretch(); //自动连接选择区域UI m_autoConnectFrame = new QFrame(this); m_autoConnectFrameLyt = new QHBoxLayout(m_autoConnectFrame); m_autoConnectFrameLyt->setContentsMargins(FRAME_CONTENT_MARGINS); m_autoConnectFrameLyt->setSpacing(FRAME_SPACING); m_autoConnectFrame->setLayout(m_autoConnectFrameLyt); m_autoConnectCheckBox = new QCheckBox(m_autoConnectFrame); m_autoConnectCheckBox->installEventFilter(this); m_autoConnectCheckBox->setChecked(true); m_autoConnectCheckBox->setFixedSize(SHOW_PWD_BUTTON_SIZE); m_autoConnectFrameLyt->addWidget(m_autoConnectCheckBox); m_autoConnectLabel = new QLabel(m_autoConnectFrame); m_autoConnectLabel->setText(tr("Auto Connect")); m_autoConnectFrameLyt->addWidget(m_autoConnectLabel); m_autoConnectFrameLyt->addStretch(); m_mainLayout->addWidget(m_pwdFrame); m_mainLayout->addWidget(m_autoConnectFrame); m_mainLayout->addStretch(); m_pwdFrame->hide(); m_autoConnectFrame->hide(); this->m_freq->show(); this->setFrequency(); } QString getIcon(bool isEncrypted, int signalStrength, int category) { QString iconNameFirst,iconNameLast; if (category == 0){ iconNameFirst = "network-wireless-signal-"; } else if (category == 1) { iconNameFirst = "ukui-wifi6-"; } else if (category == 3) { iconNameFirst = "ukui-wifi7-"; } else { iconNameFirst = "ukui-wifi6+-"; } if (!isEncrypted) { if (signalStrength > EXCELLENT_SIGNAL){ if (category == 0) { iconNameLast = "excellent-symbolic"; } else { iconNameLast = "full-symbolic"; } } else if (signalStrength > GOOD_SIGNAL) { if (category == 0) { iconNameLast = "good-symbolic"; } else { iconNameLast = "high-symbolic"; } } else if (signalStrength > OK_SIGNAL) { if (category == 0) { iconNameLast = "ok-symbolic"; } else { iconNameLast = "medium-symbolic"; } } else if (signalStrength > LOW_SIGNAL) { if (category == 0) { iconNameLast = "weak-symbolic"; } else { iconNameLast = "low-symbolic"; } } else { iconNameLast = "none-symbolic"; } } else { if (signalStrength > EXCELLENT_SIGNAL){ if (category == 0) { iconNameLast = "excellent-secure-symbolic"; } else { iconNameLast = "full-pwd-symbolic"; } } else if (signalStrength > GOOD_SIGNAL) { if (category == 0) { iconNameLast = "good-secure-symbolic"; } else { iconNameLast = "high-pwd-symbolic"; } } else if (signalStrength > OK_SIGNAL) { if (category == 0) { iconNameLast = "ok-secure-symbolic"; } else { iconNameLast = "medium-pwd-symbolic"; } } else if (signalStrength > LOW_SIGNAL) { if (category == 0) { iconNameLast = "weak-secure-symbolic"; } else { iconNameLast = "low-pwd-symbolic"; } } else { if (category == 0) { iconNameLast = "none-secure-symbolic"; } else { iconNameLast = "none-pwd-symbolic"; } } } return iconNameFirst + iconNameLast; } void WlanListItem::refreshIcon(bool isActivated) { if (m_isApMode) { m_netButton->setButtonIcon(QIcon::fromTheme("network-wireless-hotspot-symbolic", QIcon(":/res/w/wifi-full.png"))); m_netButton->setActive(isActivated); return; } int category = 0; int signalStrength = 0; QString uni = ""; QString secuType = ""; category = m_wirelessNetItem.getCategory(m_wirelessNetItem.m_uni); signalStrength = m_wirelessNetItem.m_signalStrength; if (isActivated) { if (m_deviceResource->getActiveConnectionInfo(m_wlanDevice, signalStrength, uni, secuType)) { category = m_wirelessNetItem.getCategory(uni); m_hasPwd = (secuType.isEmpty() || secuType == "") ? false : true; } } if (!m_isShowWifi6Plus && category == 2) { category = 1; } QString iconPath = getIcon(m_hasPwd, signalStrength, category); m_netButton->setButtonIcon(QIcon::fromTheme(iconPath)); m_netButton->setActive(isActivated); this->setFrequency(); qDebug() << "refreshIcon" << m_wirelessNetItem.m_NetSsid << "isActivated" << isActivated << "path" << iconPath; } void WlanListItem::onInfoButtonClicked() { //ZJP_TODO 呼出无线详情页 // if(netDetail != nullptr){ // netDetail->activateWindow(); // return; // } qDebug() << LOG_FLAG << "Net active or not:"<< m_connectState; qDebug() << LOG_FLAG << "On wlan info button clicked! ssid = " << m_wirelessNetItem.m_NetSsid << "; name = " << m_wirelessNetItem.m_connName << "." <show(); #endif Q_EMIT this->detailShow(m_wlanDevice, m_wirelessNetItem.m_NetSsid); } void WlanListItem::onNetButtonClicked() { qDebug() << LOG_FLAG << "onNetButtonClicked"; if (m_wirelessNetItem.m_NetSsid == EMPTY_SSID) { return; } if (Deactivated != m_connectState) { m_wirelessConnectOperation->deActivateWirelessConnection(m_wlanDevice, m_wirelessNetItem.m_connectUuid); return; } //获取有配置网络的安全类型 KyKeyMgmt type = m_wirelessConnectOperation->getConnectKeyMgmt(m_wirelessNetItem.m_connectUuid); KySecuType kySecuType = KYLIN_NM::NONE; if (type == WpaNone || type == Unknown) { kySecuType = KYLIN_NM::NONE; } else if (type == WpaPsk) { kySecuType = KYLIN_NM::WPA_AND_WPA2_PERSONAL; } else if (type == SAE) { kySecuType = KYLIN_NM::WPA3_PERSONAL; } else if (type == WpaEap) { kySecuType = KYLIN_NM::WPA_AND_WPA2_ENTERPRISE; } else { qDebug() << "KeyMgmt not support now " << type; } //有配置或者无密码的wifi直接连接 if (m_wirelessNetItem.m_isConfigured && updatewirelessItemConnectInfo(m_wirelessNetItem)) { if (m_wirelessNetItem.m_kySecuType == kySecuType || (m_wirelessNetItem.m_kySecuType == WPA_AND_WPA3 && (kySecuType == WPA_AND_WPA2_PERSONAL || kySecuType == WPA3_PERSONAL))) { //安全类型不变直接连接 m_wirelessConnectOperation->activeWirelessConnect(m_wlanDevice, m_wirelessNetItem.m_connectUuid); qDebug()<<"[WlanListItem] Has configuration, will be activated. ssid = " << m_wirelessNetItem.m_NetSsid << Q_FUNC_INFO << __LINE__; return; } else { //安全类型改变则删除连接 m_wirelessConnectOperation->deleteWirelessConnect(m_wirelessNetItem.m_connectUuid); } } qWarning() << Q_FUNC_INFO << __LINE__ << m_wirelessNetItem.m_secuType; if (!this->m_connectButton->isVisible() && !m_wirelessNetItem.m_secuType.isEmpty()) { if (m_wirelessNetItem.m_secuType.contains("802.1x", Qt::CaseInsensitive)) { if (isEnterpriseWlanDialogShow && enterpriseWlanDialog != nullptr) { qDebug() << LOG_FLAG <<"EnterpriseWlanDialog is show do not show again!"; enterpriseWlanDialog->show(); enterpriseWlanDialog->activateWindow(); return; } else { enterpriseWlanDialog = new EnterpriseWlanDialog(m_wirelessNetItem, m_wlanDevice); connect(enterpriseWlanDialog, &EnterpriseWlanDialog::enterpriseWlanDialogClose, this, &WlanListItem::onEnterpriseWlanDialogClose); enterpriseWlanDialog->show(); enterpriseWlanDialog->activateWindow(); isEnterpriseWlanDialogShow = true; } } else { this->setExpanded(true); } } else { onConnectButtonClicked(); } } void WlanListItem::onNetButtonReleased() { qDebug() << "net button released"; } void WlanListItem::updateWirelessNetSecurity(QString ssid, QString securityType) { if (ssid != m_wirelessNetItem.m_NetSsid) { return; } qDebug() << LOG_FLAG << "Security changed! ssid = " << m_wirelessNetItem.m_NetSsid << "; security = " << m_wirelessNetItem.m_secuType << "change to "<< securityType <text().length() < PWD_LENGTH_LIMIT) { m_connectButton->setEnabled(false); } else { m_connectButton->setEnabled(true); } } void WlanListItem::onConnectButtonClicked() { qDebug()<< LOG_FLAG << "onConnectButtonClicked"; if ((Activating == m_connectState || Deactivating == m_connectState)) { qDebug() << LOG_FLAG << "On wlan clicked! But there is nothing to do because it is already activating/deactivating!" << Q_FUNC_INFO << __LINE__; return; } if (m_connectButton->isVisible() && !m_connectButton->isEnabled()) { qWarning() << "Connect wlan failed because of null pointer or button state!" << Q_FUNC_INFO << __LINE__; return; } KyWirelessConnectSetting settings; settings.m_connectName = m_wirelessNetItem.m_NetSsid; settings.m_ssid = m_wirelessNetItem.m_NetSsid; settings.isAutoConnect = m_autoConnectCheckBox->isChecked(); settings.m_psk = m_pwdLineEdit->text(); if (m_wirelessNetItem.m_secuType.isEmpty() || m_wirelessNetItem.m_secuType == "") { settings.m_type = WpaNone; } else if (m_wirelessNetItem.m_secuType.contains("WPA1") || m_wirelessNetItem.m_secuType.contains("WPA2")) { settings.m_type = WpaPsk; } else if (m_wirelessNetItem.m_secuType.contains("WPA3")) { settings.m_type = SAE; } qDebug() << "[WlanListItem] On button connect clicked, will connect wlan. ssid = " << m_wirelessNetItem.m_NetSsid << Q_FUNC_INFO <<__LINE__; m_wirelessConnectOperation->addAndActiveWirelessConnect(m_wlanDevice, settings, false); setExpanded(false); } ConnectState WlanListItem::getConnectionState() { return m_connectState; } void WlanListItem::updateConnectState(ConnectState state) { m_connectState = state; if (Activated == state) { m_netButton->stopLoading(); m_netButton->setActive(true); m_hoverButton->setProperty("useButtonPalette", true); m_hoverButton->setProperty("isImportant", false); m_hoverButton->setButtonText(tr("Disconnect")); if (m_hoverButton->isHidden()) { m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_ACTIVATED); } } else if(Deactivated == state) { m_netButton->stopLoading(); m_netButton->setActive(false); m_hoverButton->setProperty("isImportant", true); m_hoverButton->setProperty("useButtonPalette", false); m_hoverButton->setButtonText(tr("Connect")); if (m_hoverButton->isHidden()) { m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_DEACTIVATED); } } else { qDebug() << "[WlanListItem] start loading connect state:" << state; m_netButton->startLoading(); m_hoverButton->setProperty("useButtonPalette", true); m_hoverButton->setProperty("isImportant", false); m_hoverButton->setButtonText(tr("Disconnect")); } this->setFrequency(); } void WlanListItem::onMenuTriggered(QAction *action) { if (action->text() == tr("Connect")) { this->onNetButtonClicked(); } else if (action->text() == tr("Disconnect")) { m_wirelessConnectOperation->deActivateWirelessConnection(m_wlanDevice, m_wirelessNetItem.m_connectUuid); qDebug()<<"[WlanListItem] Clicked on connected wifi, it will be inactivated. ssid = " << m_wirelessNetItem.m_NetSsid << Q_FUNC_INFO << __LINE__; } else if (action->text() == tr("Forget")) { if (m_pwdLineEdit != nullptr) { m_pwdLineEdit->clear(); } m_wirelessConnectOperation->deleteWirelessConnect(m_wirelessNetItem.m_connectUuid); } else if (action->text() == tr("Property")) { onInfoButtonClicked(); } } void WlanListItem::onEnterpriseWlanDialogClose(bool isShow) { isEnterpriseWlanDialogShow = isShow; } void WlanListItem::forgetPwd() { if (!this->isConfigured()) { m_pwdLineEdit->setText(""); } } void WlanListItem::setFrequency() { bool isMix = false; uint freq,iChan; QString strMac, strSecu; if (m_connectState == Activated) { m_deviceResource->getDeviceActiveAPInfo(m_wlanDevice, strMac, freq, iChan, strSecu); } else { NetworkManager::Device::Ptr devicePtr = nullptr; KyNetworkResourceManager* networkResourceInstance = KyNetworkResourceManager::getInstance(); devicePtr = networkResourceInstance->findDeviceInterface(m_wlanDevice); if (!devicePtr.isNull()) { QString devUni = devicePtr->uni(); NetworkManager::WirelessNetwork::Ptr wirelessPtr = nullptr; wirelessPtr = networkResourceInstance->findWifiNetwork(m_wirelessNetItem.m_NetSsid, devUni); if (!wirelessPtr.isNull()) { NetworkManager::AccessPoint::List apList = wirelessPtr->accessPoints(); bool b2G = false; bool b5G = false; if (!apList.empty()) { for (int i = 0; i < apList.count(); ++i) { if (apList.at(i)->frequency() < FREQ_5GHZ) { b2G = true; } if (apList.at(i)->frequency() >= FREQ_5GHZ) { b5G = true; } if (b2G && b5G) { isMix = true; break; } } } if (!isMix) { if (b2G) { freq = 0; } else { freq = FREQ_5GHZ; } } } } } if (isMix) { this->m_freq->setText("2.4/5G"); return; } if (freq < FREQ_5GHZ) { this->m_freq->setText("2.4G"); } else { this->m_freq->setText("5G"); } } kylin-nm/src/frontend/list-items/lanlistitem.cpp0000664000175000017500000002571415167651420021007 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "lanlistitem.h" #include "backend/dbus-interface/kylinconnectitem.h" #include #define LOG_FLAG "[LanListItem]" #define NAMELABLE_MAX_WIDTH_HOVER 220 #define NAMELABLE_MAX_WIDTH_ACTIVATED 190 #define NAMELABLE_MAX_WIDTH_DEACTIVATED 326 #define V_MARGINS_SUM 14 LanListItem::LanListItem(const KyConnectItem *lanConnectItem, const QString &deviceName, QWidget *parent):ListItem(parent) { m_connectOperation = new KyWiredConnectOperation(this); m_deviceResource = new KyNetworkDeviceResourse(this); connectItemCopy(lanConnectItem); m_deviceName = deviceName; m_nameLabel->setLabelText(m_lanConnectItem.m_connectName); m_netButton->setButtonIcon(QIcon::fromTheme("network-wired-connected-symbolic")); qDebug() << "LanListItem init:" << m_lanConnectItem.m_connectName << m_lanConnectItem.m_connectState << m_lanConnectItem.m_ifaceName; KyConnectResourse resource; if (resource.isPppoeConnection(m_lanConnectItem.m_connectUuid)) { m_netButton->setButtonIcon(QIcon::fromTheme("ukui-dial-up-symbolic")); } if (Deactivated == m_lanConnectItem.m_connectState || Activated == m_lanConnectItem.m_connectState) { m_netButton->stopLoading(); if (m_lanConnectItem.m_connectState == Activated) { setIcon(true); m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_ACTIVATED); } else { setIcon(false); m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_DEACTIVATED); } } else { m_netButton->startLoading(); } m_connectivityLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_ACTIVATED); m_connectivityLabel->hide(); m_itemFrame->installEventFilter(this); // connect(this->m_infoButton, &InfoButton::clicked, this, &LanListItem::onInfoButtonClicked); connect(m_hoverButton, &FixPushButton::clicked, this, &LanListItem::onNetButtonClicked); connect(m_hoverButton, &FixPushButton::released, this, &LanListItem::onNetButtonReleased); } LanListItem::LanListItem(QWidget *parent) : ListItem(parent) { m_isActive = false; m_netButton->setButtonIcon(QIcon::fromTheme("network-wired-disconnected-symbolic")); setIcon(false); const QString str=tr("Not connected"); m_nameLabel->setLabelText(str); // this->m_infoButton->hide(); } LanListItem::~LanListItem() { qDebug()<<"[LanPage] lan list item is deleted." << m_lanConnectItem.m_connectName; } void LanListItem::setIcon(bool isOn) { if (isOn) { m_netButton->setActive(true); //设置图标显示不同颜色 } else { m_netButton->setActive(false); } } void LanListItem::connectItemCopy(const KyConnectItem *lanConnectItem) { if (lanConnectItem) { m_lanConnectItem.m_connectName = lanConnectItem->m_connectName; m_lanConnectItem.m_connectPath = lanConnectItem->m_connectPath; m_lanConnectItem.m_connectState = lanConnectItem->m_connectState; m_lanConnectItem.m_connectUuid = lanConnectItem->m_connectUuid; m_lanConnectItem.m_ifaceName = lanConnectItem->m_ifaceName; m_lanConnectItem.m_itemType = lanConnectItem->m_itemType; } else { qDebug() << LOG_FLAG <<"the connect item is nullptr"; m_lanConnectItem.m_connectName = ""; m_lanConnectItem.m_connectPath = ""; m_lanConnectItem.m_connectState = NetworkManager::ActiveConnection::State::Unknown; m_lanConnectItem.m_connectUuid = ""; m_lanConnectItem.m_ifaceName = ""; m_lanConnectItem.m_itemType = NetworkManager::ConnectionSettings::ConnectionType::Unknown; } return; } void LanListItem::onNetButtonClicked() { if (m_lanConnectItem.m_connectUuid.isEmpty()) { qDebug() << LOG_FLAG << "connect is empty, so can not connect or disconnect."; return; } if (Deactivated == m_lanConnectItem.m_connectState) { if (m_deviceResource->wiredDeviceIsCarriered(m_deviceName)) { m_connectOperation->activateWiredConnection(m_lanConnectItem.m_connectUuid, m_deviceName); qDebug() << LOG_FLAG << "it will activate connection" << m_lanConnectItem.m_connectName << ". it's device is" << m_deviceName; } else { qDebug() << LOG_FLAG << m_deviceName << "is not carried, so can not activate connection"; this->showDesktopNotify(tr("Wired Device not carried"), "networkwrong"); } } else { m_connectOperation->deactivateWiredConnection(m_lanConnectItem.m_connectName, m_lanConnectItem.m_connectUuid); } return; } void LanListItem::onNetButtonReleased() { if (Deactivated == m_lanConnectItem.m_connectState) { m_hoverButton->setProperty("isImportant", true); m_hoverButton->setProperty("useButtonPalette", false); m_hoverButton->setButtonText(tr("Connect")); } else { m_hoverButton->setProperty("useButtonPalette", true); m_hoverButton->setProperty("isImportant", false); m_hoverButton->setButtonText(tr("Disconnect")); } if (Activating == m_lanConnectItem.m_connectState) { m_netButton->startLoading(); } else { m_netButton->stopLoading(); } } void LanListItem::onRightButtonClicked() { //右键点击事件 qDebug()<< LOG_FLAG <<"onRightButtonClicked"; if (!m_menu) { return; } m_menu->clear(); if (Activated == m_lanConnectItem.m_connectState || Activating == m_lanConnectItem.m_connectState) { m_menu->addAction(new QAction(tr("Disconnect"), this)); } else if (Deactivated == m_lanConnectItem.m_connectState) { m_menu->addAction(new QAction(tr("Connect"), this)); } else { return; } m_menu->addAction(new QAction(tr("Property"), this)); m_menu->addAction(new QAction(tr("Delete"), this)); m_menu->popup(cursor().pos()); return; } void LanListItem::onMenuTriggered(QAction *action) { if (action->text() == tr("Connect")) { this->onNetButtonClicked(); } else if (action->text() == tr("Disconnect")) { m_connectOperation->deactivateWiredConnection(m_lanConnectItem.m_connectName, m_lanConnectItem.m_connectUuid); qDebug() << LOG_FLAG << "it will disconnect connection" << m_lanConnectItem.m_connectName << ". it's device is" << m_deviceName; m_netButton->startLoading(); } else if (action->text() == tr("Property")) { onInfoButtonClicked(); } else if (action->text() == tr("Delete")) { m_connectOperation->deleteConnect(m_lanConnectItem.m_connectUuid); } return; } void LanListItem::onInfoButtonClicked() { if (m_lanConnectItem.m_connectUuid.isEmpty()) { qDebug() << LOG_FLAG << "connect is empty, so can not show detail info."; return; } // if(netDetail != nullptr){ // netDetail->activateWindow(); // return; // } qDebug()<< LOG_FLAG << "the info button of lan is clicked! uuid = " << m_lanConnectItem.m_connectUuid << "; name = " << m_lanConnectItem.m_connectName << "." <show(); #endif Q_EMIT this->detailShow(m_deviceName, m_lanConnectItem.m_connectUuid); return; } void LanListItem::updateConnectionState(ConnectState state) { m_lanConnectItem.m_connectState = (NetworkManager::ActiveConnection::State)state; if (Deactivated == state || Activated == state) { if (state == Activated) { setIcon(true); } else { setIcon(false); } } onNetButtonReleased(); return; } QString LanListItem::getConnectionName() { return m_lanConnectItem.m_connectName; } void LanListItem::updateConnectionName(QString connectionName) { m_lanConnectItem.m_connectName = connectionName; m_nameLabel->setLabelText(m_lanConnectItem.m_connectName); return; } QString LanListItem::getConnectionPath() { return m_lanConnectItem.m_connectPath; } void LanListItem::updateConnectionPath(QString connectionPath) { m_lanConnectItem.m_connectPath = connectionPath; } void LanListItem::updateConnectivityText(QString connectivityText) { if (!connectivityText.isEmpty()) { m_connectivityLabel->setLabelText(connectivityText); m_connectivityLabel->show(); } else { m_connectivityLabel->setLabelText(""); m_connectivityLabel->hide(); } } int LanListItem::itemHeight() { return m_nameLabel->height() + m_connectivityLabel->height() + V_MARGINS_SUM; } void LanListItem::enterEvent(QEvent *event) { m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_HOVER); if (m_lanConnectItem.m_connectState != UnknownState) { if (Deactivated != m_lanConnectItem.m_connectState) { m_hoverButton->setProperty("useButtonPalette", true); m_hoverButton->setProperty("isImportant", false); m_hoverButton->setButtonText(tr("Disconnect")); } else { m_hoverButton->setProperty("isImportant", true); m_hoverButton->setProperty("useButtonPalette", false); m_hoverButton->setButtonText(tr("Connect")); } m_hoverButton->show(); m_lbLoadUp->hide(); m_lbLoadDown->hide(); m_lbLoadDownImg->hide(); m_lbLoadUpImg->hide(); } return ListItem::enterEvent(event); } void LanListItem::leaveEvent(QEvent *event) { m_hoverButton->hide(); if (m_lanConnectItem.m_connectState == Activated || m_connectState == Deactivating) { m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_ACTIVATED); m_lbLoadUp->show(); m_lbLoadDown->show(); m_lbLoadDownImg->show(); m_lbLoadUpImg->show(); } else { m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_DEACTIVATED); } return ListItem::leaveEvent(event); } kylin-nm/src/frontend/list-items/listitem.h0000664000175000017500000000776315167651420017765 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef LISTITEM_H #define LISTITEM_H #include #include #include #include #include #include #include "radioitembutton.h" #include "infobutton.h" #include "netdetails/netdetail.h" typedef enum{ UnknownState = 0, /**< The active connection is in an unknown state */ Activating, /**< The connection is activating */ Activated, /**< The connection is activated */ Deactivating, /**< The connection is being torn down and cleaned up */ Deactivated /**< The connection is no longer active */ }ConnectState; class FreqLabel : public QLabel { Q_OBJECT public: FreqLabel(QWidget *parent = nullptr); ~FreqLabel() = default; protected: void paintEvent(QPaintEvent *event); private Q_SLOTS: void changedFontSlot(); }; class FixPushButton : public QPushButton { Q_OBJECT public: explicit FixPushButton(QWidget *parent = 0); public: void setButtonText(QString text); QString getText(); private Q_SLOTS: void changedLabelSlot(); private: QString mStr; }; class NameLabel : public QLabel { Q_OBJECT public: explicit NameLabel(QWidget *parent = 0); ~NameLabel() = default; void setLabelText(QString text); void setLabelMaximumWidth(int width); void setPointSizeOffset(int offset); private: QString m_name; int m_maximumWidth = 120; int m_systemPointSize = 10; int m_pointSizeOffset = 0; private Q_SLOTS: void changedLabelSlot(); protected: bool event(QEvent *event) override; }; class ListItem : public QFrame { Q_OBJECT public: ListItem(QWidget *parent = nullptr); ~ListItem(); void setName(const QString &name); void setActive(const bool &isActive); void setConnectState(ConnectState state); static void showDesktopNotify(const QString &message, QString soundName); void setConnectivityText(const QString connectivityText); protected: void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void enterEvent(QEvent *event); void leaveEvent(QEvent *event); void paintEvent(QPaintEvent *event); virtual void onRightButtonClicked() = 0; protected: QFrame * m_itemFrame = nullptr; QFrame *m_nameFrame = nullptr; NameLabel *m_connectivityLabel = nullptr; NameLabel * m_nameLabel = nullptr; RadioItemButton * m_netButton = nullptr; // InfoButton * m_infoButton = nullptr; bool m_isActive = false; ConnectState m_connectState; QMenu *m_menu = nullptr; public: QVBoxLayout * m_mainLayout = nullptr; QHBoxLayout * m_hItemLayout = nullptr; QLabel *m_lbLoadDown = nullptr; QLabel *m_lbLoadUp = nullptr; QLabel *m_lbLoadDownImg = nullptr; QLabel *m_lbLoadUpImg = nullptr; QLabel *m_freq = nullptr; NetDetail *netDetail = nullptr; FixPushButton *m_hoverButton = nullptr; private: void initUI(); void initConnection(); public Q_SLOTS: virtual void onNetButtonClicked() = 0; virtual void onNetButtonReleased() = 0; void onPaletteChanged(); virtual void onMenuTriggered(QAction *action)=0; Q_SIGNALS: void detailShow(QString, QString); }; #endif // LISTITEM_H kylin-nm/src/frontend/list-items/wlanlistitem.h0000664000175000017500000001010615167651420020630 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef WLANLISTITEM_H #define WLANLISTITEM_H #include "listitem.h" #include "kywirelessnetitem.h" #include "kywirelessnetresource.h" #include "wlanpage.h" #include "kywirelessconnectoperation.h" #include #include "kylinactiveconnectresource.h" #include #include "enterprisewlandialog.h" #include #include "kwidget.h" #include "kpasswordedit.h" using namespace kdk; #define PSK_SETTING_NAME "802-11-wireless-security" #define NORMAL_HEIGHT 48 #define EXPANDED_HEIGHT 120 #define PWD_LENGTH_LIMIT 8 #define PWD_LENGTH_MAX 63 #define EXCELLENT_SIGNAL 80 #define GOOD_SIGNAL 55 #define OK_SIGNAL 30 #define LOW_SIGNAL 5 #define NONE_SIGNAL 0 #define FREQ_5GHZ 5000 class WlanListItem : public ListItem { Q_OBJECT public: WlanListItem(KyWirelessNetItem &wirelessNetItem, QString device, bool isApMode, bool isShowWifi6Plus, QWidget *parent = nullptr); WlanListItem(KyWirelessNetItem &wirelessNetItem, QString device, bool isShowWifi6Plus, QWidget *parent = nullptr); WlanListItem(QWidget *parent = nullptr); ~WlanListItem(); public: QString getSsid(); QString getUuid(); QString getPath(); void setSignalStrength(const int &signal); int getSignalStrength(); bool isConfigured(); void setWlanState(const int &state); void setExpanded(const bool &expanded); ConnectState getConnectionState(); void updateConnectState(ConnectState state); void updateWirelessNetSecurity(QString ssid, QString securityType); void updateWirelessNetItem(KyWirelessNetItem &wirelessNetItem); void forgetPwd(); void setFrequency(); protected: void resizeEvent(QResizeEvent *event); void onRightButtonClicked(); void enterEvent(QEvent *event); void leaveEvent(QEvent *event); bool eventFilter(QObject *watched, QEvent *event); void keyPressEvent(QKeyEvent *event); void paintEvent(QPaintEvent *event); Q_SIGNALS: void itemHeightChanged(const bool isExpanded, const QString &ssid); private: void initWlanUI(); void refreshIcon(bool isActivated); private: KyWirelessNetItem m_wirelessNetItem; KyWirelessConnectOperation *m_wirelessConnectOperation = nullptr; EnterpriseWlanDialog *enterpriseWlanDialog = nullptr; KyNetworkDeviceResourse *m_deviceResource = nullptr; bool m_hasPwd = true; QString m_wlanDevice; bool isEnterpriseWlanDialogShow = false; //密码输入区域的UI QFrame *m_pwdFrame = nullptr; QHBoxLayout *m_pwdFrameLyt = nullptr; KPasswordEdit *m_pwdLineEdit = nullptr; FixPushButton *m_connectButton = nullptr; //自动连接选择区域UI QFrame *m_autoConnectFrame = nullptr; QHBoxLayout *m_autoConnectFrameLyt = nullptr; QCheckBox *m_autoConnectCheckBox = nullptr; QLabel *m_autoConnectLabel = nullptr; bool m_forgetConnection = false; bool m_isApMode = false; bool m_isShowWifi6Plus = true; protected Q_SLOTS: void onInfoButtonClicked(); private Q_SLOTS: void onNetButtonClicked(); void onNetButtonReleased(); void onPwdEditorTextChanged(); void onConnectButtonClicked(); void onMenuTriggered(QAction *action); void onEnterpriseWlanDialogClose(bool isShow); }; #endif // WLANLISTITEM_H kylin-nm/src/frontend/list-items/wlanmoreitem.h0000664000175000017500000000252115167651420020621 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef WLANMOREITEM_H #define WLANMOREITEM_H #include #include "listitem.h" const QString WMI_OB_NAME = "WlanMoreItemObjName"; class WlanMoreItem : public ListItem { Q_OBJECT protected: void onRightButtonClicked(); public: WlanMoreItem(QWidget *parent = nullptr); ~WlanMoreItem(); void onNetButtonClicked(); void onNetButtonReleased(); void onMenuTriggered(QAction *action); Q_SIGNALS: void hiddenWlanClicked(); }; #endif // WLANMOREITEM_H kylin-nm/src/frontend/list-items/listitem.cpp0000664000175000017500000003454015167651420020311 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "listitem.h" #include #include #define MAIN_LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_SPACING 0 #define ITEM_FRAME_MARGINS 12,6,16,6 #define ITEM_FRAME_SPACING 8 #define FRAME_WIDTH 404 #define INFO_ICON_WIDTH 16 #define INFO_ICON_HEIGHT 16 #define LIGHT_HOVER_COLOR QColor(240,240,240,255) #define DARK_HOVER_COLOR QColor(15,15,15,255) #define CONNECT_BUTTON_WIDTH 96 #define PWD_AREA_HEIGHT 36 #define FREQLABLE_HIGHT 18 #define FREQLABLE_MARGINS 4,0,4,0 #define LOADIMG_SIZE 16,16 #define NAME_LABEL_MIN_HEIGHT 16 #define NAME_LABEL_MAX_HEIGHT 36 FreqLabel::FreqLabel(QWidget *parent) : QLabel(parent) { const QByteArray id("org.ukui.style"); QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); if(QGSettings::isSchemaInstalled(id)){ connect(fontSetting, &QGSettings::changed,[=](QString key) { if ("systemFontSize" ==key) { changedFontSlot(); } }); } changedFontSlot(); } void FreqLabel::changedFontSlot() { const QByteArray id("org.ukui.style"); if(QGSettings::isSchemaInstalled(id)){ QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); QVariant fontVariant = fontSetting->get("systemFontSize"); QFont font; font.setPointSize(fontVariant.toInt()*0.85); this->setFont(font); } } void FreqLabel::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); //抗锯齿效果 QRect rect(this->rect().left() + 1, this->rect().top() + 1, this->rect().width() - 2, this->rect().height() - 2); painter.drawRoundedRect(rect, 4, 4); QLabel::paintEvent(event); } FixPushButton::FixPushButton(QWidget *parent) : QPushButton(parent) { const QByteArray id("org.ukui.style"); QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); if(QGSettings::isSchemaInstalled(id)){ connect(fontSetting, &QGSettings::changed,[=](QString key) { if ("systemFont" == key || "systemFontSize" ==key) { changedLabelSlot(); } }); } } void FixPushButton::setButtonText(QString text) { mStr = text; changedLabelSlot(); } QString FixPushButton::getText(){ return mStr; } void FixPushButton::changedLabelSlot() { QFontMetrics fontMetrics(this->font()); int fontSize = fontMetrics.horizontalAdvance(mStr); if (fontSize > 65) { setText(fontMetrics.elidedText(mStr, Qt::ElideRight, 65)); setToolTip(mStr); } else { setText(mStr); setToolTip(""); } } ListItem::ListItem(QWidget *parent) : QFrame(parent) { m_connectState = UnknownState; initUI(); initConnection(); connect(qApp, &QApplication::paletteChanged, this, &ListItem::onPaletteChanged); // m_itemFrame->installEventFilter(this); const QByteArray id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(id)) { QGSettings * styleGsettings = new QGSettings(id, QByteArray(), this); connect(styleGsettings, &QGSettings::changed, this, [=](QString key){ if ("themeColor" == key) { onPaletteChanged(); } }); } onPaletteChanged(); } ListItem::~ListItem() { if (nullptr != m_netButton) { delete m_netButton; m_netButton = nullptr; } // if (nullptr != m_infoButton) { // delete m_infoButton; // m_infoButton = nullptr; // } } void ListItem::setName(const QString &name) { m_nameLabel->setLabelText(name); } //仅无线调用,有线自己获取 void ListItem::setActive(const bool &isActive) { m_netButton->setActive(isActive); m_isActive = isActive; } void ListItem::setConnectState(ConnectState state) { m_connectState = state; } void ListItem::showDesktopNotify(const QString &message, QString soundName) { QDBusInterface iface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus()); QStringList actions; //跳转动作 actions.append("default"); actions.append("kylin-nm"); //默认动作:点击消息体时打开麒麟录音 QMap hints; if (!soundName.isEmpty()) { hints.insert("sound-name",soundName); //添加声音 } QList args; args<<(tr("Kylin NM")) <<((unsigned int) 0) <setLabelText(connectivityText); } void ListItem::mousePressEvent(QMouseEvent *event) { qDebug()<<"[ListItem]"<<"mousePressEvent"; if (event->button() == Qt::LeftButton) { onNetButtonClicked(); } else if (event->button() == Qt::RightButton) { onRightButtonClicked(); } return QFrame::mousePressEvent(event); } void ListItem::mouseReleaseEvent(QMouseEvent *event) { qDebug()<<"[ListItem]"<<"mousePressEvent"; if (event->button() == Qt::LeftButton) { onNetButtonReleased(); } else if (event->button() == Qt::RightButton) { onNetButtonReleased(); } return QFrame::mousePressEvent(event); } void ListItem::enterEvent(QEvent *event) { // QPalette pal = qApp->palette(); // QColor baseColor = qApp->palette().base().color(); // if (baseColor.red() > MIDDLE_COLOR) { // pal.setColor(QPalette::Window, LIGHT_HOVER_COLOR); // } else { // pal.setColor(QPalette::Window, DARK_HOVER_COLOR); // } // this->setPalette(pal); // return QFrame::enterEvent(event); } void ListItem::leaveEvent(QEvent *event) { // QPalette pal = qApp->palette(); // pal.setColor(QPalette::Window, qApp->palette().base().color()); // this->setPalette(pal); // return QFrame::leaveEvent(event); } void ListItem::paintEvent(QPaintEvent *event) { // QPainter painter(this); // painter.setRenderHint(QPainter::Antialiasing); //反锯齿 // painter.setBrush(this->palette().brush(QPalette::Window)); // painter.setPen(Qt::transparent); // painter.drawRoundedRect(this->rect(), 6, 6); // return QFrame::paintEvent(event); } void ListItem::initUI() { m_menu = new QMenu(this);//右键菜单 // m_menu->setStyleSheet("QMenu::item{border:3px; border-radius:3px}"); // m_menu->setStyleSheet("QMenu{border-radius:6px; margin:6px 6px 6px 6px}"); connect(m_menu, &QMenu::triggered, this, &ListItem::onMenuTriggered); m_mainLayout = new QVBoxLayout(this); m_mainLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); m_mainLayout->setSpacing(MAIN_LAYOUT_SPACING); this->setLayout(m_mainLayout); m_itemFrame = new QFrame(this); m_itemFrame->setFixedWidth(FRAME_WIDTH); m_hItemLayout = new QHBoxLayout(m_itemFrame); m_hItemLayout->setContentsMargins(ITEM_FRAME_MARGINS); m_hItemLayout->setSpacing(0); m_hItemLayout->setAlignment(Qt::AlignHCenter); m_netButton = new RadioItemButton(m_itemFrame); m_freq = new FreqLabel(m_itemFrame); m_freq->setEnabled(false); m_freq->setText("..."); m_freq->setAlignment(Qt::AlignCenter); m_freq->hide(); m_freq->setFixedHeight(FREQLABLE_HIGHT); m_freq->setContentsMargins(FREQLABLE_MARGINS); m_nameLabel = new NameLabel(m_itemFrame); m_nameFrame = new QFrame(m_itemFrame); m_connectivityLabel = new NameLabel(m_itemFrame); m_connectivityLabel->setPointSizeOffset(-2); QVBoxLayout *hLabelsLayout = new QVBoxLayout(m_nameFrame); hLabelsLayout->setContentsMargins(0, 0, 0, 0); hLabelsLayout->setSpacing(2); hLabelsLayout->addWidget(m_nameLabel); hLabelsLayout->addWidget(m_connectivityLabel); m_connectivityLabel->hide(); m_hoverButton = new FixPushButton(m_itemFrame); m_hoverButton->setProperty("needTranslucent", true); m_hoverButton->setFixedSize(CONNECT_BUTTON_WIDTH, PWD_AREA_HEIGHT); // m_infoButton = new InfoButton(m_itemFrame); // m_infoButton->setIconSize(QSize(INFO_ICON_WIDTH,INFO_ICON_HEIGHT)); m_lbLoadUp = new QLabel(m_itemFrame); m_lbLoadUp->setAlignment(Qt::AlignCenter); m_lbLoadDown = new QLabel(m_itemFrame); m_lbLoadDown->setAlignment(Qt::AlignCenter); m_lbLoadDownImg = new QLabel(m_itemFrame); m_lbLoadUpImg = new QLabel(m_itemFrame); m_lbLoadUp->hide(); m_lbLoadDown->hide(); m_lbLoadDownImg->hide(); m_lbLoadUpImg->hide(); m_lbLoadDownImg->setFixedSize(LOADIMG_SIZE); m_lbLoadDownImg->setAlignment(Qt::AlignCenter); m_lbLoadUpImg->setFixedSize(LOADIMG_SIZE); m_lbLoadUpImg->setAlignment(Qt::AlignCenter); QFont font; font.setPointSize(10); m_lbLoadUp->setFont(font); m_lbLoadDown->setFont(font); m_lbLoadUp->setText("0KB/s"); m_lbLoadDown->setText("0KB/s"); m_lbLoadDownImg->setPixmap(QPixmap(QLatin1String(":/res/x/load-down.png"))); m_lbLoadUpImg->setPixmap(QPixmap(QLatin1String(":/res/x/load-up.png"))); m_hItemLayout->addWidget(m_netButton); m_hItemLayout->addSpacing(10); m_hItemLayout->addWidget(m_nameFrame); m_hItemLayout->addSpacing(6); //设计稿间距为8 nameLabel宽度另+2 m_hItemLayout->addWidget(m_freq); m_hItemLayout->addStretch(); m_hItemLayout->addSpacing(8); m_hItemLayout->addWidget(m_lbLoadUpImg); m_hItemLayout->addWidget(m_lbLoadUp); m_hItemLayout->addSpacing(2); m_hItemLayout->addWidget(m_lbLoadDownImg); m_hItemLayout->addWidget(m_lbLoadDown); m_hItemLayout->addWidget(m_hoverButton); // m_hItemLayout->addWidget(m_infoButton); m_mainLayout->addWidget(m_itemFrame); m_hoverButton->hide(); // this->setAutoFillBackground(true); // this->setBackgroundRole(QPalette::Base); // QPalette pal = qApp->palette(); // pal.setColor(QPalette::Window, qApp->palette().base().color()); // this->setPalette(pal); } void ListItem::initConnection() { connect(this->m_netButton, &RadioItemButton::clicked, this, &ListItem::onNetButtonClicked); // connect(this->m_infoButton, &InfoButton::clicked, this, &ListItem::onInfoButtonClicked); } void ListItem::onPaletteChanged() { // QPalette pal = qApp->palette(); // pal.setColor(QPalette::Window, qApp->palette().base().color()); // this->setPalette(pal); QPalette pal = qApp->palette(); QGSettings * styleGsettings = nullptr; const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { styleGsettings = new QGSettings(style_id, QByteArray(), this); QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = themePalette(true, this); } } pal.setColor(QPalette::Base, pal.color(QPalette::Base)); //解决Wayland环境this->setPalette(pal)不生效问题 this->setPalette(pal); if (m_menu != nullptr) { pal.setColor(QPalette::Text, pal.color(QPalette::Text)); m_menu->setPalette(pal); } if (m_connectivityLabel != nullptr) { QColor PlaceColor = this->palette().color(QPalette::PlaceholderText); pal.setColor(QPalette::Text, PlaceColor); m_connectivityLabel->setPalette(pal); } } NameLabel::NameLabel(QWidget *parent) :QLabel(parent) { this->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); const QByteArray id("org.ukui.style"); QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); if(QGSettings::isSchemaInstalled(id)){ m_systemPointSize = fontSetting->get("systemFontSize").toFloat(); connect(fontSetting, &QGSettings::changed,[=](QString key) { if ("systemFont" == key || "systemFontSize" ==key) { m_systemPointSize = fontSetting->get("systemFontSize").toFloat(); QFont font; font.setPointSize(m_systemPointSize + m_pointSizeOffset); this->setFont(font); changedLabelSlot(); } }); } } void NameLabel::setLabelText(QString text) { m_name = text; changedLabelSlot(); } void NameLabel::setLabelMaximumWidth(int width) { m_maximumWidth = width; this->setMaximumWidth(m_maximumWidth); if (m_name != nullptr) { changedLabelSlot(); } } void NameLabel::setPointSizeOffset(int offset) { m_pointSizeOffset = offset; QFont font; font.setPointSize(m_systemPointSize + m_pointSizeOffset); this->setFont(font); } void NameLabel::changedLabelSlot() { this->setMinimumHeight(NAME_LABEL_MIN_HEIGHT); this->setMaximumHeight(NAME_LABEL_MAX_HEIGHT); QFontMetrics fontMetrics(this->font()); int fontSize = fontMetrics.horizontalAdvance(m_name); if (fontSize > m_maximumWidth) { this->setFixedWidth(m_maximumWidth); setText(fontMetrics.elidedText(m_name, Qt::ElideRight, m_maximumWidth)); setToolTip(m_name); } else { this->setFixedWidth(fontMetrics.horizontalAdvance(m_name) + 2); setText(m_name); setToolTip(""); } this->adjustSize(); this->setFixedHeight(this->height()); } bool NameLabel::event(QEvent *event) { if (event->type() == QEvent::Paint) { QPalette tooltipPal = QToolTip::palette(); tooltipPal.setColor(QPalette::ToolTipBase, this->palette().toolTipBase().color()); tooltipPal.setColor(QPalette::ToolTipText, this->palette().toolTipText().color()); QToolTip::setPalette(tooltipPal); } return QWidget::event(event); } kylin-nm/src/frontend/list-items/onelancform.ui0000664000175000017500000001236115167646234020621 0ustar fengfeng OneLancForm 0 0 424 167 Form 63 8 190 20 316 14 100 34 316 14 100 34 316 14 100 34 63 31 200 20 0 0 424 162 63 64 238 85 63 62 238 20 63 86 260 20 63 110 238 20 63 134 238 20 leInfo_1 leInfo_2 leInfo_3 leInfo_4 btnInfo 14 14 32 32 2 59 421 2 background-color: rgba(156, 156, 156,0.1); Qt::Horizontal 0 0 424 60 316 14 100 34 380 20 20 20 316 14 70 34 wbg wbg_2 lbName lbConned lbIcon line btnConnSub btnDisConn btnConn lbWaiting lbWaitingIcon btnCancel kylin-nm/src/frontend/list-items/lanlistitem.h0000664000175000017500000000422215167651420020443 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef LANLISTITEM_H #define LANLISTITEM_H #include "listitem.h" #include "kylinactiveconnectresource.h" #include #include #include class LanListItem : public ListItem { Q_OBJECT public: LanListItem(const KyConnectItem *lanConnectItem, const QString &deviceName, QWidget *parent = nullptr); LanListItem(QWidget *parent = nullptr); ~LanListItem(); public: void updateConnectionState(ConnectState state); QString getConnectionName(); void updateConnectionName(QString connectionName); QString getConnectionPath(); void updateConnectionPath(QString connectionPath); void updateConnectivityText(QString connectivityText); int itemHeight(); protected: void setIcon(bool isOn); void onRightButtonClicked(); void enterEvent(QEvent *event); void leaveEvent(QEvent *event); private: void connectItemCopy(const KyConnectItem *lanConnectItem); private Q_SLOTS: void onInfoButtonClicked(); void onNetButtonClicked(); void onNetButtonReleased(); void onMenuTriggered(QAction *action); private: KyConnectItem m_lanConnectItem; KyWiredConnectOperation *m_connectOperation = nullptr; KyNetworkDeviceResourse *m_deviceResource = nullptr; QString m_deviceName = ""; }; #endif // LANLISTITEM_H kylin-nm/src/frontend/list-items/oneconnform.ui0000664000175000017500000001435715167646234020650 0ustar fengfeng OneConnForm 0 0 424 142 Form 63 8 241 20 316 14 100 34 316 14 100 34 14 14 32 32 63 31 140 20 0 0 424 106 64 64 352 30 390 75 18 9 316 14 100 34 316 14 100 34 316 14 100 34 0 0 424 138 63 64 230 61 63 62 230 20 63 86 230 20 63 110 230 20 leInfo_1 leInfo_2 leInfo_3 btnInfo 2 59 421 2 background-color: rgba(156, 156, 156,0.1); Qt::Horizontal 0 0 424 60 316 14 100 34 380 20 20 20 316 14 70 34 wbg_3 wbg_2 lbName lbSignal lbConned line wbg btnConnSub btnConn btnConnPWD btnDisConn btnHideConn lbWaiting lbWaitingIcon btnCancel kylin-nm/src/frontend/tab-pages/0000775000175000017500000000000015167651420015516 5ustar fengfengkylin-nm/src/frontend/tab-pages/tab-pages.pri0000664000175000017500000000027215167646234020105 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/lanpage.h \ $$PWD/wlanpage.h \ $$PWD/tabpage.h SOURCES += \ $$PWD/lanpage.cpp \ $$PWD/wlanpage.cpp \ $$PWD/tabpage.cpp kylin-nm/src/frontend/tab-pages/wlanpage.cpp0000664000175000017500000021025615167651420020026 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "wlanpage.h" #include "kywirelessnetitem.h" #include "kwindowsystem.h" #include "kwindowsystem_export.h" #include #include #include #include #include #define AP_SCAN_INTERVAL (20*1000) #define ICON_REFRESH_INTERVAL (5*1000) #define LOG_FLAG "[WlanPage]" #define LAN_PAGE_INDEX 0 const QString NotApConnection = "0"; const QString IsApConnection = "1"; WlanPage::WlanPage(QWidget *parent) : TabPage(parent) { qRegisterMetaType("NetworkManager::Device::State"); qRegisterMetaType("NetworkManager::Device::StateChangeReason"); m_wirelessNetResource = new KyWirelessNetResource(this); m_activatedConnectResource = new KyActiveConnectResourse(this); m_netDeviceResource=new KyNetworkDeviceResourse(this); m_connectResource = new KyConnectResourse(this); m_wirelessConnectOpreation = new KyWirelessConnectOperation(this); checkShowWifi6Plus(); initDevice(); initWlanUI(); initWlanSwitchState(); initWirelssDeviceConnectState();//需在initDeviceCombox前初始化 initDeviceCombox(); initWlanArea(); initTimer(); m_usdInterface = new QDBusInterface("org.ukui.SettingsDaemon","/org/ukui/SettingsDaemon/MediaKeys","org.ukui.SettingsDaemon.MediaKeys",QDBusConnection::sessionBus()); if(!m_usdInterface->isValid()) { qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } connect(m_wirelessNetResource, &KyWirelessNetResource::wifiNetworkAdd, this, &WlanPage::onWlanAdded); connect(m_wirelessNetResource, &KyWirelessNetResource::wifiNetworkRemove, this, &WlanPage::onWlanRemoved); connect(m_wirelessNetResource, &KyWirelessNetResource::signalStrengthChange, this, &WlanPage::signalStrengthChange); connect(m_wirelessNetResource, &KyWirelessNetResource::secuTypeChange, this, &WlanPage::onSecurityTypeChange); connect(m_wirelessNetResource, &KyWirelessNetResource::connectionAdd, this, &WlanPage::onConnectionAdd); connect(m_wirelessNetResource, &KyWirelessNetResource::connectionRemove, this, &WlanPage::onConnectionRemove); connect(m_wirelessNetResource, &KyWirelessNetResource::connectionUpdate, this, &WlanPage::onConnectionUpdate); connect(m_activatedConnectResource, &KyActiveConnectResourse::stateChangeReason, this, &WlanPage::onConnectionStateChanged); connect(m_netDeviceResource, &KyNetworkDeviceResourse::deviceAdd, this, &WlanPage::onDeviceAdd); connect(m_netDeviceResource, &KyNetworkDeviceResourse::deviceRemove, this, &WlanPage::onDeviceRemove); connect(m_netDeviceResource, &KyNetworkDeviceResourse::deviceNameUpdate, this, &WlanPage::onDeviceNameUpdate); connect(m_netDeviceResource, &KyNetworkDeviceResourse::deviceManagedChange, this, &WlanPage::onDeviceManagedChanged); connect(m_netDeviceResource, &KyNetworkDeviceResourse::stateChanged, this, &WlanPage::onWlanStateChanged); connect(m_wirelessConnectOpreation, &KyWirelessConnectOperation::activateConnectionError, this, &WlanPage::activateFailed); connect(m_wirelessConnectOpreation, &KyWirelessConnectOperation::addAndActivateConnectionError, this, &WlanPage::activateFailed); connect(m_wirelessConnectOpreation, &KyWirelessConnectOperation::deactivateConnectionError, this, &WlanPage::deactivateFailed); connect(m_wirelessConnectOpreation, &KyWirelessConnectOperation::wifiEnabledChanged, this, &WlanPage::onWifiEnabledChanged); connect(m_connectResource, &KyConnectResourse::connectivityChanged, this, &WlanPage::connectivityChanged); connect(m_connectResource, &KyConnectResourse::connectivityCheckSpareUriChanged, this, &WlanPage::connectivityCheckSpareUriChanged); connect(m_netSwitch, &KSwitchButton::clicked, this, [=](bool checked) { setSwitchBtnState(!checked); if (!checkTimeIsOut(500)) { return; } //解决 switchBtn不支持点击的情况下,点击按钮,有无线网卡后不自动开启的问题 if (getSwitchBtnEnable()) { setWirelessEnable(checked); } TabPage::startLoading(); }); m_wlanPagePtrMap.clear(); m_joinHiddenWiFiPagePtrMap.clear(); } bool WlanPage::eventFilter(QObject *w, QEvent *e) { if (w == m_settingsLabel) { if (e->type() == QEvent::MouseButtonRelease) { //ZJP_TODO 打开控制面板 qDebug() << LOG_FLAG <<"recive event show control center"; showControlCenter(); } } else if (w == m_netSwitch && m_netSwitch->isEnabled()) { if (e->type() == QEvent::MouseButtonRelease) { if (!getSwitchBtnEnable()) { showDesktopNotify(tr("No wireless network card detected"), "networkwrong"); //检测不到无线网卡不再触发click信号 } } } else if (w == m_activatedNetListWidget) { //去掉无右键菜单显示时的选中效果 if (e->type() == QEvent::FocusIn) { if (m_activatedNetListWidget->currentItem() != nullptr) { m_activatedNetListWidget->currentItem()->setSelected(false); } } } else if (w == m_inactivatedNetListWidget) { //去掉无右键菜单显示时的选中效果 if (e->type() == QEvent::FocusIn) { if (m_inactivatedNetListWidget->currentItem() != nullptr) { m_inactivatedNetListWidget->currentItem()->setSelected(false); } } } return QWidget::eventFilter(w,e); } void WlanPage::initWlanUI() { m_titleLabel->setText(tr("WLAN")); m_activatedNetLabel->setText(tr("Activated WLAN")); m_activatedNetListWidget = new QListWidget(m_activatedNetFrame); m_activatedNetListWidget->setFrameShape(QFrame::Shape::NoFrame); m_activatedNetListWidget->setContentsMargins(MAIN_LAYOUT_MARGINS); m_activatedNetListWidget->setSpacing(NET_LIST_SPACING); m_activatedNetListWidget->setFixedHeight(NORMAL_HEIGHT); m_activatedNetListWidget->setFixedWidth(MIN_WIDTH); m_activatedNetListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_activatedNetListWidget->setProperty("needTranslucent", true); m_activatedNetLayout->addWidget(m_activatedNetListWidget); m_inactivatedNetLabel->setText(tr("Other WLAN")); m_inactivatedNetListWidget = new QListWidget(m_inactivatedNetListArea); m_inactivatedNetListWidget->setContentsMargins(MAIN_LAYOUT_MARGINS); m_inactivatedNetListWidget->setSpacing(NET_LIST_SPACING); m_inactivatedNetListWidget->setFrameShape(QFrame::Shape::NoFrame); m_inactivatedNetListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_inactivatedNetListWidget->setVerticalScrollMode(QAbstractItemView::ScrollMode::ScrollPerPixel); m_inactivatedNetListWidget->verticalScrollBar()->setProperty("drawScrollBarGroove",false); //去除滚动条的外侧黑框 m_inactivatedNetListWidget->verticalScrollBar()->setSingleStep(SCROLL_STEP); m_inactivatedNetListWidget->verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu); m_inactivatedNetListWidget->verticalScrollBar()->setProperty("needTranslucent", true); m_inactivatedNetListWidget->setProperty("needTranslucent", true); addWlanMoreItem(); m_inactivatedAreaLayout->addWidget(m_inactivatedNetListWidget); connect(m_inactivatedNetListWidget, &QListWidget::currentItemChanged, this, &WlanPage::onInactivateListWidgetItemChanged); //点击【已连接】网络区域 去掉其他网络的选中效果 connect(m_activatedNetListWidget, &QListWidget::clicked, this, &WlanPage::setInactivateListItemNoSelect); connect(m_activatedNetListWidget, &QListWidget::currentItemChanged, this, &WlanPage::setInactivateListItemNoSelect); QPalette pal = m_activatedNetListWidget->palette(); pal.setBrush(QPalette::Base, QColor(0,0,0,0)); //背景透明 m_activatedNetListWidget->setPalette(pal); m_inactivatedNetListWidget->setPalette(pal); m_settingsLabel->installEventFilter(this); m_netSwitch->installEventFilter(this); m_activatedNetListWidget->installEventFilter(this); m_inactivatedNetListWidget->installEventFilter(this); showRate(); } bool WlanPage::getWirelessDevieceUseable() { for (auto devname : m_devList) { if (m_netDeviceResource->getDeviceState(devname) >= NetworkManager::Device::Disconnected) { return true; } } return false; } void WlanPage::setWirelessEnable(bool state) { m_wirelessConnectOpreation->setWirelessEnabled(state); return; } bool WlanPage::getWirelessEnable() { return m_wirelessConnectOpreation->getWirelessEnabled(); } void WlanPage::checkShowWifi6Plus() { //990下不显示wifi6+图标 QProcess * processCpuinfo = new QProcess(this); processCpuinfo->start(QString("cat /proc/cpuinfo")); connect(processCpuinfo, static_cast(&QProcess::finished), this, [ = ]() { processCpuinfo->deleteLater(); }); processCpuinfo->waitForFinished(); QString ctrCpuinfo = processCpuinfo->readAll(); if (ctrCpuinfo.indexOf("Kirin", 0, Qt::CaseInsensitive) != -1 && ctrCpuinfo.indexOf("990") != -1) { m_showWifi6Plus = false; } } void WlanPage::initWlanSwitchState() { if (m_devList.isEmpty()) { setSwitchBtnState(false); setSwitchBtnEnable(false); return ; } setSwitchBtnEnable(true); setSwitchBtnState(getWirelessDevieceUseable()); return; } void WlanPage::initTimer() { m_scanTimer = new QTimer(this); connect(m_scanTimer, &QTimer::timeout, this, &WlanPage::requestScan); m_refreshIconTimer = new QTimer(this); connect(m_refreshIconTimer, &QTimer::timeout, this, &WlanPage::onRefreshIconTimer); m_refreshIconTimer->start(ICON_REFRESH_INTERVAL); } /** * @brief WlanPage::initDevice 初始化默认网卡 */ void WlanPage::initDevice() { m_devList.clear(); m_netDeviceResource->getNetworkDeviceList(NetworkManager::Device::Type::Wifi, m_devList); m_currentDevice = getDefaultDeviceName(WIRELESS); if (m_devList.count() == 0) { return; } for (int index = m_devList.count() - 1; index >= 0; --index) { if (!m_netDeviceResource->getDeviceManaged(m_devList.at(index))) { //删除未托管网卡 qDebug() << LOG_FLAG << "delete unmanaged device" << m_devList.at(index); m_devList.removeOne(m_devList.at(index)); } } return; } void WlanPage::initDeviceCombox() { QString deviceState ; int flag = 0; //TODO 获取设备列表,单设备时隐藏下拉框,多设备时添加到下拉框 disconnect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &WlanPage::onDeviceComboxIndexChanged); m_deviceComboBox->clear(); if (getSwitchBtnState()) { if (0 == m_devList.count()) { m_deviceFrame->show(); m_tipsLabel->show(); m_deviceComboBox->hide(); m_currentDevice = ""; setDefaultDevice(WIRELESS, m_currentDevice); } else if (1 == m_devList.count()) { m_deviceFrame->hide(); if (m_currentDevice != m_devList.at(0)) { m_currentDevice = m_devList.at(0); setDefaultDevice(WIRELESS, m_currentDevice); } } else { m_deviceFrame->show(); m_deviceComboBox->show(); m_tipsLabel->hide(); for (int index = 0; index < m_devList.count(); ++index) { flag=m_deviceState[m_devList.at(index)]; deviceState=changeDeviceStateText(m_devList.at(index),flag); m_deviceComboBox->addItem(deviceState,m_devList.at(index)); } if (m_devList.contains(m_currentDevice)) { flag=m_deviceState[m_currentDevice]; deviceState=changeDeviceStateText(m_currentDevice,flag); m_deviceComboBox->setCurrentText(deviceState); } else { //m_currentDevice = m_deviceComboBox->currentText(); m_currentDevice = m_deviceComboBox->currentData().toString(); setDefaultDevice(WIRELESS, m_currentDevice); } } } else { m_deviceFrame->hide(); m_currentDevice = ""; setDefaultDevice(WIRELESS, m_currentDevice); } connect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &WlanPage::onDeviceComboxIndexChanged, Qt::DirectConnection); return; } QListWidgetItem *WlanPage::addEmptyItem(QListWidget *wirelessListWidget) { WlanListItem *p_wlanItem = new WlanListItem(); QListWidgetItem *p_listWidgetItem = new QListWidgetItem(); p_listWidgetItem->setSizeHint(QSize(wirelessListWidget->width(), p_wlanItem->height())); wirelessListWidget->addItem(p_listWidgetItem); wirelessListWidget->setItemWidget(p_listWidgetItem, p_wlanItem); return p_listWidgetItem; } QListWidgetItem *WlanPage::addNewItem(KyWirelessNetItem &wirelessNetItem, QListWidget *wirelessListWidget) { WlanListItem *p_wlanItem = new WlanListItem( wirelessNetItem, m_currentDevice, m_connectResource->isApConnection(wirelessNetItem.m_connectUuid), m_showWifi6Plus); connect(p_wlanItem, &WlanListItem::itemHeightChanged, this, &WlanPage::onItemHeightChanged); connect(p_wlanItem, &WlanListItem::detailShow, this, &WlanPage::showDetailPage); QListWidgetItem *p_listWidgetItem = new QListWidgetItem(); p_listWidgetItem->setSizeHint(QSize(wirelessListWidget->width(), p_wlanItem->height())); wirelessListWidget->addItem(p_listWidgetItem); wirelessListWidget->setItemWidget(p_listWidgetItem, p_wlanItem); return p_listWidgetItem; } QListWidgetItem *WlanPage::insertNewItem(KyWirelessNetItem &wirelessNetItem, QListWidget *wirelessListWidget, int row) { WlanListItem *p_wlanItem = new WlanListItem(wirelessNetItem, m_currentDevice, m_showWifi6Plus); connect(p_wlanItem, &WlanListItem::itemHeightChanged, this, &WlanPage::onItemHeightChanged); connect(p_wlanItem, &WlanListItem::detailShow, this, &WlanPage::showDetailPage); QListWidgetItem *p_listWidgetItem = new QListWidgetItem(); p_listWidgetItem->setSizeHint(QSize(wirelessListWidget->width(), p_wlanItem->height())); wirelessListWidget->insertItem(row, p_listWidgetItem); wirelessListWidget->setItemWidget(p_listWidgetItem, p_wlanItem); return p_listWidgetItem; } QListWidgetItem *WlanPage::insertNewItemWithSort(KyWirelessNetItem &wirelessNetItem, QListWidget *p_ListWidget) { int row = 0; WlanListItem *p_sortWlanItem = new WlanListItem(wirelessNetItem, m_currentDevice, m_showWifi6Plus); connect(p_sortWlanItem, &WlanListItem::itemHeightChanged, this, &WlanPage::onItemHeightChanged); connect(p_sortWlanItem, &WlanListItem::detailShow, this, &WlanPage::showDetailPage); QListWidgetItem *p_sortListWidgetItem = new QListWidgetItem(); p_sortListWidgetItem->setSizeHint(QSize(p_ListWidget->width(), p_sortWlanItem->height())); for (row = 0; row < p_ListWidget->count() - 1; ++row) { QListWidgetItem *p_listWidgetItem = p_ListWidget->item(row); WlanListItem *p_wlanItem = (WlanListItem *)p_ListWidget->itemWidget(p_listWidgetItem); if (WMI_OB_NAME == p_wlanItem->objectName()) { qDebug() << "insertNewItemWithSort" << "p_wlanItem is WlanMoreItem"; continue; } // qDebug()<< "insertNewItemWithSort" << p_wlanItem->getSsid() // <<"item config" << p_wlanItem->isConfigured() // << "signal strength" << p_wlanItem->getSignalStrength(); if (wirelessNetItem.m_isConfigured == p_wlanItem->isConfigured()) { if (wirelessNetItem.m_signalStrength > p_wlanItem->getSignalStrength()) { break; } } else { if (wirelessNetItem.m_isConfigured) { break; } } } p_ListWidget->insertItem(row, p_sortListWidgetItem); p_ListWidget->setItemWidget(p_sortListWidgetItem, p_sortWlanItem); //qDebug()<< "insertNewItemWithSort" << "insert sort item finished. row" << row; return p_sortListWidgetItem; } void WlanPage::clearWirelessNetItemMap(QMap &wirelessNetItem, QListWidget *wirelessListWidget) { QMap::iterator iter; iter = wirelessNetItem.begin(); while (iter != wirelessNetItem.end()) { QListWidgetItem *p_listWidgetItem = iter.value(); if (p_listWidgetItem == m_hiddenItem) { continue; } WlanListItem *p_wlanItem = (WlanListItem *)wirelessListWidget->itemWidget(p_listWidgetItem); wirelessListWidget->removeItemWidget(p_listWidgetItem); delete p_wlanItem; delete p_listWidgetItem; iter = wirelessNetItem.erase(iter); } return; } void WlanPage::deleteWirelessItemFormMap(QMap &wirelessNetItemMap, QListWidget *wirelessListWidget, QString ssid) { QListWidgetItem *p_listWidgetItem = wirelessNetItemMap.value(ssid); if (nullptr == p_listWidgetItem) { qWarning()<< LOG_FLAG <<"wireless item is not exsit, it's ssid is " << ssid; return; } WlanListItem *p_wlanItem = (WlanListItem *)wirelessListWidget->itemWidget(p_listWidgetItem); if (nullptr == p_wlanItem) { qWarning() << LOG_FLAG << "p_wlanItem is null"; return; } wirelessNetItemMap.remove(ssid); wirelessListWidget->takeItem(wirelessListWidget->row(p_listWidgetItem)); delete p_wlanItem; delete p_listWidgetItem; if (m_inactivatedNetListWidget->count() <= MAX_ITEMS) { m_inactivatedNetListWidget->setFixedWidth(MIN_WIDTH); } return; } void WlanPage::updateWlanItemState(QListWidget *p_wirelessListWidget, QListWidgetItem *p_listWidgetItem, ConnectState state) { WlanListItem *p_wlanItem = nullptr; p_wlanItem = (WlanListItem *)p_wirelessListWidget->itemWidget(p_listWidgetItem); if (nullptr != p_wlanItem) { p_wlanItem->updateConnectState(state); } return; } void WlanPage::constructActivateConnectionArea() { int height = 0; clearWirelessNetItemMap(m_activateConnectionItemMap, m_activatedNetListWidget); if (!m_currentDevice.isEmpty()) { KyWirelessNetItem wirelessNetItem; bool ret = m_wirelessNetResource->getActiveWirelessNetItem(m_currentDevice, wirelessNetItem); if (ret == true) { QListWidgetItem *p_listWidgetItem = addNewItem(wirelessNetItem, m_activatedNetListWidget); m_activateConnectionItemMap.insert(wirelessNetItem.m_NetSsid, p_listWidgetItem); updateWlanItemState(m_activatedNetListWidget, p_listWidgetItem, Activated); height += p_listWidgetItem->sizeHint().height(); setNetSpeed->start(REFRESH_NETWORKSPEED_TIMER); m_activatedNetListWidget->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection); } } if (height == 0) { QListWidgetItem *p_listWidgetItem = addEmptyItem(m_activatedNetListWidget); m_activateConnectionItemMap.insert(EMPTY_SSID, p_listWidgetItem); m_activatedNetListWidget->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection); height += p_listWidgetItem->sizeHint().height(); } m_activatedNetListWidget->setFixedHeight(height); return; } void WlanPage::constructWirelessNetArea() { qDebug() << "[WlanPage] Started loading wireless net list!" << QDateTime::currentDateTime().toString("hh:mm:ss.zzzz"); clearWirelessNetItemMap(m_wirelessNetItemMap, m_inactivatedNetListWidget); m_expandedItem = nullptr; QList wirelessNetItemList; if (!m_wirelessNetResource->getDeviceWifiNetwork(m_currentDevice, wirelessNetItemList)) { qWarning()<<"[WlanPage] get wireless net item list failed."; return; } QString activateSsid = m_activateConnectionItemMap.firstKey(); Q_FOREACH (auto wirelessNetItem, wirelessNetItemList) { if (wirelessNetItem.m_NetSsid == activateSsid) { continue; } QListWidgetItem *p_listWidgetItem = addNewItem(wirelessNetItem, m_inactivatedNetListWidget); m_wirelessNetItemMap.insert(wirelessNetItem.m_NetSsid, p_listWidgetItem); updateWlanItemState(m_inactivatedNetListWidget, p_listWidgetItem, Deactivated); } addWlanMoreItem(); qDebug() << "[WlanPage] Stopped loading wireless net list! time=" << QDateTime::currentDateTime().toString("hh:mm:ss.zzzz"); if (m_inactivatedNetListWidget->count() <= MAX_ITEMS) { m_inactivatedNetListWidget->setFixedWidth(MIN_WIDTH); } else { m_inactivatedNetListWidget->setFixedWidth(MAX_WIDTH); } return; } void WlanPage::initWlanArea() { showNoDeiceInfo(false,tr("")); if (getSwitchBtnState()) { m_activatedNetFrame->show(); m_activatedNetDivider->show(); constructActivateConnectionArea(); m_inactivatedNetFrame->show(); constructWirelessNetArea(); } else { m_activatedNetFrame->hide(); m_activatedNetDivider->hide(); m_inactivatedNetFrame->hide(); if (m_devList.isEmpty()) { showNoDeiceInfo(true,tr("No wireless network card detected")); }; } return; } void WlanPage::onWlanAdded(QString interface, KyWirelessNetItem &item) { //for dbus int category = 0; category = item.getCategory(item.m_uni); //990 WiFi6+对应图标显示为WiFi6 if (!m_showWifi6Plus && category == 2) { category = 1; } QStringList info; info << item.m_NetSsid << QString::number(item.m_signalStrength) << item.m_secuType << (m_connectResource->isApConnection(item.m_connectUuid) ? IsApConnection : NotApConnection) << QString::number(category) << QString::number(item.m_isConfigured) << QString::number(item.m_frequency) << (item.m_isMix?IsApConnection : NotApConnection) ; Q_EMIT wlanAdd(interface, info); if (interface != m_currentDevice) { qDebug() << "[WlanPage] wlan add interface not equal defaultdevice"; return; } if (m_wirelessNetItemMap.contains(item.m_NetSsid) || m_activateConnectionItemMap.contains(item.m_NetSsid)) { return; } qDebug() << "[WlanPage] A Wlan Added! interface = " << interface << "; ssid = " << item.m_NetSsid << Q_FUNC_INFO <<__LINE__; KyWirelessNetItem wirelessNetItem; bool ret = m_wirelessNetResource->getActiveWirelessNetItem(m_currentDevice, wirelessNetItem); if (ret == true && wirelessNetItem.m_NetSsid == item.m_NetSsid) { updateActivatedArea(item.m_connectUuid, item.m_NetSsid, m_currentDevice); if (m_activateConnectionItemMap.contains(item.m_NetSsid)) { QListWidgetItem *p_listWidgetItem = m_activateConnectionItemMap.value(item.m_NetSsid); updateWlanItemState(m_activatedNetListWidget, p_listWidgetItem, Activated); return; } } QListWidgetItem *p_listWidgetItem = insertNewItemWithSort(item, m_inactivatedNetListWidget); m_wirelessNetItemMap.insert(item.m_NetSsid, p_listWidgetItem); updateWlanItemState(m_inactivatedNetListWidget, p_listWidgetItem, Deactivated); addWlanMoreItem(); if (m_inactivatedNetListWidget->count() > MAX_ITEMS) { m_inactivatedNetListWidget->setFixedWidth(MAX_WIDTH); } return; } void WlanPage::onWlanRemoved(QString interface, QString ssid) { Q_EMIT wlanRemove(interface, ssid); if (m_wlanPagePtrMap.contains(interface) && m_wlanPagePtrMap[interface].contains(ssid)) { if (m_wlanPagePtrMap[interface][ssid] != nullptr) { m_wlanPagePtrMap[interface][ssid]->close(); } } if (interface != m_currentDevice) { qDebug()<<"[WlanPage] the device is not current device," <<"current device" << m_currentDevice << "remove wlan device" << interface; return; } if (!m_wirelessNetItemMap.contains(ssid) && !m_activateConnectionItemMap.contains(ssid)) { return; } if (m_expandedItem == m_wirelessNetItemMap.value(ssid)) { m_expandedItem = nullptr; } qDebug() << "[WlanPage] A Wlan Removed! interface = " << interface << "; ssid = " << ssid << Q_FUNC_INFO <<__LINE__; if (m_wirelessNetItemMap.contains(ssid)) { deleteWirelessItemFormMap(m_wirelessNetItemMap, m_inactivatedNetListWidget, ssid); } else { deleteWirelessItemFormMap(m_activateConnectionItemMap, m_activatedNetListWidget, ssid); QListWidgetItem *p_listWidgetItem = addEmptyItem(m_activatedNetListWidget); m_activateConnectionItemMap.insert(EMPTY_SSID, p_listWidgetItem); m_activatedNetListWidget->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection); } return; } void WlanPage::updateWlanListItem(QString ssid, bool isConnnectRmove) { KyWirelessNetItem wirelessNetItem; qDebug() << LOG_FLAG << "update wlan list item " << ssid; bool ret = m_wirelessNetResource->getWifiNetwork(m_currentDevice, ssid, wirelessNetItem); if (ret) { QListWidgetItem *p_listWidgetItem = m_wirelessNetItemMap.value(ssid); if (p_listWidgetItem) { WlanListItem *p_wlanItem = (WlanListItem *)m_inactivatedNetListWidget->itemWidget(p_listWidgetItem); p_wlanItem->updateWirelessNetItem(wirelessNetItem); if (isConnnectRmove) { p_wlanItem->updateConnectState(Deactivated); Q_EMIT this->wlanConnectChanged(Deactivated); } } } return; } void WlanPage::onConnectionAdd(QString deviceName, QString ssid) { qDebug() << LOG_FLAG << "one connection is added, it's ssid " << ssid << "device name"<< deviceName; if (deviceName == m_currentDevice) { updateWlanListItem(ssid); } return; } void WlanPage::onConnectionRemove(QString deviceName, QString ssid, QString path) { qDebug() << LOG_FLAG << "one connection is removed, it's ssid " << ssid << "device name"<< deviceName; if (deviceName == m_currentDevice) { if (m_activateConnectionItemMap.contains(ssid)) { updateWirelessNetArea(nullptr, ssid, deviceName, path); } updateWlanListItem(ssid, true); } return; } void WlanPage::onConnectionUpdate(QString deviceName, QString ssid) { qDebug() << "onConnectionUpdate" << deviceName << ssid; if (deviceName == m_currentDevice || deviceName.isEmpty()) { updateWlanListItem(ssid); } } void WlanPage::onSecurityTypeChange(QString devName, QString ssid, QString secuType) { QListWidgetItem *p_listWidgetItem = nullptr; WlanListItem *p_wlanItem = nullptr; qDebug()<< LOG_FLAG << "security type is chenged"; if (m_wirelessNetItemMap.contains(ssid)) { p_listWidgetItem = m_wirelessNetItemMap.value(ssid); p_wlanItem = (WlanListItem*)m_inactivatedNetListWidget->itemWidget(p_listWidgetItem); } else if (m_activateConnectionItemMap.contains(ssid)) { p_listWidgetItem = m_activateConnectionItemMap.value(ssid); p_wlanItem = (WlanListItem*)m_activatedNetListWidget->itemWidget(p_listWidgetItem); } if (nullptr != p_wlanItem) { p_wlanItem->updateWirelessNetSecurity(ssid, secuType); } Q_EMIT secuTypeChange(devName, ssid, secuType); return; } void WlanPage::addDeviceToCombox(QString deviceName) { QString deviceState; int flag = 0; disconnect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &WlanPage::onDeviceComboxIndexChanged); if (getSwitchBtnState()) { if (m_currentDevice.isEmpty()){ m_deviceFrame->hide(); m_currentDevice = deviceName; setDefaultDevice(WIRELESS, m_currentDevice); } else if (m_deviceComboBox->count() == 0 && m_currentDevice != deviceName) { flag=m_deviceState[m_currentDevice]; deviceState=changeDeviceStateText(m_currentDevice,flag); m_deviceComboBox->addItem(deviceState,m_currentDevice); flag=m_deviceState[deviceName]; deviceState=changeDeviceStateText(deviceName,flag); m_deviceComboBox->addItem(deviceState,deviceName); m_deviceFrame->show(); m_deviceComboBox->show(); m_tipsLabel->hide(); } else { flag=m_deviceState[deviceName]; deviceState=changeDeviceStateText(deviceName,flag); m_deviceComboBox->addItem(deviceState,deviceName); } } connect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &WlanPage::onDeviceComboxIndexChanged); return; } void WlanPage::onDeviceAdd(QString deviceName, NetworkManager::Device::Type deviceType) { qDebug() << LOG_FLAG << "currentDevice" << m_currentDevice << "deviceAdd" << deviceName; if (deviceType != NetworkManager::Device::Type::Wifi) { return; } if (m_devList.contains(deviceName)) { return; } if (!m_netDeviceResource->getDeviceManaged(deviceName)) { qWarning() << LOG_FLAG << "couldn not add device" << deviceName << ", it is unmanaged"; return; } if (m_devList.isEmpty()) { m_currentDevice=deviceName; } m_devList << deviceName; setSwitchBtnEnable(true); setSwitchBtnState(getWirelessDevieceUseable()); addDeviceToCombox(deviceName); if (m_currentDevice == deviceName) { initWlanArea(); } Q_EMIT wirelessDeviceStatusChanged(); return; } void WlanPage::deleteDeviceFromCombox(QString deviceName) { disconnect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &WlanPage::onDeviceComboxIndexChanged); if (getSwitchBtnState()) { if (0 == m_devList.count()) { m_deviceFrame->hide(); m_currentDevice = ""; setDefaultDevice(WIRELESS, m_currentDevice); } else if (1 == m_devList.count()) { m_deviceFrame->hide(); m_deviceComboBox->clear(); m_currentDevice = m_devList.at(0); setDefaultDevice(WIRELESS, m_currentDevice); } else { int index = m_deviceComboBox->findData(deviceName); if (-1 != index) { m_deviceComboBox->removeItem(index); m_currentDevice = m_deviceComboBox->currentData().toString(); setDefaultDevice(WIRELESS, m_currentDevice); } } } connect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &WlanPage::onDeviceComboxIndexChanged); return; } void WlanPage::onDeviceRemove(QString deviceName) { if (!m_devList.contains(deviceName)) { return; } qDebug() << "deviceRemove" << deviceName; QString originalDeviceName = m_currentDevice; if (m_joinHiddenWiFiPagePtrMap.contains(deviceName)) { if (m_joinHiddenWiFiPagePtrMap[deviceName] != nullptr) { m_joinHiddenWiFiPagePtrMap[deviceName]->close(); } } m_devList.removeOne(deviceName); deleteDeviceFromCombox(deviceName); if (m_devList.isEmpty()) { setSwitchBtnState(false); setSwitchBtnEnable(false); } if (originalDeviceName == deviceName || m_devList.isEmpty()) { initWlanArea(); } Q_EMIT wirelessDeviceStatusChanged(); } void WlanPage::updateDeviceForCombox(QString oldDeviceName, QString newDeviceName) { QString deviceState; if (m_currentDevice == oldDeviceName) { m_currentDevice = newDeviceName; setDefaultDevice(WIRELESS, m_currentDevice); } int index = m_deviceComboBox->findData(oldDeviceName); if (index != -1) { deviceState=changeDeviceStateText(newDeviceName,m_deviceState[newDeviceName]); m_deviceComboBox->setItemText(index, deviceState); } return; } void WlanPage::onDeviceNameUpdate(QString oldName, QString newName) { if (!m_devList.contains(oldName)) { return; } qDebug()<<"[WlanPage] update device name, old name" << oldName << "new Name" << newName; m_devList.removeOne(oldName); m_devList.append(newName); QString originalDeviceName = m_currentDevice; replaceDeviceConnectState(oldName,newName); updateDeviceForCombox(oldName, newName); if (originalDeviceName != m_currentDevice) { initWlanArea(); } Q_EMIT deviceNameChanged(oldName, newName, WIRELESS); } void WlanPage::onWlanStateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason) { if (newstate == NetworkManager::Device::Failed) { if (reason == NETWORK_ACCESS_DENIED) { //NetworkManager::Device::NetWorkAccessDenied this->showDesktopNotify(tr("The routing end rejects the access of the device"), "networkwrong"); } else if (reason == NETWORK_ACCESS_FULL) { // NetworkManager::Device::NetWorkAccessFull this->showDesktopNotify(tr("The network access at the routing end is full"), "networkwrong"); } } if (getSwitchBtnState() == getWirelessDevieceUseable()) { return ; } setSwitchBtnEnable(true); setSwitchBtnState(getWirelessDevieceUseable()); initDeviceCombox(); initWlanArea(); Q_EMIT wirelessSwitchBtnChanged(getSwitchBtnState()); } void WlanPage::onDeviceManagedChanged(QString deviceName, bool managed) { if (!m_netDeviceResource->checkDeviceType(deviceName, NetworkManager::Device::Type::Wifi)) { return; } if (managed && !m_devList.contains(deviceName)) { //添加新增托管网卡 onDeviceAdd(deviceName, NetworkManager::Device::Type::Wifi); qDebug() << LOG_FLAG << "add managed device" << deviceName; } if (!managed && m_devList.contains(deviceName)) { //删除未托管网卡 onDeviceRemove(deviceName); qDebug() << LOG_FLAG << "delete unmanaged device" << deviceName; } } void WlanPage::onInactivateListWidgetItemChanged(QListWidgetItem *current, QListWidgetItem *previous) { if (previous != nullptr && previous->sizeHint().height() > NORMAL_HEIGHT) { QSize normalSize(previous->sizeHint().width(), NORMAL_HEIGHT); previous->setSizeHint(normalSize); WlanListItem *p_wlanItem = (WlanListItem*)m_inactivatedNetListWidget->itemWidget(previous); if (p_wlanItem != nullptr) { p_wlanItem->setExpanded(false); } } if (current != nullptr) { current->setSelected(false); } } void WlanPage::setInactivateListItemNoSelect() { if (m_inactivatedNetListWidget->currentItem() != nullptr && m_inactivatedNetListWidget->currentItem()->sizeHint().height() > NORMAL_HEIGHT) { WlanListItem *p_wlanItem = (WlanListItem*)m_inactivatedNetListWidget->itemWidget(m_inactivatedNetListWidget->currentItem()); if (p_wlanItem != nullptr) { p_wlanItem->setExpanded(false); } m_inactivatedNetListWidget->currentItem()->setSelected(false); } } void WlanPage::sendApStateChangeSignal(QString uuid, QString ssid, QString deviceName, NetworkManager::ActiveConnection::State state) { bool ret = false; ret = m_connectResource->isApConnection(uuid); if (!ret) { return; } if (state == NetworkManager::ActiveConnection::State::Deactivated) { qDebug() << "[WlanPage] hotspot Deactivated"; Q_EMIT hotspotDeactivated(deviceName, ssid); } else if (state == NetworkManager::ActiveConnection::State::Activated) { QString activePath; QString settingPath; activePath = m_activatedConnectResource->getAcitveConnectionPathByUuid(uuid); settingPath = m_connectResource->getApConnectionPathByUuid(uuid); qDebug() << "[WlanPage] hotspot activated"<showDesktopNotify(tr("WLAN Connected Successfully"), "networkconnected"); } return; } #endif void WlanPage::updateActivatedArea(QString uuid, QString ssid, QString devName) { qDebug() << "[WlanPage] Started activwireless list!"; m_activatedNetListWidget->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection); if(m_wirelessNetItemMap.contains(ssid)) { deleteWirelessItemFormMap(m_wirelessNetItemMap, m_inactivatedNetListWidget, ssid); } if (m_activateConnectionItemMap.contains(ssid)) { qDebug() << "updateActivatedArea exist"<getActiveWirelessNetItem(devName, wirelessNetItem); if (!ret) { qWarning()<<"[WlanPage] get wireless item failed, when update activated connection area."<setFixedHeight(p_listWidgetItem->sizeHint().height()); if (m_inactivatedNetListWidget->count() <= MAX_ITEMS) { m_inactivatedNetListWidget->setFixedWidth(MIN_WIDTH); } qDebug() << "[WlanPage] Stop activwireless list!"; return; } void WlanPage::updateWirelessNetArea(QString uuid, QString ssid, QString devName, QString path) { qDebug() << "[WlanPage] Started wireless list!"; if (m_activateConnectionItemMap.contains(ssid)) { QListWidgetItem *p_listWidgetItem = m_activateConnectionItemMap.value(ssid); if (nullptr == p_listWidgetItem) { qWarning()<< LOG_FLAG <<"wireless item is not exsit, it's ssid is " << ssid; return; } WlanListItem *p_wlanItem = (WlanListItem *)m_activatedNetListWidget->itemWidget(p_listWidgetItem); if (nullptr == p_wlanItem) { qWarning() << LOG_FLAG << "p_wlanItem is null"; return; } if (p_wlanItem->getUuid() == uuid || uuid.isEmpty()) { if (uuid.isEmpty() && p_wlanItem->getPath() != path) { return; } deleteWirelessItemFormMap(m_activateConnectionItemMap, m_activatedNetListWidget, ssid); QListWidgetItem *p_activeListWidgetItem = addEmptyItem(m_activatedNetListWidget); m_activateConnectionItemMap.insert(EMPTY_SSID, p_activeListWidgetItem); m_activatedNetListWidget->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection); m_activatedNetListWidget->setFixedHeight(p_activeListWidgetItem->sizeHint().height()); } } if(m_wirelessNetItemMap.contains(ssid)) { qDebug() << "updateWirelessNetArea exist"<getWifiNetwork(devName, ssid, wirelessNetItem); if (!ret) { qWarning()<<"[WlanPage] get wireless item failed, when update wireless area."; return; } QListWidgetItem *p_listWidgetItem = insertNewItemWithSort(wirelessNetItem, m_inactivatedNetListWidget); m_wirelessNetItemMap.insert(wirelessNetItem.m_NetSsid, p_listWidgetItem); // 更新‘更多’条目,以保证其处于listwidget的最底部 addWlanMoreItem(); if (m_inactivatedNetListWidget->count() <= MAX_ITEMS) { m_inactivatedNetListWidget->setFixedWidth(MIN_WIDTH); } else { m_inactivatedNetListWidget->setFixedWidth(MAX_WIDTH); } qDebug() << "[WlanPage] Stop wireless list!"; return; } void WlanPage::onConnectionStateChanged(QString uuid, NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason) { QString devName, ssid; m_wirelessNetResource->getSsidByUuid(uuid, ssid); m_wirelessNetResource->getDeviceByUuid(uuid, devName); qDebug()<< LOG_FLAG << "Q_EMIT wlanActiveConnectionStateChanged" << devName << ssid << state; Q_EMIT wlanActiveConnectionStateChanged(devName, ssid, uuid, state); if (!m_connectResource->isWirelessConnection(uuid)) { qDebug()<< LOG_FLAG << "it is not wireless connection" << uuid; return; } Q_EMIT this->wlanConnectChanged(state); bool isApConnection = m_connectResource->isApConnection(uuid); if (isApConnection) { sendApStateChangeSignal(uuid, ssid, devName, state); } else { if (state == NetworkManager::ActiveConnection::State::Deactivated && !m_activateConnectionItemMap.contains(ssid)) { qDebug() << "wlan remove before deactivated"; } } updateDeviceConnectState(devName,state); if (!devName.isEmpty() && devName != m_currentDevice) { return; } if (state == NetworkManager::ActiveConnection::State::Deactivating || state == NetworkManager::ActiveConnection::State::Deactivated) { if (!m_activateConnectionItemMap.contains(ssid)) { //check uuid QMap::iterator iter; for(iter = m_activateConnectionItemMap.begin(); iter!= m_activateConnectionItemMap.end(); iter++) { if(iter.value() != nullptr) { QListWidgetItem *p_listWidgetItem = iter.value(); WlanListItem *p_wlanItem = (WlanListItem*)m_activatedNetListWidget->itemWidget(p_listWidgetItem); if (p_wlanItem->getUuid() == uuid) { ssid = p_wlanItem->getSsid(); break; } } } } } qDebug()<< "[WlanPage] wlan state changed, ssid = " << ssid << "; state = " << state << "; reason = " << reason << Q_FUNC_INFO <<__LINE__; if (state == NetworkManager::ActiveConnection::State::Activated) { m_updateStrength = true; updateActivatedArea(uuid, ssid, devName); setNetSpeed->start(REFRESH_NETWORKSPEED_TIMER); if (m_activateConnectionItemMap.contains(ssid)) { QListWidgetItem *p_listWidgetItem = m_activateConnectionItemMap.value(ssid); updateWlanItemState(m_activatedNetListWidget, p_listWidgetItem, Activated); } } else if (state == NetworkManager::ActiveConnection::State::Deactivated) { m_updateStrength = true; if (devName.isEmpty()) { devName = m_currentDevice; } updateWirelessNetArea(uuid, ssid, devName,""); setNetSpeed->stop(); if (m_wirelessNetItemMap.contains(ssid)) { QListWidgetItem *p_listWidgetItem = m_wirelessNetItemMap.value(ssid); updateWlanItemState(m_inactivatedNetListWidget, p_listWidgetItem, Deactivated); } } else if (state == NetworkManager::ActiveConnection::State::Deactivating){ m_updateStrength = false; if (m_activateConnectionItemMap.contains(ssid)) { QListWidgetItem *p_listWidgetItem = m_activateConnectionItemMap.value(ssid); updateWlanItemState(m_activatedNetListWidget, p_listWidgetItem, Deactivating); } } else if (state == NetworkManager::ActiveConnection::State::Activating) { m_updateStrength = false; if (m_wirelessNetItemMap.contains(ssid)) { QListWidgetItem *p_listWidgetItem = m_wirelessNetItemMap.value(ssid); updateWlanItemState(m_inactivatedNetListWidget, p_listWidgetItem, Activating); } } return; } void WlanPage::onItemHeightChanged(const bool isExpanded, const QString &ssid) { if (!m_wirelessNetItemMap.contains(ssid)) { return; } QListWidgetItem *p_listWidgetItem = m_wirelessNetItemMap.value(ssid); qDebug()<sizeHint().height(); int width = p_listWidgetItem->sizeHint().width(); if (isExpanded) { if (m_expandedItem != p_listWidgetItem) { onInactivateListWidgetItemChanged(p_listWidgetItem, m_expandedItem); qDebug()<setSizeHint(expandedSize); } m_inactivatedNetListWidget->scrollToItem(p_listWidgetItem, QAbstractItemView::QAbstractItemView::EnsureVisible); } else { m_expandedItem = nullptr; if (height > NORMAL_HEIGHT) { qDebug()<setSizeHint(normalSize); } } return; } void WlanPage::onDeviceComboxIndexChanged(int currentIndex) { qDebug() << "onDeviceComboxIndexChanged"; if (!m_deviceComboBox || currentIndex < 0) { return; } m_currentDevice = m_deviceComboBox->itemData(currentIndex).toString(); setDefaultDevice(WIRELESS, m_currentDevice); initWlanArea(); Q_EMIT timeToUpdate(); return; } //申请触发扫描,初始化执行&定时执行 void WlanPage::requestScan() { if (!m_wirelessConnectOpreation) { qWarning() << "[WlanPage]Scan failed! m_wirelessConnectOpreation is nullptr!" << Q_FUNC_INFO << __LINE__; return; } m_wirelessConnectOpreation->requestWirelessScan(); return; } void WlanPage::onHiddenWlanClicked() { qDebug() << "[wlanPage] AddHideWifi Clicked! " << Q_FUNC_INFO << __LINE__ ; showHiddenWlanPage(m_currentDevice); } void WlanPage::showControlCenter() { qDebug() << LOG_FLAG <<"show control center"; QProcess process; process.startDetached("ukui-control-center", QStringList() << "-m" << "wlanconnect"); return; } void WlanPage::onWifiEnabledChanged(bool isWifiOn) { TabPage::stopLoading(); //监听外部命令导致wifi状态变化,更新界面 if (m_usdInterface == nullptr || !m_usdInterface->isValid()) { return; } QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{ m_usdInterface->asyncCall("SetWifiState", isWifiOn), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [isWifiOn] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("usd set offline mode failed: ") + watcher->error().message(); qWarning()<deleteLater(); }); return; } void WlanPage::refreshActiveConnectionIcon(QString ssid, const int &signal) { QListWidgetItem *p_listWidgetItem = m_activateConnectionItemMap.value(ssid); if (p_listWidgetItem) { WlanListItem *p_wlanItem = (WlanListItem *)m_activatedNetListWidget->itemWidget(p_listWidgetItem); if (nullptr != p_wlanItem) { p_wlanItem->setSignalStrength(signal); return; } } } void WlanPage::onRefreshIconTimer() { if (!m_updateStrength) { return; } Q_EMIT timeToUpdate(); if(!this->isVisible()) { return; } //qDebug() << "onRefreshIconTimer"; if (m_expandedItem) { qDebug()<< LOG_FLAG << "Has expanded item and forbid refresh wifi strength" << Q_FUNC_INFO << __LINE__; return; } QList wlanList; if (!m_wirelessNetResource->getDeviceWifiNetwork(m_currentDevice, wlanList)) { return; } //解决没有无线设备且m_currentDevice不清空的情况下,m_activateConnectionItemMap为空造成的段错误 if (m_activateConnectionItemMap.isEmpty()) { return ; } QString activateSsid; KyWirelessNetItem wirelessNetItem; bool ret = m_wirelessNetResource->getActiveWirelessNetItem(m_currentDevice, wirelessNetItem); if (ret == true) { activateSsid = wirelessNetItem.m_NetSsid; } int sortRow = 0; for (int index = 0; index < wlanList.length(); index++) { KyWirelessNetItem sortItem = wlanList.at(index); QString sortSsid = sortItem.m_NetSsid; //应该在第currentRow行的新的WiFi名称 //qDebug()<< LOG_FLAG << "sort ssid"<< sortSsid << "active ssid" << activateSsid << "sort row"<< sortRow; if (sortSsid == activateSsid) { //排除已连接WiFi int signalStrength = 0; QString uni, secuType; m_netDeviceResource->getActiveConnectionInfo(m_currentDevice, signalStrength, uni, secuType); refreshActiveConnectionIcon(activateSsid, signalStrength); continue; } QListWidgetItem *p_listWidgetItem = m_inactivatedNetListWidget->item(sortRow); if (p_listWidgetItem) { WlanListItem *p_wlanItem = (WlanListItem *)m_inactivatedNetListWidget->itemWidget(p_listWidgetItem); if (nullptr == p_wlanItem) { qDebug() << LOG_FLAG << "p_wlanItem is null continue"; continue;//暂时先保持continue,后续讨论是否使用break直接跳出循环 } // 该item是‘更多’条目,不需要更新 if (WMI_OB_NAME == p_wlanItem->objectName()) { qDebug() << LOG_FLAG << "p_wlanItem is WlanMoreItem"; continue; } if (sortSsid == p_wlanItem->getSsid()) { p_wlanItem->setSignalStrength(sortItem.m_signalStrength); sortRow++; continue; } QListWidgetItem *p_sortListWidgetItem = m_wirelessNetItemMap.value(sortSsid); if (p_sortListWidgetItem) { WlanListItem *p_wlanItem = (WlanListItem *)m_inactivatedNetListWidget->itemWidget(p_listWidgetItem); if (p_wlanItem == nullptr) { continue; } if (Deactivated != p_wlanItem->getConnectionState()) { continue; } int takeRow = m_inactivatedNetListWidget->row(p_sortListWidgetItem); m_inactivatedNetListWidget->takeItem(takeRow); WlanListItem *p_sortWlanItem = new WlanListItem(sortItem, m_currentDevice, m_showWifi6Plus); connect(p_sortWlanItem, &WlanListItem::itemHeightChanged, this, &WlanPage::onItemHeightChanged); connect(p_sortWlanItem, &WlanListItem::detailShow, this, &WlanPage::showDetailPage); m_inactivatedNetListWidget->insertItem(sortRow, p_sortListWidgetItem); m_inactivatedNetListWidget->setItemWidget(p_sortListWidgetItem, p_sortWlanItem); updateWlanItemState(m_inactivatedNetListWidget, p_sortListWidgetItem, Deactivated); sortRow++; continue; } } QListWidgetItem *p_newListWidgetItem = insertNewItem(sortItem, m_inactivatedNetListWidget, sortRow); m_wirelessNetItemMap.insert(sortItem.m_NetSsid, p_newListWidgetItem); updateWlanItemState(m_inactivatedNetListWidget, p_listWidgetItem, Deactivated); sortRow++; } return; } //for dbus void WlanPage::getWirelessList(QString devName, QList &list) { KyWirelessNetItem data; QList wlanList; if (!m_wirelessNetResource->getDeviceWifiNetwork(devName, wlanList)) { return; } QString activeSsid ; //先是已连接 if (m_wirelessNetResource->getActiveWirelessNetItem(devName, data)) { qDebug() << "find " << devName; QString ssid =""; m_wirelessNetResource->getSsidByUuid(data.m_connectUuid, ssid); if (m_wirelessNetResource->getWifiNetwork(devName, ssid, data)) { int category = 0; int signalStrength; QString uni,secuType; if (m_netDeviceResource->getActiveConnectionInfo(devName, signalStrength, uni, secuType)) { category = data.getCategory(uni); } if (!m_showWifi6Plus && category == 2) { category = 1; } list.append(QStringList() << data.m_NetSsid //1 << QString::number(signalStrength) //2 << secuType //3 << data.m_connectUuid //4 << (m_connectResource->isApConnection(data.m_connectUuid) ? IsApConnection : NotApConnection) //5 << QString::number(category) //6 << QString::number(data.m_isConfigured) //7 << QString::number(data.m_frequency) //8 << (data.m_isMix ? IsApConnection : NotApConnection) //9 ); // activeSsid = data.m_NetSsid; } else { list.append(QStringList("--")); } } else { list.append(QStringList("--")); } //未连接 Q_FOREACH (auto itemData, wlanList) { if (itemData.m_NetSsid == activeSsid) { continue; } int category = 0; category = itemData.getCategory(itemData.m_uni); if (!m_showWifi6Plus && category == 2) { category = 1; } list.append(QStringList()<isApConnection(itemData.m_connectUuid) ? IsApConnection : NotApConnection) << QString::number(category) << QString::number(itemData.m_isConfigured) << QString::number(itemData.m_frequency) << (itemData.m_isMix ? IsApConnection : NotApConnection) ); } } //for dbus bool WlanPage::getWirelessSwitchBtnState() { return getSwitchBtnState(); } //开启热点 void WlanPage::activeWirelessAp(const QString apName, const QString apPassword, const QString wirelessBand, const QString apDevice) { QString uuid(""); QList apConnectItemList; m_connectResource->getApConnections(apConnectItemList); if (!apConnectItemList.isEmpty()) { uuid = apConnectItemList.at(0)->m_connectUuid; } m_wirelessConnectOpreation->activeWirelessAp(uuid, apName, apPassword, apDevice, wirelessBand); } //断开热点 void WlanPage::deactiveWirelessAp(const QString apName, const QString uuid) { if (!uuid.isEmpty()) { m_wirelessConnectOpreation->deactiveWirelessAp(apName, uuid); } } void WlanPage::getStoredApInfo(QStringList &list) { list.clear(); QList apConnectItemList; m_connectResource->getApConnections(apConnectItemList); if (!apConnectItemList.isEmpty()) { list << apConnectItemList.at(0)->m_connectSsid; list << apConnectItemList.at(0)->m_password; list << apConnectItemList.at(0)->m_ifaceName; list << (apConnectItemList.at(0)->m_isActivated? "true":"false"); list << apConnectItemList.at(0)->m_connectUuid; list << apConnectItemList.at(0)->m_band; } } void WlanPage::getApConnectionPath(QString &path, QString uuid) { path.clear(); path = m_connectResource->getApConnectionPathByUuid(uuid); } void WlanPage::getActiveConnectionPath(QString &path, QString uuid) { path.clear(); path = m_activatedConnectResource->getAcitveConnectionPathByUuid(uuid); } void WlanPage::getApInfoBySsid(QString devName, QString ssid, QStringList &list) { list.clear(); QList apConnectItemList; m_connectResource->getApConnections(apConnectItemList); for (int i = 0; i < apConnectItemList.size(); i++) { if (apConnectItemList.at(i)->m_connectSsid == ssid && apConnectItemList.at(i)->m_ifaceName == devName) { list << apConnectItemList.at(i)->m_password; list << apConnectItemList.at(i)->m_band; } } return; } void WlanPage::activateWirelessConnection(const QString& devName, const QString& ssid) { KyWirelessNetItem wirelessNetItem; if (!m_wirelessNetResource->getWifiNetwork(devName, ssid, wirelessNetItem)) { qDebug() << "[WlanPage] no such wifi " << ssid << " in " << devName; return; } if (devName != m_currentDevice) { int index = m_deviceComboBox->findData(devName); if (index >= 0) { m_deviceComboBox->setCurrentIndex(index); } else { qDebug() << "[WlanPage]activateWirelessConnection no such " << devName; return; } } QListWidgetItem *p_listWidgetItem = nullptr; WlanListItem *p_wlanItem = nullptr; if (m_wirelessNetItemMap.contains(ssid)) { //Q_EMIT showMainWindow(WLAN_PAGE_INDEX);//mqtest p_listWidgetItem = m_wirelessNetItemMap.value(ssid); p_wlanItem = (WlanListItem*)m_inactivatedNetListWidget->itemWidget(p_listWidgetItem); m_inactivatedNetListWidget->scrollToItem(p_listWidgetItem, QAbstractItemView::EnsureVisible); QMouseEvent *event = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QApplication::postEvent(p_wlanItem, event); } else { qDebug() << "[WlanPage]activateWirelessConnection no such " << ssid << "in" << devName; } return; } void WlanPage::deactivateWirelessConnection(const QString& devName, const QString& ssid) { KyWirelessNetItem wirelessNetItem; if (!m_wirelessNetResource->getWifiNetwork(devName, ssid, wirelessNetItem)) { qDebug() << "[WlanPage] no such wifi " << ssid << " in " << devName; return; } if (!m_connectResource->isActivatedConnection(wirelessNetItem.m_connectUuid)) { qDebug()<<"[WlanPage]"<deActivateWirelessConnection(wirelessNetItem.m_connName, wirelessNetItem.m_connectUuid); return; } void WlanPage::onMainWindowVisibleChanged(const bool &visible) { qDebug() << "[WlanPage] Received signal of mainwindow visible changed. cur_state = " << visible << Q_FUNC_INFO << __LINE__; //开关关闭状态不刷新 if (visible && getSwitchBtnState()) { //打开页面时先触发一次扫描,然后定时扫描wifi热点和刷新icon requestScan(); m_scanTimer->start(AP_SCAN_INTERVAL); onRefreshIconTimer(); } else { //界面关闭的时候,停止wifi扫描和刷新 m_scanTimer->stop(); qDebug() << "wlanpage not visible"; showNonePwd(); } return; } void WlanPage::onWlanPageVisibleChanged(int index) { if (index == LAN_PAGE_INDEX) { qDebug() << "wlanpage not visible"; showNonePwd(); } m_inactivatedNetListWidget->setCurrentIndex(QModelIndex()); // 去除item选中效果 } void WlanPage::showNonePwd() { QMap::iterator iter; for(iter=m_wirelessNetItemMap.begin();iter!= m_wirelessNetItemMap.end();iter++) { if(iter.value() != nullptr) { QListWidgetItem *p_listWidgetItem = iter.value(); WlanListItem *p_wlanItem = (WlanListItem*)m_inactivatedNetListWidget->itemWidget(p_listWidgetItem); p_wlanItem->forgetPwd(); p_wlanItem->setExpanded(false); } } return; } void WlanPage::showRate() { //定时获取网速 setNetSpeed = new QTimer(this); setNetSpeed->setTimerType(Qt::PreciseTimer); connect(setNetSpeed, &QTimer::timeout, [&](){ onSetNetSpeed(m_activatedNetListWidget, m_activateConnectionItemMap.contains(EMPTY_SSID), m_currentDevice); }); } void WlanPage::showHiddenWlanPage(QString devName) { if (m_joinHiddenWiFiPagePtrMap.contains(devName)) { if (m_joinHiddenWiFiPagePtrMap[devName] != nullptr) { qDebug() << "[WlanPage] showAddOtherWlanWidget" << devName << "already create,just raise"; m_joinHiddenWiFiPagePtrMap[devName]->activateWindow(); return; } } JoinHiddenWiFiPage *hiddenWiFi =new JoinHiddenWiFiPage(devName); connect(hiddenWiFi, &JoinHiddenWiFiPage::hiddenWiFiPageClose, [&](QString interfaceName){ if (m_joinHiddenWiFiPagePtrMap.contains(interfaceName)) { m_joinHiddenWiFiPagePtrMap[interfaceName] = nullptr; } }); connect(hiddenWiFi, &JoinHiddenWiFiPage::showWlanList, this, &WlanPage::showMainWindow); m_joinHiddenWiFiPagePtrMap.insert(devName, hiddenWiFi); hiddenWiFi->show(); } void WlanPage::showDetailPage(QString devName, QString ssid) { KyWirelessNetItem wirelessNetItem; if (!m_wirelessNetResource->getWifiNetwork(devName, ssid, wirelessNetItem)) { qDebug()<<"[WlanPage] " << ssid << " is missing when showDetailPage"; return; } bool isActive = m_connectResource->isActivatedConnection(wirelessNetItem.m_connectUuid); if (m_wlanPagePtrMap.contains(devName) && m_wlanPagePtrMap[devName].contains(ssid)) { if (m_wlanPagePtrMap[devName][ssid] != nullptr) { qDebug() << "[WlanPage] ShowWlanDetailPage" << ssid << "already create,just raise"; m_wlanPagePtrMap[devName][ssid]->activateWindow(); return; } } int category = 0; category = wirelessNetItem.getCategory(wirelessNetItem.m_uni); NetDetail *netDetail = new NetDetail(devName, ssid, wirelessNetItem.m_connectUuid, isActive, true, !wirelessNetItem.m_isConfigured,category); m_wlanPagePtrMap[devName].insert(ssid, netDetail); connect(netDetail, &NetDetail::detailPageClose, [&](QString deviceName, QString wlanSsid){ if (m_wlanPagePtrMap.contains(deviceName) && m_wlanPagePtrMap[deviceName].contains(wlanSsid)) { m_wlanPagePtrMap[deviceName][wlanSsid] = nullptr; } }); netDetail->show(); return; } void WlanPage::showAddOtherPage(QString devName) { showHiddenWlanPage(devName); } bool WlanPage::checkWlanStatus(NetworkManager::ActiveConnection::State state) { return m_activatedConnectResource->checkWirelessStatus(state); } bool WlanPage::checkInternetLoading() { return m_activatedConnectResource->checkInternetLoading(); } void WlanPage::setWirelessSwitchEnable(bool enable) { qDebug() << "dbus setWirelessSwitchEnable = " << enable << __LINE__; setWirelessEnable(enable); } void WlanPage::getWirelessDeviceCap(QMap &map) { for (int i = 0; i < m_devList.size(); ++i) { QString devName = m_devList.at(i); map.insert(devName, m_netDeviceResource->getWirelessDeviceCapability(devName)); } } void WlanPage::getConnectivity(NetworkManager::Connectivity &connectivity) { m_connectResource->getConnectivity(connectivity); } /** * @brief WlanPage::addWlanMoreItem * 添加‘更多网络’的条目 */ void WlanPage::addWlanMoreItem() { if (m_hiddenItem) { m_inactivatedNetListWidget->takeItem(m_inactivatedNetListWidget->row(m_hiddenItem)); delete m_hiddenItem; m_hiddenItem = nullptr; } if (m_hiddenWlanWidget) { m_hiddenWlanWidget->setParent(nullptr); delete m_hiddenWlanWidget; m_hiddenWlanWidget = nullptr; } m_hiddenWlanWidget = new WlanMoreItem(this); connect(m_hiddenWlanWidget, &WlanMoreItem::hiddenWlanClicked, this, &WlanPage::onHiddenWlanClicked); m_hiddenWlanWidget->setFixedHeight(NORMAL_HEIGHT); m_hiddenItem = new QListWidgetItem(m_inactivatedNetListWidget); m_hiddenItem->setFlags(m_hiddenItem->flags() & (~Qt::ItemIsSelectable)); m_hiddenItem->setSizeHint(QSize(m_inactivatedNetListWidget->width(), m_hiddenWlanWidget->height())); m_inactivatedNetListWidget->addItem(m_hiddenItem); m_inactivatedNetListWidget->setItemWidget(m_hiddenItem, m_hiddenWlanWidget); m_hiddenWlanWidget->m_freq->hide(); return; } int WlanPage::getActivateWifiSignal(QString devName) { return m_activatedConnectResource->getActivateWifiSignal(devName); } void WlanPage::getWirelssDeviceConnectState(QMap &map) { map.clear(); if (m_devList.isEmpty()) { return; } for (const auto devname : m_devList) { KyWirelessNetItem wirelessNetItem; if (!m_netDeviceResource->getDeviceManaged(devname)) { continue; } if (m_wirelessNetResource->getActiveWirelessNetItem(devname, wirelessNetItem)) { map.insert(devname, QString(tr("Connected: ")) + wirelessNetItem.m_NetSsid); } else { map.insert(devname, tr("Not Connected")); } } } void WlanPage::initWirelssDeviceConnectState() { m_deviceState.clear(); if (m_devList.isEmpty()) { return; } for (const auto devname : m_devList) { KyWirelessNetItem wirelessNetItem; if (!m_netDeviceResource->getDeviceManaged(devname)) { continue; } if (m_wirelessNetResource->getActiveWirelessNetItem(devname, wirelessNetItem)) { m_deviceState.insert(devname,NetworkManager::ActiveConnection::Activated); } else { m_deviceState.insert(devname,NetworkManager::ActiveConnection::Deactivated); } } } void WlanPage::getWirelssDeviceConnect(QMap &map) { map.clear(); if (m_devList.isEmpty()) { return; } for (const auto devname : m_devList) { KyWirelessNetItem wirelessNetItem; if (!m_netDeviceResource->getDeviceManaged(devname)) { continue; } if (m_wirelessNetResource->getActiveWirelessNetItem(devname, wirelessNetItem)) { map.insert(devname, wirelessNetItem.m_connectUuid); } } } void WlanPage::deactivateWirelessConnectionWithUuid(const QString devName, const QString uuid) { if (!m_connectResource->isActivatedConnection(uuid)) { qDebug()<<"[WlanPage]"<deActivateWirelessConnection(devName,uuid); return; } void WlanPage::deleteWirelessConnect(const QString &connectUuid) { m_wirelessConnectOpreation->deleteWirelessConnect(connectUuid); } kylin-nm/src/frontend/tab-pages/lanpage.h0000664000175000017500000001755015167651420017306 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef LANPAGE_H #define LANPAGE_H #include "divider.h" #include #include #include #include #include #include #include #include "list-items/listitem.h" #include "list-items/lanlistitem.h" #include "tab-pages/tabpage.h" #include #define SYSTEM_DBUS_SERVICE "com.kylin.network.qt.systemdbus" #define SYSTEM_DBUS_PATH "/" #define SYSTEM_DBUS_INTERFACE "com.kylin.network.interface" class LanListItem; class LanPage : public TabPage { Q_OBJECT public: explicit LanPage(QWidget *parent = nullptr); ~LanPage(); //for dbus void getWiredList(QString devName, QList &list); void activateWired(const QString& devName, const QString& connUuid); void deactivateWired(const QString& devName, const QString& connUuid, bool concise = false); void deleteWiredConnect(const QString& connUuid); void showDetailPage(QString devName, QString uuid); void setWiredDeviceEnable(const QString& devName, bool enable); int getDeviceConnectivity(const QString deviceName); bool getCableStateByDevice(const QString &deviceName); bool lanIsConnected(); void getWiredDeviceConnectState(QMap &map); bool getWiredEnabledState() { return m_wiredConnectOperation->getWiredEnabled(); } void setWiredEnabledState(bool enable) { m_wiredConnectOperation->setWiredEnabled(enable); } void getWiredDeviceConnect(QMap &map); void setWiredDeviceAutoconnect(const QString& devName, bool state); protected: bool eventFilter(QObject *watched, QEvent *event); private: void initLanDevice(); void initUI(); void initLanArea(); void initNetSwitch(); void initLanDeviceState(); void initLanDeviceConnectState(); void initDeviceCombox(); void updateDeviceCombox(QString oldDeviceName, QString newDeviceName); void deleteDeviceFromCombox(QString deviceName); void addDeviceForCombox(QString deviceName); QListWidgetItem *insertNewItem(KyConnectItem *itemData, QListWidget *listWidget); QListWidgetItem *addNewItem(KyConnectItem *itemData, QListWidget *listWidget); bool removeConnectionItem(QMap &connectMap, QListWidget *lanListWidget, QString path); void getEnabledDevice(QStringList &enableDeviceList); void getDisabledDevices(QStringList &disableDeviceList); void constructConnectionArea(); void constructActiveConnectionArea(); void updateConnectionArea(KyConnectItem *p_newItem); void updateActivatedConnectionArea(KyConnectItem *p_newItem); void updateConnectionState(QMap &connectMap, QListWidget *lanListWidget, QString uuid, ConnectState state); QString getConnectionDevice(QString uuid); void updateActiveConnectionProperty(KyConnectItem *p_connectItem); void updateConnectionProperty(KyConnectItem *p_connectItem); void sendLanUpdateSignal(KyConnectItem *p_connectItem); void sendLanAddSignal(KyConnectItem *p_connectItem); void sendLanStateChangeSignal(QString uuid, ConnectState state); void addEmptyConnectItem(QMap &connectMap, QListWidget *lanListWidget); void clearConnectionMap(QMap &connectMap, QListWidget *lanListWidget); void deleteConnectionMapItem(QMap &connectMap, QListWidget *lanListWidget, QString uuid); void updateCurrentDevice(QString deviceName); void showRate(); void updateActivatedNetFrame(QString deviceName); QString strConnectivityFromType(int type); void showBallonTip(); void connectFontGsetting(); public Q_SLOTS: void onMainWindowVisibleChanged(const bool &visible); Q_SIGNALS: void lanAdd(QString devName, QStringList info); void lanRemove(QString dbusPath); void lanUpdate(QString devName, QStringList info); void lanActiveConnectionStateChanged(QString interface, QString uuid, int status); void lanConnectChanged(int state); void showLanRate(QListWidget *widget, QMap &map, QString dev, bool isLan); void wiredEnabledChanged(bool status); void wiredMainSwitchBtnChanged(bool); private Q_SLOTS: void onConnectionStateChange(QString uuid, NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason); void onAddConnection(QString uuid); void onRemoveConnection(QString path); void onUpdateConnection(QString uuid); void onDeviceAdd(QString deviceName, NetworkManager::Device::Type deviceType); void onDeviceRemove(QString deviceName); void onDeviceNameUpdate(QString oldName, QString newName); void onDeviceManagedChange(QString deviceName, bool managed); void onDeviceCarriered(QString deviceName, bool pluged); void onDeviceComboxIndexChanged(int currentIndex); void onShowControlCenter(); void onWiredEnabledChanged(bool); void onDeviceConnectivityChanged(QString devName, NetworkManager::Connectivity connectivity); void onShowKylinNetworkCheck(); void onLanStateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason); void onSysWiredMainSwitchChanged(bool); void onSysDeviceSwitchChanged(const QString&); private: QListWidget * m_activatedLanListWidget = nullptr; QListWidget * m_inactivatedLanListWidget = nullptr; KyNetworkDeviceResourse *m_deviceResource = nullptr; KyWiredConnectOperation *m_wiredConnectOperation = nullptr; KyActiveConnectResourse *m_activeResourse = nullptr; //激活的连接 KyConnectResourse *m_connectResourse = nullptr; //未激活的连接 QMap m_inactiveConnectionMap; QMap m_activeConnectionMap; QString m_currentDeviceName; QStringList m_devList; QStringList m_enableDeviceList; QStringList m_disableDeviceList; QGSettings *m_switchGsettings = nullptr; QMap m_lanPagePtrMap; bool m_showedNetTipFlag = false; KBallonTip *m_netTip = nullptr; inline void setSwitchBtnState(bool state) { if (m_netSwitch != nullptr) { m_netSwitch->setChecked(state); } } inline bool getSwitchBtnState() { if (m_netSwitch != nullptr) { return m_netSwitch->isChecked(); } } inline void setSwitchBtnEnable(bool state) { if (m_netSwitch != nullptr) { m_netSwitch->setEnabled(state); } } inline bool getSwitchBtnEnable() { if (m_netSwitch != nullptr) { return m_netSwitch->isEnabled(); } } QDBusInterface *m_pSysBusIntfs; Q_SIGNALS: void deviceConnectivityChanged(QString devName, int connectivityType); }; #endif // LANPAGE_H kylin-nm/src/frontend/tab-pages/lanpage.cpp0000775000175000017500000017653315167651420017653 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "lanpage.h" #include #include "kwindowsystem_export.h" #include #include #include "windowmanager/windowmanager.h" #define MAIN_LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_SPACING 0 #define TITLE_FRAME_HEIGHT 52 #define TITLE_LAYOUT_MARGINS 24,0,24,0 #define LAN_LIST_SPACING 0 #define TEXT_MARGINS 16,0,0,0 #define SETTINGS_LAYOUT_MARGINS 24,16,24,16 #define TRANSPARENT_COLOR QColor(0,0,0,0) #define ITEM_HEIGHT 48 #define LOG_FLAG "[LanPage]" const QString EMPTY_CONNECT_UUID = "emptyconnect"; const QString WIRED_SWITCH = "wiredswitch"; LanPage::LanPage(QWidget *parent) : TabPage(parent) { m_activeResourse = new KyActiveConnectResourse(this); m_connectResourse = new KyConnectResourse(this); m_deviceResource = new KyNetworkDeviceResourse(this); m_wiredConnectOperation = new KyWiredConnectOperation(this); m_netTip = new KBallonTip(); initUI(); initLanDevice(); initNetSwitch(); initLanDeviceState(); initLanDeviceConnectState();//需在initDeviceCombox前初始化 initDeviceCombox(); initLanArea(); m_pSysBusIntfs = new QDBusInterface(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, QDBusConnection::systemBus()); if (m_pSysBusIntfs->isValid()) { QDBusConnection::systemBus().connect(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, "sysWiredMainSwitchChanged", this, SLOT(onSysWiredMainSwitchChanged(bool))); QDBusConnection::systemBus().connect(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, "sysDeviceSwitchChanged", this, SLOT(onSysDeviceSwitchChanged(const QString&))); } connect(m_activeResourse, &KyActiveConnectResourse::stateChangeReason, this, &LanPage::onConnectionStateChange); connect(m_activeResourse, &KyActiveConnectResourse::activeConnectRemove, this, [=] (QString activeConnectUuid) { sendLanStateChangeSignal(activeConnectUuid,Deactivated); } ); connect(m_connectResourse, &KyConnectResourse::connectionAdd, this, &LanPage::onAddConnection); connect(m_connectResourse, &KyConnectResourse::connectionRemove, this, &LanPage::onRemoveConnection); connect(m_connectResourse, &KyConnectResourse::connectionUpdate, this, &LanPage::onUpdateConnection); connect(m_connectResourse, &KyConnectResourse::needShowDesktop, this, [=](QString ip) { this->showDesktopNotify(ip + tr("conflict, unable to connect to the network normally!"), QString()); }); connect(m_deviceResource, &KyNetworkDeviceResourse::deviceAdd, this, &LanPage::onDeviceAdd); connect(m_deviceResource, &KyNetworkDeviceResourse::deviceRemove, this, &LanPage::onDeviceRemove); connect(m_deviceResource, &KyNetworkDeviceResourse::deviceNameUpdate, this, &LanPage::onDeviceNameUpdate); connect(m_deviceResource, &KyNetworkDeviceResourse::carrierChanage, this, &LanPage::onDeviceCarriered); connect(m_deviceResource, &KyNetworkDeviceResourse::deviceManagedChange, this, &LanPage::onDeviceManagedChange); connect(m_deviceResource, &KyNetworkDeviceResourse::deviceConnectivityChanged, this, &LanPage::onDeviceConnectivityChanged); connect(m_deviceResource, &KyNetworkDeviceResourse::stateChanged, this, &LanPage::onLanStateChanged); connect(m_wiredConnectOperation, &KyWiredConnectOperation::activateConnectionError, this, &LanPage::activateFailed); connect(m_wiredConnectOperation, &KyWiredConnectOperation::deactivateConnectionError, this, &LanPage::deactivateFailed); connect(m_wiredConnectOperation, &KyWiredConnectOperation::wiredEnabledChanged, this, &LanPage::onWiredEnabledChanged); connect(m_netSwitch, &KSwitchButton::clicked, this, [=](bool checked) { TabPage::startLoading(); if (getSwitchBtnEnable()) { setSwitchBtnState(!checked); if(!checkTimeIsOut(500)) return; m_wiredConnectOperation->setWiredEnabled(checked); // 如果关闭有线总开关的时候,网卡设备已经全部关闭,则不转圈 if (0 == m_enableDeviceList.count()) { TabPage::stopLoading(); } } }); connectFontGsetting(); m_lanPagePtrMap.clear(); qDBusRegisterMetaType>(); } LanPage::~LanPage() { if (m_netTip != nullptr) { delete m_netTip; m_netTip = nullptr; } if (m_pSysBusIntfs != nullptr) { delete m_pSysBusIntfs; m_pSysBusIntfs = nullptr; } } void LanPage::initLanDevice() { m_devList.clear(); m_deviceResource->getNetworkDeviceList(NetworkManager::Device::Type::Ethernet, m_devList); m_currentDeviceName = getDefaultDeviceName(WIRED); bool getDefault = !m_currentDeviceName.isEmpty(); if (getDefault) { if (m_deviceResource->wiredDeviceIsCarriered(m_currentDeviceName)) { return; } } QList activedList; for (int index = 0; index < m_devList.size(); ++index) { m_activeResourse->getActiveConnectionList(m_devList.at(index), NetworkManager::ConnectionSettings::Wired, activedList); m_activeResourse->getActiveConnectionList(m_devList.at(index), NetworkManager::ConnectionSettings::Pppoe, activedList); if (!activedList.isEmpty()) { m_currentDeviceName = m_devList.at(index); if (!getDefault) { setDefaultDevice(WIRED, m_currentDeviceName); } return; } } for (int index = 0; index < m_devList.size(); ++index) { if (m_deviceResource->wiredDeviceIsCarriered(m_devList.at(index))) { m_currentDeviceName = m_devList.at(index); if (!getDefault) { setDefaultDevice(WIRED, m_currentDeviceName); } return; } } return; } void LanPage::initLanDeviceState() { m_disableDeviceList.clear(); m_enableDeviceList.clear(); for (int index = 0; index < m_devList.count(); ++index) { QString deviceName = m_devList.at(index); if (m_deviceResource->getDeviceManaged(deviceName)) { m_enableDeviceList<getWiredEnabled(); //从3.0升级上来 先读取老的配置文件来保证和升级前状态一致 bool oldVersionState = true; if (getOldVersionWiredSwitchState(oldVersionState)) { if (wiredEnable != oldVersionState) { wiredEnable = oldVersionState; m_wiredConnectOperation->setWiredEnabled(oldVersionState); } } if (m_devList.count() == 0) { qDebug() << "[wiredSwitch]:init not enable when no device"; setSwitchBtnState(false); setSwitchBtnEnable(false); } qDebug() << "[wiredSwitch]:init state:" << wiredEnable; setSwitchBtnState(wiredEnable); } void LanPage::getEnabledDevice(QStringList &enableDeviceList) { if (m_devList.isEmpty()) { qDebug()<<"[LanPage] there is not wired device."; return; } for (int index = 0; index < m_devList.size(); ++index) { if (m_deviceResource->getDeviceManaged(m_devList.at(index))) { enableDeviceList << m_devList.at(index); } } } void LanPage::getDisabledDevices(QStringList &disableDeviceList) { if (m_devList.isEmpty()) { qDebug()<<"[LanPage] there is not wired device."; return; } for (int index = 0; index < m_devList.size(); ++index) { if (!m_deviceResource->getDeviceManaged(m_devList.at(index))) { disableDeviceList << m_devList.at(index); } } } void LanPage::initDeviceCombox() { QString deviceState = ""; int flag = 0; //TODO 获取设备列表,单设备时隐藏下拉框,多设备时添加到下拉框;m_devList记录插入的所有设备,deviceMap记录设备状态 disconnect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &LanPage::onDeviceComboxIndexChanged); m_deviceComboBox->clear(); if (getSwitchBtnState()) { int enableDeviceCount = m_enableDeviceList.count(); if (enableDeviceCount > 1) { for (int index = 0; index < enableDeviceCount; ++index) { flag=m_deviceState[m_enableDeviceList.at(index)]; deviceState=changeDeviceStateText(m_enableDeviceList.at(index),flag); m_deviceComboBox->addItem(deviceState,m_enableDeviceList.at(index)); } m_deviceFrame->show(); m_tipsLabel->hide(); m_deviceComboBox->show(); if (m_currentDeviceName != m_deviceComboBox->currentData().toString()) { if (m_enableDeviceList.contains(m_currentDeviceName)) { flag=m_deviceState[m_currentDeviceName]; deviceState=changeDeviceStateText(m_currentDeviceName,flag); m_deviceComboBox->setCurrentText(deviceState); } else { m_currentDeviceName = m_deviceComboBox->currentData().toString(); } } } else if (enableDeviceCount == 1) { m_deviceFrame->hide(); if (m_currentDeviceName != m_enableDeviceList.at(0)) { m_currentDeviceName = m_enableDeviceList.at(0); } } else { m_deviceFrame->show(); m_deviceComboBox->hide(); m_tipsLabel->show(); m_currentDeviceName = ""; } } else { m_deviceFrame->hide(); m_currentDeviceName = ""; } setDefaultDevice(WIRED, m_currentDeviceName); connect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &LanPage::onDeviceComboxIndexChanged); } void LanPage::addEmptyConnectItem(QMap &connectMap, QListWidget *lanListWidget) { QListWidgetItem *p_listWidgetItem = addNewItem(nullptr, lanListWidget); connectMap.insert(EMPTY_CONNECT_UUID, p_listWidgetItem); } void LanPage::deleteConnectionMapItem(QMap &connectMap, QListWidget *lanListWidget, QString uuid) { QListWidgetItem *p_listWidgetItem = connectMap.value(uuid); if (p_listWidgetItem) { connectMap.remove(uuid); LanListItem *p_lanItem = (LanListItem *)lanListWidget->itemWidget(p_listWidgetItem); lanListWidget->removeItemWidget(p_listWidgetItem); delete p_lanItem; p_lanItem = nullptr; delete p_listWidgetItem; p_listWidgetItem = nullptr; } return; } void LanPage::clearConnectionMap(QMap &connectMap, QListWidget *lanListWidget) { QMap::iterator iter; iter = connectMap.begin(); while (iter != connectMap.end()) { qDebug()<<"[LanPage] clear connection map item"<< iter.key(); QListWidgetItem *p_widgetItem = iter.value(); LanListItem *p_lanItem = (LanListItem *)lanListWidget->itemWidget(p_widgetItem); lanListWidget->removeItemWidget(p_widgetItem); delete p_lanItem; p_lanItem = nullptr; delete p_widgetItem; p_widgetItem = nullptr; iter = connectMap.erase(iter); } return; } void LanPage::constructActiveConnectionArea() { QList activedList; activedList.clear(); clearConnectionMap(m_activeConnectionMap, m_activatedLanListWidget); m_activeResourse->getActiveConnectionList(m_currentDeviceName, NetworkManager::ConnectionSettings::Wired, activedList); //激活列表的显示 m_activeResourse->getActiveConnectionList(m_currentDeviceName, NetworkManager::ConnectionSettings::Pppoe, activedList); qDebug() << "[LanPage] construct active connection area get Active list size:" << activedList.size(); if (!activedList.isEmpty()) { for (int index = 0; index < activedList.size(); index++) { KyConnectItem *p_activeConnectionItem = activedList.at(index); qDebug() << "[LanPage] construct active connection area. add active item" << p_activeConnectionItem->m_connectName; QListWidgetItem *p_listWidgetItem = addNewItem(p_activeConnectionItem, m_activatedLanListWidget); m_activeConnectionMap.insert(p_activeConnectionItem->m_connectUuid, p_listWidgetItem); delete p_activeConnectionItem; p_activeConnectionItem = nullptr; } setNetSpeed->start(REFRESH_NETWORKSPEED_TIMER); m_activatedLanListWidget->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection); } else { qDebug()<<"[LanPage] there is not active"; addEmptyConnectItem(m_activeConnectionMap, m_activatedLanListWidget); m_activatedLanListWidget->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection); } return; } void LanPage::constructConnectionArea() { QList deactivedList; deactivedList.clear(); clearConnectionMap(m_inactiveConnectionMap, m_inactivatedLanListWidget); m_connectResourse->getConnectionList(m_currentDeviceName, NetworkManager::ConnectionSettings::Wired, deactivedList); //未激活列表的显示 m_connectResourse->getConnectionList(m_currentDeviceName, NetworkManager::ConnectionSettings::Pppoe, deactivedList); qDebug() << "[LanPage]construct connection area get connection list size:" << deactivedList.size(); if (!deactivedList.isEmpty()) { for (int index = 0; index < deactivedList.size(); index++) { KyConnectItem *p_deactiveConnectionItem = deactivedList.at(index); qDebug()<<"[LanPage] construct connection area add deactive item"<m_connectName; QListWidgetItem *p_listWidgetItem = addNewItem(p_deactiveConnectionItem, m_inactivatedLanListWidget); if (m_inactiveConnectionMap.contains(p_deactiveConnectionItem->m_connectUuid)) { qDebug()<m_connectUuid; } m_inactiveConnectionMap.insert(p_deactiveConnectionItem->m_connectUuid, p_listWidgetItem); delete p_deactiveConnectionItem; p_deactiveConnectionItem = nullptr; } } if (m_inactivatedLanListWidget->count() <= MAX_ITEMS) { m_inactivatedLanListWidget->setFixedWidth(MIN_WIDTH); } else { m_inactivatedLanListWidget->setFixedWidth(MAX_WIDTH); } return; } void LanPage::initLanArea() { showNoDeiceInfo(false,tr("")); if (!getSwitchBtnState() || m_currentDeviceName.isEmpty()) { m_activatedNetDivider->hide(); m_activatedNetFrame->hide(); m_inactivatedNetFrame->hide(); if(m_devList.isEmpty()) { showNoDeiceInfo(true,tr("No wired network card detected")); } } else { m_activatedNetDivider->show(); m_activatedNetFrame->show(); constructActiveConnectionArea(); updateActivatedNetFrame(m_currentDeviceName); m_inactivatedNetFrame->show(); constructConnectionArea(); } return; } bool LanPage::removeConnectionItem(QMap &connectMap, QListWidget *lanListWidget, QString path) { QMap::iterator iter; for (iter = connectMap.begin(); iter != connectMap.end(); ++iter) { QListWidgetItem *p_listWidgetItem = iter.value(); LanListItem *p_lanItem = (LanListItem*)lanListWidget->itemWidget(p_listWidgetItem); if (p_lanItem->getConnectionPath() == path) { qDebug()<<"[LanPage] Remove a connection from list"; lanListWidget->removeItemWidget(p_listWidgetItem); delete p_lanItem; p_lanItem = nullptr; delete p_listWidgetItem; p_listWidgetItem = nullptr; iter = connectMap.erase(iter); if (m_inactivatedLanListWidget->count() <= MAX_ITEMS) { m_inactivatedLanListWidget->setFixedWidth(MIN_WIDTH); } return true; } } return false; } void LanPage::onRemoveConnection(QString path) //删除时后端会自动断开激活,将其从未激活列表中删除 { //for dbus qDebug() << "[LanPage] Q_EMIT lanRemove because onRemoveConnection " << path; Q_EMIT lanRemove(path); if (m_lanPagePtrMap.contains(path)) { if (m_lanPagePtrMap[path] != nullptr) { delete m_lanPagePtrMap[path]; m_lanPagePtrMap[path] = nullptr; } } if (removeConnectionItem(m_inactiveConnectionMap, m_inactivatedLanListWidget, path)) { return; } else { removeConnectionItem(m_activeConnectionMap, m_activatedLanListWidget, path); if (m_activeConnectionMap.count() <= 0) { addEmptyConnectItem(m_activeConnectionMap, m_activatedLanListWidget); m_activatedLanListWidget->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection); } setNetSpeed->stop(); return; } } void LanPage::onAddConnection(QString uuid) //新增一个有线连接,将其加入到激活列表 { if (!m_connectResourse->isWiredConnection(uuid) && !m_connectResourse->isPppoeConnection(uuid)) { return; } KyConnectItem *p_newItem = nullptr; p_newItem = m_connectResourse->getConnectionItemByUuid(uuid); if (nullptr == p_newItem) { return; } sendLanAddSignal(p_newItem); if (p_newItem->m_ifaceName == m_currentDeviceName || p_newItem->m_ifaceName == "") { qDebug()<<"[LanPage] Add a new connection, name:"<m_connectName; QListWidgetItem *p_listWidgetItem = insertNewItem(p_newItem, m_inactivatedLanListWidget); if (m_inactiveConnectionMap.contains(p_newItem->m_connectUuid)) { qDebug()<m_connectUuid; } m_inactiveConnectionMap.insert(p_newItem->m_connectUuid, p_listWidgetItem); } delete p_newItem; p_newItem = nullptr; if (m_inactivatedLanListWidget->count() > MAX_ITEMS) { m_inactivatedLanListWidget->setFixedWidth(MAX_WIDTH); } } void LanPage::addDeviceForCombox(QString deviceName) { QString deviceState = ""; int flag = 0; disconnect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &LanPage::onDeviceComboxIndexChanged); if (getSwitchBtnState()) { if (1 == m_enableDeviceList.count()) { //1、从无到有添加第一块有线网卡 //2、有多快网卡,但是没有使能 m_deviceFrame->hide(); m_currentDeviceName = m_enableDeviceList.at(0); setDefaultDevice(WIRED, m_currentDeviceName); } else if (2 == m_enableDeviceList.count()) { //3、现在有且只有一块网卡,并已使能 //4、有多快网卡,且使能了其中一块 flag=m_deviceState[m_currentDeviceName]; deviceState=changeDeviceStateText(m_currentDeviceName,flag); m_deviceComboBox->addItem(deviceState,m_currentDeviceName); flag=m_deviceState[deviceName]; deviceState=changeDeviceStateText(deviceName,flag); m_deviceComboBox->addItem(deviceState,deviceName); m_deviceFrame->show(); m_tipsLabel->hide(); m_deviceComboBox->show(); } else if (m_enableDeviceList.count() > 2) { //5、有多快网卡且使能了多块网卡 flag=m_deviceState[deviceName]; deviceState=changeDeviceStateText(deviceName,flag); m_deviceComboBox->addItem(deviceState,deviceName); } } connect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &LanPage::onDeviceComboxIndexChanged); } void LanPage::onDeviceAdd(QString deviceName, NetworkManager::Device::Type deviceType) { Q_UNUSED(deviceType) if (!m_deviceResource->checkDeviceType(deviceName, NetworkManager::Device::Type::Ethernet)) { return; } if (m_devList.contains(deviceName)) { return; } bool wiredSwitch = m_wiredConnectOperation->getWiredEnabled(); setSwitchBtnEnable(true); setSwitchBtnState(wiredSwitch); if (m_devList.isEmpty()) { m_currentDeviceName = deviceName; } qDebug() << "[LanPage] Begin add device:" << deviceName << m_currentDeviceName; m_devList << deviceName; if (m_deviceResource->getDeviceManaged(deviceName)) { m_enableDeviceList << deviceName; } else { m_disableDeviceList << deviceName; } addDeviceForCombox(deviceName); if (m_currentDeviceName == deviceName) { initLanArea(); } Q_EMIT deviceStatusChanged(); } void LanPage::deleteDeviceFromCombox(QString deviceName) { disconnect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &LanPage::onDeviceComboxIndexChanged); if (getSwitchBtnState()) { if (0 == m_enableDeviceList.count()) { //1、没有使能任何网卡 goto l_out; } else if (1 == m_enableDeviceList.count()) { //2、使能了一个网卡,且当前网卡是要删除的网卡 if (m_currentDeviceName == deviceName) { m_deviceFrame->show(); m_deviceComboBox->hide(); m_tipsLabel->show(); m_currentDeviceName = ""; setDefaultDevice(WIRED, m_currentDeviceName); } } else if (2 == m_enableDeviceList.count()) { //3、使能了两个网卡,且包括要删除的网卡,有可能是要删除的网卡 if (m_deviceComboBox->findData(deviceName) != -1) { for (int index = m_deviceComboBox->count() - 1; index >= 0; index--) { if (m_currentDeviceName == deviceName && m_deviceComboBox->itemData(index).toString() != deviceName) { m_currentDeviceName = m_deviceComboBox->itemData(index).toString(); setDefaultDevice(WIRED, m_currentDeviceName); } m_deviceComboBox->removeItem(index); } m_tipsLabel->hide(); m_deviceFrame->hide(); m_deviceComboBox->hide(); } } else { //4、使能了多个网卡,且包括要删除的网卡,有可能是正要删除的网卡 int index = m_deviceComboBox->findData(deviceName); if (index != -1) { m_deviceComboBox->removeItem(index); if (m_currentDeviceName == deviceName) { m_currentDeviceName = m_deviceComboBox->currentData().toString(); setDefaultDevice(WIRED, m_currentDeviceName); } } } } l_out: connect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &LanPage::onDeviceComboxIndexChanged); return; } void LanPage::onDeviceRemove(QString deviceName) { if (!m_devList.contains(deviceName)) { return; } qDebug() << "[LanPage] deviceRemove:" << deviceName; m_devList.removeOne(deviceName); if (m_devList.isEmpty()) { setSwitchBtnState(false); setSwitchBtnEnable(false); qDebug() << "[wiredSwitch]set not enable after device remove"; } QString nowDevice = m_currentDeviceName; deleteDeviceFromCombox(deviceName); if (nowDevice == deviceName || m_devList.isEmpty()) { setDefaultDevice(WIRED, m_currentDeviceName); initLanArea(); } if (m_enableDeviceList.contains(deviceName)) { m_enableDeviceList.removeOne(deviceName); } if (m_disableDeviceList.contains(deviceName)) { m_disableDeviceList.removeOne(deviceName); } Q_EMIT deviceStatusChanged(); } void LanPage::updateDeviceCombox(QString oldDeviceName, QString newDeviceName) { QString deviceState=""; if (m_currentDeviceName == oldDeviceName) { m_currentDeviceName = newDeviceName; setDefaultDevice(WIRED, m_currentDeviceName); } int index = m_deviceComboBox->findData(oldDeviceName); if (index != -1) { deviceState=changeDeviceStateText(newDeviceName,m_deviceState[newDeviceName]); m_deviceComboBox->setItemText(index, deviceState); } return; } void LanPage::onDeviceNameUpdate(QString oldName, QString newName) { if (m_devList.contains(oldName)) { m_devList.removeOne(oldName); m_devList.append(newName); if (m_enableDeviceList.contains(oldName)) { m_enableDeviceList.removeOne(oldName); m_enableDeviceList.append(newName); } else if (m_disableDeviceList.contains(oldName)) { m_disableDeviceList.removeOne(oldName); m_disableDeviceList.append(newName); } qDebug() << "[LanPage] Q_EMIT deviceNameUpdate " << oldName << newName; replaceDeviceConnectState(oldName,newName); updateDeviceCombox(oldName, newName); if (m_currentDeviceName == newName) { initLanArea(); } Q_EMIT deviceNameChanged(oldName, newName, WIRED); } } void LanPage::onDeviceCarriered(QString deviceName, bool pluged) { if (!pluged) { return; } if (m_enableDeviceList.contains(deviceName)) { updateCurrentDevice(deviceName); } } void LanPage::onDeviceManagedChange(QString deviceName, bool managed) { if (!m_deviceResource->checkDeviceType(deviceName, NetworkManager::Device::Type::Ethernet)) { return; } initLanDeviceState(); initDeviceCombox(); initLanArea(); m_showedNetTipFlag = false; Q_EMIT deviceStatusChanged(); } void LanPage::onDeviceComboxIndexChanged(int currentIndex) { //TODO 设备变更时更新设备和列表 m_currentDeviceName = m_deviceComboBox->currentData().toString(); qDebug() << "[LanPage]Current Device Changed to:" << m_currentDeviceName; initLanArea(); } void LanPage::onShowControlCenter() { QProcess process; process.startDetached("ukui-control-center", QStringList() << "-m" << "netconnect"); } void LanPage::initUI() { m_titleLabel->setText(tr("LAN")); m_activatedNetLabel->setText(tr("Activated LAN")); m_activatedLanListWidget = new QListWidget(m_activatedNetFrame); m_activatedLanListWidget->setFrameShape(QFrame::Shape::NoFrame); m_activatedLanListWidget->setSpacing(LAN_LIST_SPACING); m_activatedLanListWidget->setFixedHeight(ITEM_HEIGHT); //active区域固定高度,只显示一个条目 m_activatedLanListWidget->setFixedWidth(MIN_WIDTH); m_activatedLanListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_activatedLanListWidget->setProperty("needTranslucent", true); m_activatedNetLayout->addWidget(m_activatedLanListWidget); m_inactivatedNetLabel->setText(tr("Inactivated LAN")); m_inactivatedLanListWidget = new QListWidget(m_inactivatedNetListArea); m_inactivatedLanListWidget->setFrameShape(QFrame::Shape::NoFrame); m_inactivatedLanListWidget->setSpacing(LAN_LIST_SPACING); m_inactivatedLanListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_inactivatedLanListWidget->setVerticalScrollMode(QAbstractItemView::ScrollMode::ScrollPerPixel); m_inactivatedLanListWidget->verticalScrollBar()->setProperty("drawScrollBarGroove",false); //去除滚动条的外侧黑框 m_inactivatedLanListWidget->verticalScrollBar()->setSingleStep(SCROLL_STEP); m_inactivatedLanListWidget->verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu); m_inactivatedLanListWidget->verticalScrollBar()->setProperty("needTranslucent", true); m_inactivatedLanListWidget->setProperty("needTranslucent", true); m_inactivatedAreaLayout->addWidget(m_inactivatedLanListWidget); connect(m_inactivatedLanListWidget, &QListWidget::currentItemChanged, this, [=]() { if (m_inactivatedLanListWidget->currentItem() != nullptr) { m_inactivatedLanListWidget->currentItem()->setSelected(false); } }); QPalette pal = m_activatedLanListWidget->palette(); pal.setBrush(QPalette::Base, QColor(0,0,0,0)); //背景透明 m_activatedLanListWidget->setPalette(pal); m_inactivatedLanListWidget->setPalette(pal); m_settingsLabel->installEventFilter(this); m_netSwitch->installEventFilter(this); m_activatedLanListWidget->installEventFilter(this); m_inactivatedLanListWidget->installEventFilter(this); showRate(); } QListWidgetItem *LanPage::insertNewItem(KyConnectItem *itemData, QListWidget *listWidget) { int index = 0; for(index = 0; index < m_inactivatedLanListWidget->count(); index++) { QListWidgetItem *p_listWidgetItem = m_inactivatedLanListWidget->item(index); LanListItem *p_lanItem = (LanListItem *)m_inactivatedLanListWidget->itemWidget(p_listWidgetItem); QString name1 = p_lanItem->getConnectionName(); QString name2 = itemData->m_connectName; if (QString::compare(name1, name2, Qt::CaseInsensitive) > 0) { break; } } QListWidgetItem *p_sortListWidgetItem = new QListWidgetItem(); // p_sortListWidgetItem->setFlags(p_sortListWidgetItem->flags() & (~Qt::ItemIsSelectable)); //设置不可被选中 p_sortListWidgetItem->setSizeHint(QSize(listWidget->width(),ITEM_HEIGHT)); listWidget->insertItem(index, p_sortListWidgetItem); LanListItem *p_sortLanItem = nullptr; p_sortLanItem = new LanListItem(itemData, m_currentDeviceName); listWidget->setItemWidget(p_sortListWidgetItem, p_sortLanItem); connect(p_sortLanItem, &LanListItem::detailShow, this, &LanPage::showDetailPage); return p_sortListWidgetItem; } QListWidgetItem *LanPage::addNewItem(KyConnectItem *itemData, QListWidget *listWidget) { QListWidgetItem *p_listWidgetItem = new QListWidgetItem(); // p_listWidgetItem->setFlags(p_listWidgetItem->flags() & (~Qt::ItemIsSelectable)); p_listWidgetItem->setSizeHint(QSize(listWidget->width(), ITEM_HEIGHT)); listWidget->addItem(p_listWidgetItem); LanListItem *p_lanItem = nullptr; if (itemData != nullptr) { p_lanItem = new LanListItem(itemData, m_currentDeviceName); qDebug() << "[LanPage] addNewItem, connection: " << itemData->m_connectName << "deviceName: " << m_currentDeviceName; } else { p_lanItem = new LanListItem(); qDebug() << "[LanPage] Add nullItem!"; } listWidget->setItemWidget(p_listWidgetItem, p_lanItem); connect(p_lanItem, &LanListItem::detailShow, this, &LanPage::showDetailPage); return p_listWidgetItem; } void LanPage::updateActivatedConnectionArea(KyConnectItem *p_newItem) { m_activatedLanListWidget->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection); if (m_activeConnectionMap.contains(p_newItem->m_connectUuid)) { return; } deleteConnectionMapItem(m_inactiveConnectionMap, m_inactivatedLanListWidget, p_newItem->m_connectUuid); if (p_newItem->m_ifaceName == m_currentDeviceName) { qDebug()<<"[LanPage]update active connection item"<m_connectName; deleteConnectionMapItem(m_activeConnectionMap, m_activatedLanListWidget, EMPTY_CONNECT_UUID); QListWidgetItem *p_listWidgetItem = addNewItem(p_newItem, m_activatedLanListWidget); m_activeConnectionMap.insert(p_newItem->m_connectUuid, p_listWidgetItem); // this->showDesktopNotify(tr("LAN Connected Successfully"), "networkconnected"); } if (m_inactivatedLanListWidget->count() <= MAX_ITEMS) { m_inactivatedLanListWidget->setFixedWidth(MIN_WIDTH); } return; } void LanPage::updateConnectionArea(KyConnectItem *p_newItem) { if (m_inactiveConnectionMap.contains(p_newItem->m_connectUuid)) { return; } deleteConnectionMapItem(m_activeConnectionMap, m_activatedLanListWidget, p_newItem->m_connectUuid); if (m_activeConnectionMap.count() <= 0) { addEmptyConnectItem(m_activeConnectionMap, m_activatedLanListWidget); m_activatedLanListWidget->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection); } if (p_newItem->m_ifaceName == m_currentDeviceName || p_newItem->m_ifaceName == "") { qDebug()<<"[LanPage] update connection item"<m_connectName; QListWidgetItem *p_listWidgetItem = insertNewItem(p_newItem, m_inactivatedLanListWidget); m_inactiveConnectionMap.insert(p_newItem->m_connectUuid, p_listWidgetItem); // this->showDesktopNotify(tr("LAN Disconnected Successfully"), "networkdisconnected"); } if (m_inactivatedLanListWidget->count() <= MAX_ITEMS) { m_inactivatedLanListWidget->setFixedWidth(MIN_WIDTH); } else { m_inactivatedLanListWidget->setFixedWidth(MAX_WIDTH); } return; } void LanPage::updateConnectionState(QMap &connectMap, QListWidget *lanListWidget, QString uuid, ConnectState state) { qDebug() << LOG_FLAG << "update connection state"; QListWidgetItem *p_listWidgetItem = connectMap.value(uuid); if (p_listWidgetItem) { LanListItem *p_lanItem = (LanListItem *)lanListWidget->itemWidget(p_listWidgetItem); p_lanItem->updateConnectionState(state); } return; } QString LanPage::getConnectionDevice(QString uuid) { QString deviceName = ""; deviceName = m_activeResourse->getDeviceOfActivateConnect(uuid); if (deviceName.isEmpty()) { m_connectResourse->getInterfaceByUuid(deviceName, uuid); } return deviceName; } void LanPage::updateCurrentDevice(QString deviceName) { if (m_currentDeviceName != deviceName) { int index = m_deviceComboBox->findData(deviceName); if (index < 0) { index = 0; } m_deviceComboBox->setCurrentIndex(index); return; } return; } void LanPage::onConnectionStateChange(QString uuid, NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason) { QString devName; devName=getConnectionDevice(uuid); //lanpage函数内持续监听连接状态的变化并记录供其他函数调用获取状态 if (!m_connectResourse->isWiredConnection(uuid) && !m_connectResourse->isPppoeConnection(uuid)) { qDebug() << "[LanPage] connection state change signal but not wired"; return; } sendLanStateChangeSignal(uuid, (ConnectState)state); updateDeviceConnectState(devName,state); if (m_activeConnectionMap.keys().contains(uuid) && state == NetworkManager::ActiveConnection::State::Activated) { return; } qDebug()<<"[LanPage] connection uuid"<< uuid << "state change slot:"<< state; KyConnectItem *p_newItem = nullptr; QString deviceName = ""; if (state == NetworkManager::ActiveConnection::State::Activated) { p_newItem = m_activeResourse->getActiveConnectionByUuid(uuid); if (nullptr == p_newItem) { qWarning()<<"[LanPage] get active connection failed, connection uuid" << uuid; return; } deviceName = p_newItem->m_ifaceName; // add by cyf //连接后将信息写入配置文件 QDBusInterface iface(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, QDBusConnection::systemBus()); if (iface.isValid()) { iface.call("writeNmConfig", "/etc/kylin-nm/netSwitch.conf", "Lan_Connect", deviceName, uuid); } updateActivatedConnectionArea(p_newItem); updateConnectionState(m_activeConnectionMap, m_activatedLanListWidget, uuid, (ConnectState)state); if (deviceName == m_currentDeviceName) { updateActivatedNetFrame(deviceName); setNetSpeed->start(REFRESH_NETWORKSPEED_TIMER); } } else if (state == NetworkManager::ActiveConnection::State::Deactivated) { p_newItem = m_connectResourse->getConnectionItemByUuidWithoutActivateChecking(uuid); qDebug() << "[LanPage] deactivated reason" << reason; if (nullptr == p_newItem) { qWarning()<<"[LanPage] get active connection failed, connection uuid" << uuid; return; } deviceName = p_newItem->m_ifaceName; updateActivatedNetFrame(deviceName); updateConnectionArea(p_newItem); updateConnectionState(m_inactiveConnectionMap, m_inactivatedLanListWidget, uuid, (ConnectState)state); if (deviceName == m_currentDeviceName) { setNetSpeed->stop(); } } else if (state == NetworkManager::ActiveConnection::State::Activating) { deviceName = getConnectionDevice(uuid); if (deviceName == m_currentDeviceName) { updateConnectionState(m_inactiveConnectionMap, m_inactivatedLanListWidget, uuid, (ConnectState)state); } } else if (state == NetworkManager::ActiveConnection::State::Deactivating) { deviceName = getConnectionDevice(uuid); if (deviceName == m_currentDeviceName) { updateConnectionState(m_activeConnectionMap, m_activatedLanListWidget, uuid, (ConnectState)state); } } Q_EMIT lanActiveConnectionStateChanged(deviceName, uuid, state); if (p_newItem) { delete p_newItem; p_newItem = nullptr; } return; } void LanPage::getWiredList(QString devName, QList &list) { QStringList devlist; m_deviceResource->getNetworkDeviceList(NetworkManager::Device::Type::Ethernet, devlist); if (!devlist.contains(devName)) { return; } QList activedList; QList deactivedList; m_activeResourse->getActiveConnectionList(devName,NetworkManager::ConnectionSettings::Wired,activedList); m_activeResourse->getActiveConnectionList(devName,NetworkManager::ConnectionSettings::Pppoe,activedList); if (!activedList.isEmpty()) { list.append(QStringList() << activedList.at(0)->m_connectName << activedList.at(0)->m_connectUuid << activedList.at(0)->m_connectPath << (m_connectResourse->isPppoeConnection(activedList.at(0)->m_connectUuid) ? "1" : "0") << QString::number(m_connectResourse->getActiveConnectionState(activedList.at(0)->m_connectUuid))); } else { list.append(QStringList()<<("--")); } m_connectResourse->getConnectionList(devName, NetworkManager::ConnectionSettings::Wired, deactivedList); //未激活列表的显示 m_connectResourse->getConnectionList(devName, NetworkManager::ConnectionSettings::Pppoe, deactivedList); if (!deactivedList.isEmpty()) { for (int i = 0; i < deactivedList.size(); i++) { list.append(QStringList() << deactivedList.at(i)->m_connectName << deactivedList.at(i)->m_connectUuid << deactivedList.at(i)->m_connectPath << (m_connectResourse->isPppoeConnection(deactivedList.at(i)->m_connectUuid) ? "1" : "0") << QString::number(m_connectResourse->getActiveConnectionState(deactivedList.at(i)->m_connectUuid))); } } } void LanPage::sendLanUpdateSignal(KyConnectItem *p_connectItem) { QStringList info; info << p_connectItem->m_connectName << p_connectItem->m_connectUuid << p_connectItem->m_connectPath << (m_connectResourse->isPppoeConnection(p_connectItem->m_connectUuid) ? "1" : "0") << QString::number(m_connectResourse->getActiveConnectionState(p_connectItem->m_connectUuid)); Q_EMIT lanUpdate(p_connectItem->m_ifaceName, info); return; } void LanPage::sendLanAddSignal(KyConnectItem *p_connectItem) { QStringList info; info << p_connectItem->m_connectName << p_connectItem->m_connectUuid << p_connectItem->m_connectPath << (m_connectResourse->isPppoeConnection(p_connectItem->m_connectUuid) ? "1" : "0"); qDebug() << "[LanPage] Q_EMIT lanAdd because addConnection "; Q_EMIT lanAdd(p_connectItem->m_ifaceName, info); return; } void LanPage::sendLanStateChangeSignal(QString uuid, ConnectState state) { if (state == Activating || state == Deactivating) { if (m_activeResourse->connectionIsVirtual(uuid) && !m_connectResourse->isPppoeConnection(uuid)) { return; } } updateConnectionState(m_activeConnectionMap, m_activatedLanListWidget, uuid, state); Q_EMIT this->lanConnectChanged(state); return; } void LanPage::updateConnectionProperty(KyConnectItem *p_connectItem) { QString newUuid = p_connectItem->m_connectUuid; if (m_inactiveConnectionMap.contains(newUuid)) { QListWidgetItem *p_listWidgetItem = m_inactiveConnectionMap.value(newUuid); LanListItem *p_lanItem = (LanListItem*)m_inactivatedLanListWidget->itemWidget(p_listWidgetItem); if (p_connectItem->m_ifaceName != "" && m_currentDeviceName != p_connectItem->m_ifaceName) { m_inactivatedLanListWidget->removeItemWidget(p_listWidgetItem); delete p_listWidgetItem; p_listWidgetItem = nullptr; delete p_lanItem; p_lanItem = nullptr; m_inactiveConnectionMap.remove(newUuid); } else { if (p_connectItem->m_connectName != p_lanItem->getConnectionName()){ //只要名字改变就要删除,重新插入,主要是为了排序 deleteConnectionMapItem(m_inactiveConnectionMap, m_inactivatedLanListWidget, newUuid); QListWidgetItem *p_sortListWidgetItem = insertNewItem(p_connectItem, m_inactivatedLanListWidget); if (m_inactiveConnectionMap.contains(newUuid)) { qDebug()<m_connectPath != p_lanItem->getConnectionPath()) { p_lanItem->updateConnectionPath(p_connectItem->m_connectPath); } } } else if (!m_activeConnectionMap.contains(newUuid)){ if (p_connectItem->m_ifaceName == m_currentDeviceName || p_connectItem->m_ifaceName.isEmpty()) { QListWidgetItem *p_listWidgetItem = insertNewItem(p_connectItem, m_inactivatedLanListWidget); if (m_inactiveConnectionMap.contains(newUuid)) { qDebug()<m_connectUuid; if (m_activeConnectionMap.contains(newUuid)) { QListWidgetItem *p_listWidgetItem = m_activeConnectionMap.value(newUuid); LanListItem *p_lanItem = (LanListItem *)m_activatedLanListWidget->itemWidget(p_listWidgetItem); if (m_currentDeviceName != p_connectItem->m_ifaceName) { m_activeConnectionMap.remove(newUuid); int takeRow = m_activatedLanListWidget->row(p_listWidgetItem); m_activatedLanListWidget->takeItem(takeRow); delete p_lanItem; p_lanItem = nullptr; p_lanItem = new LanListItem(); m_activatedLanListWidget->addItem(p_listWidgetItem); m_activatedLanListWidget->setItemWidget(p_listWidgetItem, p_lanItem); m_activeConnectionMap.insert(EMPTY_CONNECT_UUID, p_listWidgetItem); } else { if (p_lanItem->getConnectionName() != p_connectItem->m_connectName) { p_lanItem->updateConnectionName(p_connectItem->m_connectName); } if (p_lanItem->getConnectionName() != p_connectItem->m_connectPath) { p_lanItem->updateConnectionPath(p_connectItem->m_connectPath); } } } return; } void LanPage::onUpdateConnection(QString uuid) { if (!m_connectResourse->isWiredConnection(uuid) && !m_connectResourse->isPppoeConnection(uuid)) { return; } qDebug() << "[LanPage]:Connection property Changed." << Q_FUNC_INFO << __LINE__; KyConnectItem *p_newItem = nullptr; if (m_connectResourse->isActivatedConnection(uuid)) { p_newItem = m_activeResourse->getActiveConnectionByUuid(uuid); if (nullptr == p_newItem) { qWarning()<<"[LanPage] get item failed, when update activate connection." <<"connection uuid" << uuid; return; } updateActiveConnectionProperty(p_newItem); } else { p_newItem = m_connectResourse->getConnectionItemByUuid(uuid); if (nullptr == p_newItem) { qWarning()<<"[LanPage] get item failed, when update connection." <<"connection uuid"<setDeviceManaged(devName, enable); } bool LanPage::getCableStateByDevice(const QString &deviceName) { return m_deviceResource->wiredDeviceIsCarriered(deviceName); } int LanPage::getDeviceConnectivity(const QString deviceName) { NetworkManager::Connectivity connectivity; m_deviceResource->getDeviceConnectivity(deviceName, connectivity); return (int)connectivity; } bool LanPage::eventFilter(QObject *watched, QEvent *event) { if (watched == m_settingsLabel) { if (event->type() == QEvent::MouseButtonRelease) { onShowControlCenter(); } } else if(watched == m_netSwitch && m_netSwitch->isEnabled()) { if (event->type() == QEvent::MouseButtonRelease) { qDebug()<<"[LanPage] On lan switch button clicked! Status:" <showDesktopNotify(tr("No ethernet device avaliable"), "networkwrong"); setSwitchBtnState(false); setSwitchBtnEnable(false); } } } else if (watched == m_activatedLanListWidget) { //去掉无右键菜单显示时的选中效果 if (event->type() == QEvent::FocusIn) { if (m_activatedLanListWidget->currentItem() != nullptr) { m_activatedLanListWidget->currentItem()->setSelected(false); } } } else if (watched == m_inactivatedLanListWidget) { //去掉无右键菜单显示时的选中效果 if (event->type() == QEvent::FocusIn) { if (m_inactivatedLanListWidget->currentItem() != nullptr) { m_inactivatedLanListWidget->currentItem()->setSelected(false); } } } return QWidget::eventFilter(watched, event); } void LanPage::onWiredEnabledChanged(bool enabled) { if (m_devList.isEmpty()) { qDebug() << "[LanPage] have no device to use " << Q_FUNC_INFO << __LINE__; return; } if (getSwitchBtnState() == enabled) { return; } else { setSwitchBtnState(enabled); initLanDeviceState(); initDeviceCombox(); initLanArea(); } Q_EMIT wiredEnabledChanged(enabled); } void LanPage::onDeviceConnectivityChanged(QString devName, NetworkManager::Connectivity connectivity) { qDebug() << LOG_FLAG << "device network connectivity changed slot" << connectivity; //update device Frame ui updateActivatedNetFrame(devName); Q_EMIT deviceConnectivityChanged(devName, (int)connectivity); } void LanPage::onShowKylinNetworkCheck() { QProcess process; process.startDetached("kylin-os-manager --diagnosis --mode=Network"); } void LanPage::onLanStateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason) { QTimer::singleShot(500, [this]() { TabPage::stopLoading(); }); if (newstate == NetworkManager::Device::Failed) { if (reason == NetworkManager::Device::StateChangeReason::ConfigUnavailableReason) { if (!m_showedNetTipFlag) { showBallonTip(); m_showedNetTipFlag = true; } } } } void LanPage::activateWired(const QString& devName, const QString& connUuid) { qDebug() << "[LanPage] activateWired" << devName << connUuid; if (!m_deviceResource->wiredDeviceIsCarriered(devName)) { qDebug() << LOG_FLAG << devName << "is not carried, so can not activate connection"; this->showDesktopNotify(tr("Wired Device not carried"), "networkwrong"); } else { m_wiredConnectOperation->activateConnection(connUuid, devName); } } void LanPage::deactivateWired(const QString& devName, const QString& connUuid, bool concise) { qDebug() << "[LanPage] deactivateWired" << devName << connUuid; QString name(""); m_wiredConnectOperation->deactivateWiredConnection(name, connUuid, concise, devName); } void LanPage::setWiredDeviceAutoconnect(const QString& devName,bool state) { qDebug() << Q_FUNC_INFO << __LINE__ <setWiredDeviceAutoconnect(devName, state); } void LanPage::deleteWiredConnect(const QString& connUuid) { qDebug() << "[LanPage] deactivateWired" << connUuid; m_wiredConnectOperation->deleteWiredConnect(connUuid); } void LanPage::showDetailPage(QString devName, QString uuid) { KyConnectItem *p_item = nullptr; bool isActive = true; if (m_connectResourse->isActivatedConnection(uuid)) { p_item = m_activeResourse->getActiveConnectionByUuid(uuid); isActive = true; } else { p_item = m_connectResourse->getConnectionItemByUuid(uuid); isActive = false; } if (nullptr == p_item) { qWarning()<<"[LanPage] GetConnectionItemByUuid is empty when showDetailPage." <<"device name"<m_connectPath)) { if (m_lanPagePtrMap[p_item->m_connectPath] != nullptr) { qDebug() << "[LanPage] ShowLanDetailPage" << uuid << "already create,just raise"; m_lanPagePtrMap[p_item->m_connectPath]->activateWindow(); return; } } NetDetail *netDetail = new NetDetail(devName, p_item->m_connectName, uuid, isActive, false, false,0); m_lanPagePtrMap.insert(p_item->m_connectPath, netDetail); netDetail->show(); connect(netDetail, &NetDetail::detailPageClose, [&](QString deviceName, QString lanName, QString lanUuid){ if (lanUuid.isEmpty()) { return; } KyConnectItem *currentItem = nullptr; if (m_connectResourse->isActivatedConnection(lanUuid)) { currentItem = m_activeResourse->getActiveConnectionByUuid(lanUuid); } else { currentItem = m_connectResourse->getConnectionItemByUuid(lanUuid); } if (currentItem == nullptr) { return; } if (m_lanPagePtrMap.contains(currentItem->m_connectPath)) { m_lanPagePtrMap[currentItem->m_connectPath] = nullptr; } delete currentItem; currentItem = nullptr; }); delete p_item; p_item = nullptr; } bool LanPage::lanIsConnected() { if (m_activeResourse->wiredConnectIsActived()) { return true; } else { return false; } } void LanPage::getWiredDeviceConnectState(QMap &map) { map.clear(); if (m_enableDeviceList.isEmpty()) { return; } for (const auto devname : m_enableDeviceList) { NetworkManager::Connectivity state; QList activedList; m_deviceResource->getDeviceConnectivity(devname, state); m_activeResourse->getActiveConnectionList(devname, NetworkManager::ConnectionSettings::Wired, activedList); m_activeResourse->getActiveConnectionList(devname, NetworkManager::ConnectionSettings::Pppoe, activedList); if (activedList.isEmpty()) { map.insert(devname, tr("Not Connected")); continue; } switch (state) { case NetworkManager::Connectivity::NoConnectivity: //map.insert(devname, QString(tr("Connected: ")) + activedList.at(0)->m_connectName + " " + QString(tr("(No Internet)"))); //break; case NetworkManager::Connectivity::Portal: case NetworkManager::Connectivity::Limited: map.insert(devname, QString(tr("Connected: ")) + activedList.at(0)->m_connectName + " " + QString(tr("(Limited)"))); break; case NetworkManager::Connectivity::Full: map.insert(devname, QString(tr("Connected: ")) + activedList.at(0)->m_connectName); break; default: qDebug() << devname << " Network connectivity is unknown."; break; } } } void LanPage::showRate() { //定时获取网速 setNetSpeed = new QTimer(this); setNetSpeed->setTimerType(Qt::PreciseTimer); connect(setNetSpeed, &QTimer::timeout, [&]() { onSetNetSpeed(m_activatedLanListWidget, m_activeConnectionMap.contains(EMPTY_CONNECT_UUID), m_currentDeviceName); }); } void LanPage::updateActivatedNetFrame(QString deviceName) { QList activedList; m_activeResourse->getActiveConnectionList(deviceName, NetworkManager::ConnectionSettings::Wired, activedList); m_activeResourse->getActiveConnectionList(deviceName, NetworkManager::ConnectionSettings::Pppoe, activedList); if (activedList.isEmpty()) { m_activatedLanListWidget->setFixedHeight(ITEM_HEIGHT); return; } NetworkManager::Connectivity connectivity; m_deviceResource->getDeviceConnectivity(deviceName, connectivity); QString connectivityText = strConnectivityFromType(connectivity); if (m_activeConnectionMap.contains(activedList.at(0)->m_connectUuid)) { QListWidgetItem *p_listWidgetItem = m_activeConnectionMap.value(activedList.at(0)->m_connectUuid); LanListItem *p_lanItem = (LanListItem *)m_activatedLanListWidget->itemWidget(p_listWidgetItem); p_lanItem->updateConnectivityText(connectivityText); if (connectivityText.isEmpty()) { m_activatedLanListWidget->setFixedHeight(ITEM_HEIGHT); p_listWidgetItem->setSizeHint(QSize(m_activatedLanListWidget->width(), ITEM_HEIGHT)); } else { int itemHeight = p_lanItem->itemHeight(); m_activatedLanListWidget->setFixedHeight(itemHeight); p_listWidgetItem->setSizeHint(QSize(m_activatedLanListWidget->width(), itemHeight)); } } } QString LanPage::strConnectivityFromType(int type) { switch (type) { case NetworkManager::Connectivity::Portal: case NetworkManager::Connectivity::Limited: //文案:已连接,网络受限 return QString(tr("Connected, restricting access")); break; default: return QString(""); break; } } void LanPage::showBallonTip() { QString warnInfo = tr("No internet access. Please click Network Check to specific reasons."); if (m_netTip != nullptr) { delete m_netTip; m_netTip = nullptr; } m_netTip = new KBallonTip(); m_netTip->setWindowFlags(Qt::FramelessWindowHint); QPushButton *btn = new QPushButton(m_netTip); btn->setText(tr("Network Check")); connect(btn, &QPushButton::clicked, m_netTip, [=]() { m_netTip->close(); onShowKylinNetworkCheck(); }); m_netTip->setAttribute(Qt::WA_TranslucentBackground, true); m_netTip->setTipType(TipType::Warning); m_netTip->hBoxLayout()->setContentsMargins(16, 6, 10, 6); m_netTip->hBoxLayout()->setSpacing(4); m_netTip->hBoxLayout()->addSpacing(4); m_netTip->hBoxLayout()->addWidget(btn); m_netTip->setTipTime(9 * 1000); //call close() when time out m_netTip->setText(warnInfo); //set palette QPalette pal = m_netTip->palette(); pal.setColor(QPalette::Window, this->palette().window().color()); pal.setColor(QPalette::WindowText, this->palette().windowText().color()); m_netTip->setPalette(pal); QPalette btnPal = btn->palette(); btnPal.setColor(QPalette::Text, this->palette().text().color()); //button text btnPal.setColor(QPalette::Button, this->palette().button().color()); btn->setPalette(btnPal); //set position m_netTip->adjustSize(); KX11Extras::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager); QRect rect = caculatePositionWithPanel(m_netTip->width() - 8, m_netTip->height() - 4); m_netTip->setGeometry(rect); m_netTip->showInfo(); } void LanPage::connectFontGsetting() { const QByteArray id("org.ukui.style"); QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); if(QGSettings::isSchemaInstalled(id)){ connect(fontSetting, &QGSettings::changed,[=](QString key) { if ("systemFont" == key || "systemFontSize" ==key) { if (m_netTip->isVisible()) { m_netTip->adjustSize(); QRect rect = caculatePositionWithPanel(m_netTip->width() - 8, m_netTip->height() - 4); m_netTip->setGeometry(rect); } } }); } } void LanPage::onMainWindowVisibleChanged(const bool &visible) { //刷新界面显示 if (visible) { updateActivatedNetFrame(m_currentDeviceName); } } void LanPage::initLanDeviceConnectState() { QList activedList; m_deviceState.clear(); activedList.clear(); if (m_devList.isEmpty()) { return; } for (const auto devname : m_devList) { if (!m_deviceResource->getDeviceManaged(devname)) { continue; } m_activeResourse->getActiveConnectionList(devname, NetworkManager::ConnectionSettings::Wired, activedList); //激活列表的显示 m_activeResourse->getActiveConnectionList(devname, NetworkManager::ConnectionSettings::Pppoe, activedList); if (!activedList.isEmpty()) { for (const auto devActivedDate : activedList) { qDebug() << Q_FUNC_INFO << __LINE__<< devActivedDate->m_ifaceName; if (devname == devActivedDate->m_ifaceName) m_deviceState.insert(devname,NetworkManager::ActiveConnection::Activated); else m_deviceState.insert(devname,NetworkManager::ActiveConnection::Deactivated); } } else { m_deviceState.insert(devname,NetworkManager::ActiveConnection::Deactivated); } } } void LanPage::getWiredDeviceConnect(QMap &map) { map.clear(); if (m_enableDeviceList.isEmpty()) { return; } for (const auto devname : m_enableDeviceList) { QList activedList; m_activeResourse->getActiveConnectionList(devname, NetworkManager::ConnectionSettings::Wired, activedList); m_activeResourse->getActiveConnectionList(devname, NetworkManager::ConnectionSettings::Pppoe, activedList); for (const auto devActivedDate : activedList) { if (devname == devActivedDate->m_ifaceName) { map.insert(devname,devActivedDate->m_connectUuid); } } } } //自动连接有线网络 //连接有线网络时,将连接信息写入/etc/kylin-nm/netSwitch.conf文件的Lan_Connect节点中 //断开有线网络时,清除对应连接的信息 //检查到网卡打开时,传入网卡信息,寻找该网卡信息是否需要重连(网络信息还存在说明没有断开网络,而是直接关闭的网卡。需要自动连接) void LanPage::onSysDeviceSwitchChanged(const QString& devName) { QDBusInterface interface ("com.kylin.network", "/com/kylin/network", "com.kylin.network", QDBusConnection::sessionBus()); if (interface.isValid()) { QDBusReply> reply = m_pSysBusIntfs->call("getNmConfig", "/etc/kylin-nm/netSwitch.conf", "Lan_Connect"); QMap connectMap = reply.value(); QString connectUuid = connectMap[devName]; if (connectUuid == "") { return; } interface.call(QStringLiteral("activateConnect"), 0, devName, connectUuid); } else { qDebug() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } } //自动连接有线网络 //连接有线网络时,将连接信息写入/etc/kylin-nm/netSwitch.conf文件的Lan_Connect节点中 //断开有线网络时,清除对应连接的信息 //检查到有线开关打开时,自动连接所有还存在的网络信息(网络信息还存在说明没有断开网络,而是直接关闭的开关。需要自动连接) void LanPage::onSysWiredMainSwitchChanged(bool state) { qWarning() << Q_FUNC_INFO << __LINE__ << state; Q_EMIT wiredMainSwitchBtnChanged(state); if (state) { QDBusInterface interface ("com.kylin.network", "/com/kylin/network", "com.kylin.network", QDBusConnection::sessionBus()); if (interface.isValid()) { QDBusReply> reply = m_pSysBusIntfs->call("getNmConfig", "/etc/kylin-nm/netSwitch.conf", "Lan_Connect"); QMap connectMap = reply.value(); for (auto iter = connectMap.begin(); iter != connectMap.end(); ++iter) { QString deviceName = iter.key(); QString connectUuid = iter.value(); if (deviceName == "" || connectUuid == "") { continue; } interface.call(QStringLiteral("activateConnect"), 0, deviceName, connectUuid); } } else { qDebug() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } } } kylin-nm/src/frontend/tab-pages/tabpage.cpp0000664000175000017500000005440115167651420017631 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "tabpage.h" #include #include #include #include #include #include #include #include #include"listitem.h" #define LOG_FLAG "[tabPage]" #define PANEL_SETTINGS "org.ukui.panel.settings" #define PANEL_SIZE_KEY "panelsize" #define PANEL_POSITION_KEY "panelposition" #define ICONSIZE 16,16 TabPage::TabPage(QWidget *parent) : QWidget(parent) { initUI(); initPanelGSettings(); connect(qApp, &QApplication::paletteChanged, this, &TabPage::onPaletteChanged); } TabPage::~TabPage() { delete m_titleDivider; delete m_activatedNetDivider; delete m_inactivatedNetDivider; } bool TabPage::checkTimeIsOut(qint64 msTimeOut) { static qint64 lastTime=0; static QElapsedTimer systemUptime; if(!systemUptime.isValid()) { systemUptime.start(); return true; } if ((systemUptime.elapsed()-lastTime)>=msTimeOut) { lastTime=systemUptime.elapsed(); return true; } return false; } void TabPage::initUI() { m_mainLayout = new QVBoxLayout(this); m_mainLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); m_mainLayout->setSpacing(MAIN_LAYOUT_SPACING); this->setLayout(m_mainLayout); m_titleFrame = new QFrame(this); m_titleFrame->setFixedHeight(TITLE_FRAME_HEIGHT); m_titleLayout = new QHBoxLayout(m_titleFrame); m_titleLayout->setContentsMargins(TITLE_LAYOUT_MARGINS); m_titleLabel = new QLabel(m_titleFrame); m_netSwitch = new KSwitchButton(m_titleFrame); m_netSwitch->setTranslucent(true); m_titleLayout->addWidget(m_titleLabel); m_titleLayout->addStretch(); m_titleLayout->addWidget(m_netSwitch); m_titleDivider = new Divider(true, this); m_loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); m_waitTimer = new QTimer(this); connect(m_waitTimer, &QTimer::timeout, this, &TabPage::updateLoadingIcon); m_statusLabel = new QLabel(this); m_statusLabel->setProperty("useIconHighlightEffect", 0x2); m_statusLabel->hide(); m_titleLayout->addWidget(m_statusLabel); //临时增加的下拉框选择网卡区域 m_deviceFrame = new QFrame(this); m_deviceFrame->setFixedHeight(TITLE_FRAME_HEIGHT); m_deviceLayout = new QHBoxLayout(m_deviceFrame); m_deviceLayout->setContentsMargins(DEVICE_LAYOUT_MARGINS); m_deviceFrame->setLayout(m_deviceLayout); m_deviceLabel = new QLabel(m_deviceFrame); m_deviceLabel->setText(tr("Current Device")); m_deviceComboBox = new QComboBox(m_deviceFrame); m_deviceComboBox->setMinimumWidth(DEVICE_COMBOBOX_WIDTH); m_deviceComboBox->setMaximumWidth(DEVICE_COMBOBOX_WIDTH_MAX); m_deviceComboBox->setSizeAdjustPolicy(QComboBox::SizeAdjustPolicy::AdjustToContents); m_tipsLabel = new QLabel(m_deviceFrame); m_tipsLabel->setText(tr("Devices Closed!")); m_deviceLayout->addWidget(m_deviceLabel); m_deviceLayout->addStretch(); m_deviceLayout->addWidget(m_deviceComboBox); m_deviceLayout->addWidget(m_tipsLabel); connect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &TabPage::onDeviceComboxIndexChanged); m_activatedNetFrame = new QFrame(this); m_activatedNetFrame->setMaximumHeight(ACTIVE_AREA_MAX_HEIGHT); m_activatedNetLayout = new QVBoxLayout(m_activatedNetFrame); m_activatedNetLayout->setContentsMargins(ACTIVE_NET_LAYOUT_MARGINS); // m_activatedNetLayout->setSpacing(NET_LAYOUT_SPACING); m_activatedNetLabel = new QLabel(m_activatedNetFrame); m_activatedNetLabel->setContentsMargins(TEXT_MARGINS); m_activatedNetLabel->setFixedHeight(TEXT_HEIGHT); m_activatedNetLayout->addWidget(m_activatedNetLabel); m_activatedNetDivider = new Divider(true, this); m_inactivatedNetFrame = new QFrame(this); m_inactivatedNetFrame->setMinimumHeight(INACTIVE_AREA_MIN_HEIGHT); m_inactivatedNetLayout = new QVBoxLayout(m_inactivatedNetFrame); m_inactivatedNetLayout->setContentsMargins(NET_LAYOUT_MARGINS); // m_inactivatedNetLayout->setSpacing(NET_LAYOUT_SPACING); m_inactivatedNetFrame->setLayout(m_inactivatedNetLayout); m_inactivatedNetLabel = new QLabel(m_inactivatedNetFrame); m_inactivatedNetLabel->setContentsMargins(TEXT_MARGINS); m_inactivatedNetLabel->setFixedHeight(TEXT_HEIGHT); // m_inactivatedNetListArea = new QScrollArea(m_inactivatedNetFrame); // m_inactivatedNetListArea->setFrameShape(QFrame::Shape::NoFrame); // m_inactivatedNetListArea->setWidgetResizable(true); // m_inactivatedNetListArea->setBackgroundRole(QPalette::Base); // m_inactivatedNetListArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // m_inactivatedNetListArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_inactivatedNetListArea = new QWidget(m_inactivatedNetFrame); m_inactivatedAreaLayout = new QVBoxLayout(m_inactivatedNetListArea); m_inactivatedAreaLayout->setSpacing(MAIN_LAYOUT_SPACING); m_inactivatedAreaLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); // m_inactivatedNetListArea->setLayout(m_inactivatedAreaLayout); m_inactivatedNetLayout->addWidget(m_inactivatedNetLabel); m_inactivatedNetLayout->addWidget(m_inactivatedNetListArea); m_inactivatedNetDivider = new Divider(true, this); m_settingsFrame = new QFrame(this); m_settingsFrame->setFixedHeight(TITLE_FRAME_HEIGHT); m_settingsLayout = new QHBoxLayout(m_settingsFrame); m_settingsLayout->setContentsMargins(SETTINGS_LAYOUT_MARGINS); // m_settingsBtn = new KBorderlessButton(m_settingsFrame); // m_settingsBtn->setText(tr("Settings")); // m_settingsLayout->addWidget(m_settingsBtn); m_settingsLabel = new KyLable(m_settingsFrame); m_settingsLabel->setCursor(Qt::PointingHandCursor); m_settingsLabel->setText(tr("Settings")); m_settingsLabel->setScaledContents(true); m_settingsLayout->addWidget(m_settingsLabel); m_settingsLayout->addStretch(); m_settingsFrame->setLayout(m_settingsLayout); m_NoDeviceLabel = new KyLable(this); m_NoDeviceLabel->hide(); m_NoDeviceLabel->setText(tr("")); m_NoDeviceLabel->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter); m_mainLayout->addWidget(m_titleFrame); //临时增加的设备选择区域 m_mainLayout->addWidget(m_deviceFrame); m_mainLayout->addWidget(m_titleDivider); m_mainLayout->addWidget(m_activatedNetFrame); m_mainLayout->addWidget(m_activatedNetDivider); m_mainLayout->addWidget(m_inactivatedNetFrame); m_mainLayout->addStretch(); m_mainLayout->addWidget(m_NoDeviceLabel); m_mainLayout->addStretch(); m_mainLayout->addWidget(m_inactivatedNetDivider); m_mainLayout->addWidget(m_settingsFrame); // QPalette pal = m_inactivatedNetListArea->palette(); // pal.setBrush(QPalette::Base, QColor(0,0,0,0)); //背景透明 // m_inactivatedNetListArea->setPalette(pal); onPaletteChanged(); } void TabPage::initPanelGSettings() { const QByteArray id(PANEL_SETTINGS); if (QGSettings::isSchemaInstalled(id)) { if (m_panelGSettings == nullptr) { m_panelGSettings = new QGSettings(id, QByteArray(), this); } if (m_panelGSettings->keys().contains(PANEL_POSITION_KEY)) { m_panelPosition = m_panelGSettings->get(PANEL_POSITION_KEY).toInt(); } if (m_panelGSettings->keys().contains(PANEL_SIZE_KEY)) { m_panelSize = m_panelGSettings->get(PANEL_SIZE_KEY).toInt(); } connect(m_panelGSettings, &QGSettings::changed, this, [&] (const QString &key) { if (key == PANEL_POSITION_KEY) { m_panelPosition = m_panelGSettings->get(PANEL_POSITION_KEY).toInt(); } if (key == PANEL_SIZE_KEY) { m_panelSize = m_panelGSettings->get(PANEL_SIZE_KEY).toInt(); } }); } } void TabPage::onPaletteChanged() { QPalette labPal = m_activatedNetLabel->palette(); QColor color = this->palette().color(QPalette::PlaceholderText); labPal.setColor(QPalette::WindowText, color); m_activatedNetLabel->setPalette(labPal); m_inactivatedNetLabel->setPalette(labPal); if (m_deviceComboBox->view()) { QPalette view_pal = m_deviceComboBox->view()->palette(); QColor view_color = this->palette().color(QPalette::Active, QPalette::Button); view_pal.setColor(QPalette::Base, view_color); view_pal.setColor(QPalette::Text, this->palette().color(QPalette::Text)); view_pal.setColor(QPalette::WindowText, this->palette().color(QPalette::WindowText)); m_deviceComboBox->setPalette(view_pal); m_deviceComboBox->view()->setPalette(view_pal); } } int TabPage::getCurrentLoadRate(QString dev, long *save_rate, long *tx_rate) { FILE * net_dev_file; //文件指针 char buffer[1024]; //文件中的内容暂存在字符缓冲区里 //size_t bytes_read; //实际读取的内容大小 char * match; //用以保存所匹配字符串及之后的内容 char * device;//将QString转为Char * QByteArray ba = dev.toLatin1(); // must device = ba.data(); int counter = 0; //int i = 0; char tmp_value[128]; if ((NULL == device) || (NULL == save_rate) || (NULL == tx_rate)) { qDebug() << LOG_FLAG << "parameter pass error" ; return -1; } if ((net_dev_file = fopen("/proc/net/dev", "r")) == NULL) { //打开文件/pro/net/dev/,从中读取流量数据 qDebug() << LOG_FLAG << "error occurred when try to open file /proc/net/dev/"; return -1; } memset(buffer, 0, sizeof(buffer)); while (fgets(buffer, sizeof(buffer), net_dev_file) != NULL) { match = strstr(buffer, device); if (NULL == match) { // qDebug()<<"No eth0 keyword to find!"; continue; } else { match = match + qstrlen(device) + qstrlen(":"); //地址偏移到冒号 sscanf(match, "%ld ", save_rate); memset(tmp_value, 0, sizeof(tmp_value)); sscanf(match, "%s ", tmp_value); match = match + qstrlen(tmp_value); for (size_t i=0; igeometry(); int x, y; int margin = 8; switch (m_panelPosition) { case PanelPosition::Top: x = availableGeo.x() + availableGeo.width() - windowWidth - margin; y = availableGeo.y() + m_panelSize + margin; break; case PanelPosition::Bottom: x = availableGeo.x() + availableGeo.width() - windowWidth - margin; y = availableGeo.y() + availableGeo.height() - m_panelSize - windowHeight - margin; break; case PanelPosition::Left: x = availableGeo.x() + m_panelSize + margin; y = availableGeo.y() + availableGeo.height() - windowHeight - margin; break; case PanelPosition::Right: x = availableGeo.x() + availableGeo.width() - m_panelSize - windowWidth - margin; y = availableGeo.y() + availableGeo.height() - windowHeight - margin; break; } return QRect(x, y, windowWidth, windowHeight); } void TabPage::onSetNetSpeed(QListWidget* m_activatedNetListWidget, bool isEmpty, QString dev) { //未连接不显示网速 QListWidgetItem* activeitem = m_activatedNetListWidget->item(0); ListItem *p_item = (ListItem *)m_activatedNetListWidget->itemWidget(activeitem); if (isEmpty) { p_item->m_lbLoadUp->hide(); p_item->m_lbLoadDown->hide(); p_item->m_lbLoadDownImg->hide(); p_item->m_lbLoadUpImg->hide(); return; } if (this->isVisible()) { if (getCurrentLoadRate(dev, &start_rcv_rates, &start_tx_rates) == -1) { start_rcv_rates = end_rcv_rates; return; } long int delta_rcv = (start_rcv_rates - end_rcv_rates) / 1024; long int delta_tx = (start_tx_rates - end_tx_rates) / 1024; //简易滤波 if (delta_rcv < 0 || delta_tx < 0) { delta_rcv = 0; delta_tx = 0; } else if (end_rcv_rates == 0 || end_tx_rates == 0){ delta_rcv = 0; delta_tx = 0; } end_rcv_rates = start_rcv_rates; end_tx_rates = start_tx_rates; int rcv_num = delta_rcv; int tx_num = delta_tx; QString str_rcv = 0; QString str_tx = 0; if (rcv_num < 1024) { str_rcv = QString::number(rcv_num) + "KB/s"; } else { int remainder; if (rcv_num % 1024 < 100) { remainder = 0; } else { remainder = (rcv_num % 1024) / 100; } str_rcv = QString::number(rcv_num / 1024) + "." + QString::number(remainder) + "MB/s"; } if (tx_num < 1024) { str_tx = QString::number(tx_num) + "KB/s"; } else { int remainder; if (tx_num % 1024 < 100) { remainder = 0; } else { remainder = (tx_num % 1024)/100; } str_tx = QString::number(tx_num / 1024) + "." + QString::number(remainder) + "MB/s"; } p_item->m_lbLoadDown->setText(str_rcv); p_item->m_lbLoadUp->setText(str_tx); if (!p_item->m_hoverButton->isVisible()) { p_item->m_lbLoadDown->show(); p_item->m_lbLoadUp->show(); p_item->m_lbLoadDownImg->show(); p_item->m_lbLoadUpImg->show(); } } } void TabPage::showDesktopNotify(const QString &message, QString soundName) { QDBusInterface iface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus()); QStringList actions; //跳转动作 actions.append("default"); actions.append("kylin-nm"); //默认动作:点击消息体时打开麒麟录音 QMap hints; if (!soundName.isEmpty()) { hints.insert("sound-name",soundName); //添加声音 } QList args; args<<(tr("Kylin NM")) <<((unsigned int) 0) <beginGroup("DEFAULTCARD"); defaultDevice = m_settings->value(key).toString(); m_settings->endGroup(); delete m_settings; m_settings = nullptr; return defaultDevice; } void setDefaultDevice(KyDeviceType deviceType, QString deviceName) { QString key; switch (deviceType) { case WIRED: key = "wired"; break; case WIRELESS: key = "wireless"; break; default: return; } QSettings * m_settings = new QSettings(CONFIG_FILE_PATH, QSettings::IniFormat); m_settings->beginGroup("DEFAULTCARD"); m_settings->setValue(key, deviceName); m_settings->endGroup(); m_settings->sync(); delete m_settings; m_settings = nullptr; } bool checkDeviceExist(KyDeviceType deviceType, QString deviceName) { NetworkManager::Device::Type type; switch (deviceType) { case WIRED: type = NetworkManager::Device::Type::Ethernet; break; case WIRELESS: type = NetworkManager::Device::Type::Wifi; break; default: return false; break; } KyNetworkDeviceResourse * kdr = new KyNetworkDeviceResourse(); QStringList devList; devList.clear(); kdr->getNetworkDeviceList(type, devList); delete kdr; return devList.contains(deviceName); } void getDeviceEnableState(int type, QMap &map) { map.clear(); if (type != WIRED && type != WIRELESS) { qDebug() << "getDeviceEnableState but wrong type"; return; } KyNetworkDeviceResourse * kdr = new KyNetworkDeviceResourse(); QStringList wiredDevList,wirelessDevList; wiredDevList.clear(); wirelessDevList.clear(); if (type == WIRED) { kdr->getNetworkDeviceList(NetworkManager::Device::Type::Ethernet, wiredDevList); if (!wiredDevList.isEmpty()) { for (int i = 0; i < wiredDevList.size(); ++i) { QString devName = wiredDevList.at(i); map.insert(devName, kdr->getDeviceManaged(devName)); } } } else if (type == WIRELESS) { kdr->getNetworkDeviceList(NetworkManager::Device::Type::Wifi, wirelessDevList); if (!wirelessDevList.isEmpty()) { for (int i = 0; i < wirelessDevList.size(); ++i) { QString devName = wirelessDevList.at(i); map.insert(devName, kdr->getDeviceManaged(devName)); } } } delete kdr; kdr = nullptr; } bool getOldVersionWiredSwitchState(bool &state) { QSettings * m_settings = new QSettings(CONFIG_FILE_PATH, QSettings::IniFormat); QVariant value = m_settings->value("lan_switch_opened"); if (!value.isValid()) { delete m_settings; m_settings = nullptr; return false; } state = value.toBool(); m_settings->remove("lan_switch_opened"); delete m_settings; m_settings = nullptr; return true; } void TabPage::showNoDeiceInfo(bool visible,QString text) { m_NoDeviceLabel->setText(text); if(visible) { m_inactivatedNetFrame->hide(); m_activatedNetFrame->hide(); //m_deviceFrame->hide(); m_activatedNetDivider->hide(); m_inactivatedNetDivider->hide(); m_settingsFrame->hide(); m_NoDeviceLabel->resize(m_NoDeviceLabel->sizeHint()); // 设置标签大小以适应内容 m_NoDeviceLabel->show(); m_NoDeviceFlag=true; } else { m_NoDeviceLabel->hide(); m_inactivatedNetFrame->show(); m_activatedNetFrame->show(); m_activatedNetDivider->show(); m_inactivatedNetDivider->show(); //m_deviceFrame->show(); m_settingsFrame->show(); m_NoDeviceFlag=false; } } bool TabPage::isNoDevice() { return m_NoDeviceFlag; } void TabPage::updateLoadingIcon() { if (m_currentIconIndex > 6) { m_currentIconIndex = 0; } m_statusLabel->setPixmap(m_loadIcons.at(m_currentIconIndex).pixmap(ICONSIZE)); m_currentIconIndex ++; } void TabPage::startLoading() { m_waitTimer->start(FRAME_SPEED); m_netSwitch->hide(); m_statusLabel->setFocus(); m_statusLabel->show(); } void TabPage::stopLoading() { m_waitTimer->stop(); m_statusLabel->clearFocus(); m_statusLabel->hide(); m_netSwitch->show(); } QString TabPage::changeDeviceStateText(QString deviceName,int state) { QString finalShow=""; finalShow=deviceName+" "+(state==2? tr("connected"):tr("")); return finalShow; } void TabPage::updateDeviceConnectState(QString deviceName,int flag) { int index=0; int oldState=0; QString devStrState; if (!deviceName.isEmpty() && m_deviceState.contains(deviceName)) { oldState=m_deviceState[deviceName]; if(oldState!=flag) { m_deviceState[deviceName]=flag; index=m_deviceComboBox->findData(deviceName); if(index<0) { qDebug() << "cannt find " << deviceName; } devStrState=changeDeviceStateText(deviceName,flag); QFontMetrics fm(m_deviceComboBox->font()); int textWidth = fm.horizontalAdvance(devStrState); if (textWidth > DEVICE_COMBOBOX_WIDTH) { QString completeStr = devStrState; devStrState = fm.elidedText(devStrState, Qt::ElideRight, DEVICE_COMBOBOX_WIDTH); m_deviceComboBox->setToolTip(completeStr); } m_deviceComboBox->setItemText(index,devStrState); m_deviceComboBox->setItemData(index,deviceName); } } } void TabPage::replaceDeviceConnectState(QString oldName, QString newName) { int flag = 0; if (!newName.isEmpty() && m_deviceState.contains(oldName) && oldName!=newName) { flag=m_deviceState[oldName]; m_deviceState.remove(oldName); m_deviceState[newName]=flag;//不存在即创建 } } kylin-nm/src/frontend/tab-pages/wlanpage.h0000664000175000017500000002414615167651420017474 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef WLANPAGE_H #define WLANPAGE_H #include "tabpage.h" #include "kywirelessnetresource.h" #include "kylinactiveconnectresource.h" #include "kylinnetworkdeviceresource.h" #include "kywirelessconnectoperation.h" #include "wlanlistitem.h" #include "wlanmoreitem.h" #include "kylinconnectoperation.h" #include #include "netdetails/netdetail.h" #include #include "kylinactiveconnectresource.h" #include "kywirelessnetresource.h" #include "netdetails/joinhiddenwifipage.h" //#define SCROLLAREA_HEIGHT 150 #define MORE_TEXT_MARGINS 16,0,0,0 #define SCROLLAREA_HEIGHT 200 #define LAN_PAGE_INDEX 0 #define WLAN_PAGE_INDEX 1 #define NETWORK_ACCESS_DENIED 68 #define NETWORK_ACCESS_FULL 69 class WlanListItem; class WlanPage : public TabPage { Q_OBJECT public: explicit WlanPage(QWidget *parent = nullptr); ~WlanPage() = default; //for dbus void getWirelessList(QString devName, QList &list); //开启热点 void activeWirelessAp(const QString apName, const QString apPassword, const QString wirelessBand, const QString apDevice); //断开热点 void deactiveWirelessAp(const QString apName, const QString uuid); //获取热点 void getStoredApInfo(QStringList &list); void getApConnectionPath(QString &path, QString uuid); void getActiveConnectionPath(QString &path, QString uuid); void activateWirelessConnection(const QString& devName, const QString& ssid); void deactivateWirelessConnection(const QString& devName, const QString& ssid); void deactivateWirelessConnectionWithUuid(const QString devName, const QString uuid); void deleteWirelessConnect(const QString &connectUuid); void showDetailPage(QString devName, QString uuid); void showAddOtherPage(QString devName); bool checkWlanStatus(NetworkManager::ActiveConnection::State state); bool checkInternetLoading(); void getApInfoBySsid(QString devName, QString ssid, QStringList &list); //无线总开关 void setWirelessSwitchEnable(bool enable); void getWirelessDeviceCap(QMap &map); void getConnectivity(NetworkManager::Connectivity &connectivity); bool getWirelessSwitchBtnState(); int getActivateWifiSignal(QString devName = ""); //无线网卡连通性 void getWirelssDeviceConnectState(QMap &map); QString getCurrentDisplayDevice() { return m_currentDevice; } void getWirelssDeviceConnect(QMap &map); Q_SIGNALS: void oneItemExpanded(const QString &ssid); void wlanAdd(QString devName, QStringList info); void wlanRemove(QString devName,QString ssid); void wlanActiveConnectionStateChanged(QString interface, QString ssid, QString uuid, int status); void hotspotDeactivated(QString devName, QString ssid); void hotspotActivated(QString devName, QString ssid, QString uuid, QString activePath, QString settingPath); void hotspotDeactivating(QString devName, QString ssid); void hotspotActivating(QString devName, QString ssid); void signalStrengthChange(QString devName, QString ssid, int strength); void secuTypeChange(QString devName, QString ssid, QString secuType); void hiddenWlanClicked(); void wlanConnectChanged(int state); void timeToUpdate(); void showMainWindow(int type); void connectivityChanged(NetworkManager::Connectivity connectivity); void connectivityCheckSpareUriChanged(); void wirelessSwitchBtnChanged(bool state); public Q_SLOTS: void onMainWindowVisibleChanged(const bool &visible); void onSecurityTypeChange(QString devName, QString ssid, QString secuType); void requestScan(); void onWlanPageVisibleChanged(int index); private Q_SLOTS: void onWlanAdded(QString interface, KyWirelessNetItem &item); void onWlanRemoved(QString interface, QString ssid); void onConnectionAdd(QString deviceName, QString ssid); void onConnectionRemove(QString deviceName, QString ssid, QString path); void onConnectionUpdate(QString deviceName, QString ssid); void onDeviceAdd(QString deviceName, NetworkManager::Device::Type deviceType); void onDeviceRemove(QString deviceName); void onDeviceNameUpdate(QString oldName, QString newName); void onConnectionStateChanged(QString uuid, NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason); void onItemHeightChanged(const bool isExpanded, const QString &ssid); void onDeviceComboxIndexChanged(int currentIndex); void onHiddenWlanClicked(); void showControlCenter(); void onWifiEnabledChanged(bool isWifiOn); void onRefreshIconTimer(); void onWlanStateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason); void onDeviceManagedChanged(QString deviceName, bool managed); void onInactivateListWidgetItemChanged(QListWidgetItem *current, QListWidgetItem *previous); void setInactivateListItemNoSelect(); protected: bool eventFilter(QObject *watched, QEvent *event); private: //定时触发扫描的定时器 void initTimer(); void initWlanUI(); void initConnections(); void initDevice();//初始化默认设备 void initDeviceCombox(); void initWlanSwitchState(); void initWlanArea(); void addWlanMoreItem(); void showNonePwd(); void showRate(); void showHiddenWlanPage(QString devName); QListWidgetItem *addEmptyItem(QListWidget *wirelessListWidget); QListWidgetItem *addNewItem(KyWirelessNetItem &wirelessNetItem, QListWidget *wirelessListWidget); QListWidgetItem *insertNewItem(KyWirelessNetItem &wirelessNetItem, QListWidget *wirelessListWidget, int row); QListWidgetItem *insertNewItemWithSort(KyWirelessNetItem &wirelessNetItem, QListWidget *p_ListWidget); void clearWirelessNetItemMap(QMap &wirelessNetItem, QListWidget *wirelessListWidget); void deleteWirelessItemFormMap(QMap &wirelessNetItemMap, QListWidget *wirelessListWidget, QString ssid); void updateWlanItemState(QListWidget *p_wirelessListWidget, QListWidgetItem *p_listWidgetItem, ConnectState state); void updateWlanListItem(QString ssid, bool isConnnectRmove = false); void refreshActiveConnectionIcon(QString ssid, const int &signal); void constructWirelessNetArea(); void constructActivateConnectionArea(); void updateActivatedArea(QString uuid, QString ssid, QString devName); void updateWirelessNetArea(QString uuid, QString ssid, QString devName, QString path); void addDeviceToCombox(QString deviceName); void deleteDeviceFromCombox(QString deviceName); void updateDeviceForCombox(QString oldDeviceName, QString newDeviceName); void sendApStateChangeSignal(QString uuid, QString ssid, QString deviceName, NetworkManager::ActiveConnection::State state); // void wlanShowNotify(QString ssid, NetworkManager::ActiveConnection::State state, // NetworkManager::ActiveConnection::Reason reason); void initWirelssDeviceConnectState(); //是否存在可用的无线网卡 bool getWirelessDevieceUseable(); void setWirelessEnable(bool state); bool getWirelessEnable(); inline void setSwitchBtnState(bool state) { if (m_netSwitch != nullptr) { m_netSwitch->setChecked(state); } } inline bool getSwitchBtnState() { if (m_netSwitch != nullptr) { return m_netSwitch->isChecked(); } } inline void setSwitchBtnEnable(bool state) { if (m_netSwitch != nullptr) { m_netSwitch->setEnabled(state); } } inline bool getSwitchBtnEnable() { if (m_netSwitch != nullptr) { return m_netSwitch->isEnabled(); } } void checkShowWifi6Plus(); bool m_showWifi6Plus = true; QDBusInterface *m_usdInterface = nullptr; private: QMap m_wirelessNetItemMap; QMap m_activateConnectionItemMap; QListWidgetItem *m_expandedItem = nullptr; WlanMoreItem * m_hiddenWlanWidget = nullptr; QListWidgetItem *m_hiddenItem = nullptr; QListWidget * m_activatedNetListWidget = nullptr; QListWidget * m_inactivatedNetListWidget = nullptr; QStringList m_devList; QString m_currentDevice; KyWirelessNetResource *m_wirelessNetResource = nullptr; KyActiveConnectResourse *m_activatedConnectResource = nullptr; KyNetworkDeviceResourse *m_netDeviceResource = nullptr; KyWirelessConnectOperation * m_wirelessConnectOpreation = nullptr; KyConnectResourse * m_connectResource = nullptr; bool m_updateStrength = true; QTimer *m_scanTimer = nullptr; QTimer *m_refreshIconTimer = nullptr; QMap> m_wlanPagePtrMap; QMap m_joinHiddenWiFiPagePtrMap; }; #endif // WLANPAGE_H kylin-nm/src/frontend/tab-pages/tabpage.h0000664000175000017500000001543315167651420017300 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef TABPAGE_H #define TABPAGE_H #include "divider.h" #include "kylable.h" #include #include #include #include #include #include #include #include #include #include #include #include "kylinnetworkdeviceresource.h" #include "kwidget.h" #include "kswitchbutton.h" #include "kballontip.h" //#include "kborderlessbutton.h" #include #define EMPTY_SSID "emptyssid" #define REFRESH_NETWORKSPEED_TIMER 1000 using namespace kdk; #define MAIN_LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_SPACING 0 #define TITLE_FRAME_HEIGHT 50 //TabWidget的tab和widget有间隙,和设计稿看起来一致就不能设为设计稿里的高度 #define TITLE_LAYOUT_MARGINS 24,0,24,0 #define DEVICE_LAYOUT_MARGINS 24,0,24,8 #define DEVICE_COMBOBOX_WIDTH 180 #define DEVICE_COMBOBOX_WIDTH_MAX 230 #define ACTIVE_NET_LAYOUT_MARGINS 8,8,8,8 #define NET_LAYOUT_MARGINS 8,8,0,1 #define NET_LAYOUT_SPACING 8 #define NET_LIST_SPACING 0 #define TEXT_MARGINS 16,0,0,0 #define TEXT_HEIGHT 20 //#define SCROLL_AREA_HEIGHT 200 #define SETTINGS_LAYOUT_MARGINS 23,0,24,0 #define TRANSPARENT_COLOR QColor(0,0,0,0) #define INACTIVE_AREA_MIN_HEIGHT 170 #define ACTIVE_AREA_MAX_HEIGHT 130 #define MAX_ITEMS 4 #define MAX_WIDTH 412 #define MIN_WIDTH 404 #define SCROLL_STEP 4 #define FRAME_SPEED 150 enum KyDeviceType { WIRED, WIRELESS }; const QString CONFIG_FILE_DIR = QDir::homePath() + "/" + ".config/ukui"; const QString CONFIG_FILE_PATH = CONFIG_FILE_DIR + "/kylin-nm.conf"; bool checkDeviceExist(KyDeviceType deviceType, QString deviceName); QString getDefaultDeviceName(KyDeviceType deviceType); void setDefaultDevice(KyDeviceType deviceType, QString deviceName); void getDeviceEnableState(int type, QMap &map); bool getOldVersionWiredSwitchState(bool &state); class TabPage : public QWidget { Q_OBJECT public: explicit TabPage(QWidget *parent = nullptr); ~TabPage(); // void updateDefaultDevice(QString &deviceName); // QString getDefaultDevice(); static void showDesktopNotify(const QString &message, QString soundName); void showNoDeiceInfo(bool visible,QString text); void hideSetting() { if (nullptr != m_settingsFrame) { m_settingsFrame->hide(); m_inactivatedNetDivider->hide(); m_inactivatedNetFrame->setMinimumHeight(INACTIVE_AREA_MIN_HEIGHT + 100); } } void showSetting() { if (nullptr != m_settingsFrame) { m_inactivatedNetFrame->setMinimumHeight(INACTIVE_AREA_MIN_HEIGHT); m_settingsFrame->show(); m_inactivatedNetDivider->show(); } } enum PanelPosition{ Bottom = 0, //!< The bottom side of the screen. Top, //!< The top side of the screen. Left, //!< The left side of the screen. Right //!< The right side of the screen. }; bool checkTimeIsOut(qint64 msTimeOut); bool isNoDevice(); QString changeDeviceStateText(QString deviceName,int state); void replaceDeviceConnectState(QString oldName, QString newName); void updateDeviceConnectState(QString deviceName,int flag); Q_SIGNALS: void deviceStatusChanged(); void wirelessDeviceStatusChanged(); void deviceNameChanged(QString oldName, QString newName, int type); void activateFailed(QString errorMessage); void deactivateFailed(QString errorMessage); protected: void initUI(); void initPanelGSettings(); int getCurrentLoadRate(QString dev, long *save_rate, long *tx_rate); // virtual void initDevice() = 0;//初始化默认设备 virtual void initDeviceCombox() = 0;//初始化设备选择下拉框 QTimer *setNetSpeed = nullptr; QVBoxLayout * m_mainLayout = nullptr; QFrame * m_titleFrame = nullptr; QHBoxLayout * m_titleLayout = nullptr; QLabel * m_titleLabel = nullptr; KSwitchButton * m_netSwitch = nullptr; Divider * m_titleDivider = nullptr; QFrame * m_activatedNetFrame = nullptr; QVBoxLayout * m_activatedNetLayout = nullptr; QLabel * m_activatedNetLabel = nullptr; Divider * m_activatedNetDivider = nullptr; QFrame * m_inactivatedNetFrame = nullptr; QVBoxLayout * m_inactivatedNetLayout = nullptr; QLabel * m_inactivatedNetLabel = nullptr; // QScrollArea * m_inactivatedNetListArea = nullptr; QWidget * m_inactivatedNetListArea = nullptr; QVBoxLayout * m_inactivatedAreaLayout = nullptr; Divider * m_inactivatedNetDivider = nullptr; QFrame * m_settingsFrame = nullptr; QHBoxLayout * m_settingsLayout = nullptr; KyLable * m_settingsLabel = nullptr; // KBorderlessButton *m_settingsBtn = nullptr; //临时增加的下拉框选择网卡区域 QFrame * m_deviceFrame = nullptr; QHBoxLayout * m_deviceLayout = nullptr; QLabel * m_deviceLabel = nullptr; QComboBox * m_deviceComboBox = nullptr; QLabel * m_tipsLabel = nullptr; //增加的无网卡显示区域 KyLable *m_NoDeviceLabel = nullptr; bool m_NoDeviceFlag=true; long int start_rcv_rates = 0; //保存开始时的流量计数 long int end_rcv_rates = 0; //保存结束时的流量计数 long int start_tx_rates = 0; //保存开始时的流量计数 long int end_tx_rates = 0; //保存结束时的流量计数 //获取任务栏位置和大小 QGSettings *m_panelGSettings = nullptr; int m_panelPosition; int m_panelSize; QRect caculatePositionWithPanel(const int windowWidth, const int windowHeight); QMap m_deviceState ; QLabel *m_statusLabel; QTimer *m_waitTimer = nullptr; QList m_loadIcons; int m_currentIconIndex = 0; void updateLoadingIcon(); void startLoading(); void stopLoading(); public Q_SLOTS: virtual void onDeviceComboxIndexChanged(int currentIndex) = 0; void onPaletteChanged(); protected Q_SLOTS: void onSetNetSpeed(QListWidget* m_activatedNetListWidget, bool isActive, QString dev); }; #endif // TABPAGE_H kylin-nm/src/frontend/wificonfigdialog.h0000664000175000017500000000421415167646234017340 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef WIFICONFIGDIALOG_H #define WIFICONFIGDIALOG_H #include #include #include #include namespace Ui { class WiFiConfigDialog; } class WiFiConfigDialog : public QDialog { Q_OBJECT public: explicit WiFiConfigDialog(QWidget *parent = nullptr); ~WiFiConfigDialog(); void initTransparentState(); double getTransparentData(); void toConfigWifi(); void setEnableOfBtn(); protected: void paintEvent(QPaintEvent *event); private Q_SLOTS: void on_btnCancel_clicked(); void on_btnOk_clicked(); void on_leWifiId_textEdited(const QString &arg1); void on_leWiFiName_textEdited(const QString &arg1); void on_leWifiPassword_textEdited(const QString &arg1); void on_checkBoxPwd_clicked(); // void on_checkBoxPwd_released(); private: Ui::WiFiConfigDialog *ui; QGSettings *m_transparency_gsettings = nullptr; QString checkBoxQss = "QCheckBox {border:none;background:transparent;}" "QCheckBox::indicator {width: 18px; height: 9px;}" "QCheckBox::indicator:checked {image: url(:/res/h/show-pwd.png);}" "QCheckBox::indicator:unchecked {image: url(:/res/h/hide-pwd.png);}"; }; #endif // WIFICONFIGDIALOG_H kylin-nm/src/backend/0000775000175000017500000000000015167651420013423 5ustar fengfengkylin-nm/src/backend/dbus-interface/0000775000175000017500000000000015167651420016316 5ustar fengfengkylin-nm/src/backend/dbus-interface/dbus-interface.pri0000664000175000017500000000302315167646234021732 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/gsystem-local-alloc.h \ $$PWD/kyenterpricesettinginfo.h \ $$PWD/kylinactiveconnectresource.h \ $$PWD/kylinagent.h \ $$PWD/kylinagentinterface.h \ $$PWD/kylinapconnectitem.h \ $$PWD/kylinbluetoothconnectitem.h \ $$PWD/kylinconnectitem.h \ $$PWD/kylinconnectoperation.h \ $$PWD/kylinconnectresource.h \ $$PWD/kylinconnectsetting.h \ $$PWD/kylinnetworkdeviceresource.h \ $$PWD/kylinnetworkresourcemanager.h \ $$PWD/kylinutil.h \ $$PWD/kylinvpnconnectitem.h \ $$PWD/kylinvpnrequest.h \ $$PWD/kylinwiredconnectoperation.h \ $$PWD/kywirelessconnectoperation.h \ $$PWD/kywirelessnetitem.h \ $$PWD/kywirelessnetresource.h \ $$PWD/kyvpnconnectoperation.h \ $$PWD/nm-macros-internal.h SOURCES += \ $$PWD/kyenterpricesettinginfo.cpp \ $$PWD/kylinactiveconnectresource.cpp \ $$PWD/kylinagent.c \ $$PWD/kylinagentinterface.c \ $$PWD/kylinapconnectitem.cpp \ $$PWD/kylinbluetoothconnectitem.cpp \ $$PWD/kylinconnectitem.cpp \ $$PWD/kylinconnectoperation.cpp \ $$PWD/kylinconnectresource.cpp \ $$PWD/kylinconnectsetting.cpp \ $$PWD/kylinnetworkdeviceresource.cpp \ $$PWD/kylinnetworkresourcemanager.cpp \ $$PWD/kylinutil.cpp \ $$PWD/kylinvpnconnectitem.cpp \ $$PWD/kylinvpnrequest.c \ $$PWD/kylinwiredconnectoperation.cpp \ $$PWD/kywirelessconnectoperation.cpp \ $$PWD/kywirelessnetitem.cpp \ $$PWD/kyvpnconnectoperation.cpp \ $$PWD/kywirelessnetresource.cpp kylin-nm/src/backend/dbus-interface/kylinagentinterface.h0000664000175000017500000000201615167651420022514 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef __KYLINAGENTINTERFACE_H__ #define __KYLINAGENTINTERFACE_H__ #ifdef __cplusplus extern "C"{ void agent_init(); void agent_clear(); } #endif #endif // NMAGENT_H kylin-nm/src/backend/dbus-interface/kylinagent.c0000664000175000017500000007142115167651420020634 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #define KEYRING_UUID_TAG "connection-uuid" #define KEYRING_SN_TAG "setting-name" #define KEYRING_SK_TAG "setting-key" static const SecretSchema network_manager_secret_schema = { "org.freedesktop.NetworkManager.Connection", SECRET_SCHEMA_DONT_MATCH_NAME, { { KEYRING_UUID_TAG, SECRET_SCHEMA_ATTRIBUTE_STRING }, { KEYRING_SN_TAG, SECRET_SCHEMA_ATTRIBUTE_STRING }, { KEYRING_SK_TAG, SECRET_SCHEMA_ATTRIBUTE_STRING }, { NULL, 0 }, } }; G_DEFINE_TYPE (AppletAgent, applet_agent, NM_TYPE_SECRET_AGENT_OLD); #define APPLET_AGENT_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), APPLET_TYPE_AGENT, AppletAgentPrivate)) typedef struct { GHashTable *requests; gboolean vpn_only; gboolean disposed; } AppletAgentPrivate; enum { GET_SECRETS, CANCEL_SECRETS, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = { 0 }; /*******************************************************/ typedef struct { guint id; NMSecretAgentOld *agent; NMConnection *connection; char *path; char *setting_name; char **hints; guint32 flags; NMSecretAgentOldGetSecretsFunc get_callback; NMSecretAgentOldSaveSecretsFunc save_callback; NMSecretAgentOldDeleteSecretsFunc delete_callback; gpointer callback_data; GCancellable *cancellable; gint keyring_calls; } Request; static Request * request_new (NMSecretAgentOld *agent, NMConnection *connection, const char *connection_path, const char *setting_name, const char **hints, guint32 flags, NMSecretAgentOldGetSecretsFunc get_callback, NMSecretAgentOldSaveSecretsFunc save_callback, NMSecretAgentOldDeleteSecretsFunc delete_callback, gpointer callback_data) { static guint32 counter = 1; Request *r; r = g_slice_new0 (Request); r->id = counter++; r->agent = agent; r->connection = g_object_ref (connection); r->path = g_strdup (connection_path); r->setting_name = g_strdup (setting_name); if (hints) r->hints = g_strdupv ((gchar **) hints); r->flags = flags; r->get_callback = get_callback; r->save_callback = save_callback; r->delete_callback = delete_callback; r->callback_data = callback_data; r->cancellable = g_cancellable_new (); return r; } static void request_free (Request *r) { if (!g_cancellable_is_cancelled (r->cancellable)) g_hash_table_remove (APPLET_AGENT_GET_PRIVATE (r->agent)->requests, GUINT_TO_POINTER (r->id)); /* By the time the request is freed, all keyring calls should be completed */ g_warn_if_fail (r->keyring_calls == 0); g_object_unref (r->connection); g_free (r->path); g_free (r->setting_name); g_strfreev (r->hints); g_object_unref (r->cancellable); memset (r, 0, sizeof (*r)); g_slice_free (Request, r); } /*******************************************************/ static void get_save_cb (NMSecretAgentOld *agent, NMConnection *connection, GError *error, gpointer user_data) { /* Ignored */ } static void get_secrets_cb (AppletAgent *self, GVariant *secrets, GError *error, gpointer user_data) { Request *r = user_data; /* 'secrets' shouldn't be valid if there was an error */ if (error) { g_warn_if_fail (secrets == NULL); secrets = NULL; } if (!g_cancellable_is_cancelled (r->cancellable)) { /* Save updated secrets as long as user-interaction was allowed; otherwise * we'd be saving secrets we just pulled out of the keyring which is somewhat * redundant. */ if (secrets && (r->flags != NM_SECRET_AGENT_GET_SECRETS_FLAG_NONE)) { NMConnection *dupl; GVariantIter iter; const char *setting_name; /* Copy the existing connection and update its secrets */ dupl = nm_simple_connection_new_clone (r->connection); g_variant_iter_init (&iter, secrets); while (g_variant_iter_next (&iter, "{&s@a{sv}}", (gpointer) &setting_name, NULL)) nm_connection_update_secrets (dupl, setting_name, secrets, NULL); /* And save updated secrets to the keyring */ nm_secret_agent_old_save_secrets (NM_SECRET_AGENT_OLD (self), dupl, get_save_cb, NULL); g_object_unref (dupl); } r->get_callback (NM_SECRET_AGENT_OLD (r->agent), r->connection, secrets, error, r->callback_data); } request_free (r); } static void ask_for_secrets (Request *r) { /* Ask the applet to get some secrets for us */ g_signal_emit (r->agent, signals[GET_SECRETS], 0, GUINT_TO_POINTER (r->id), r->connection, r->setting_name, r->hints, r->flags, get_secrets_cb, r); } static void check_always_ask_cb (NMSetting *setting, const char *key, const GValue *value, GParamFlags flags, gpointer user_data) { gboolean *always_ask = user_data; NMSettingSecretFlags secret_flags = NM_SETTING_SECRET_FLAG_NONE; if (flags & NM_SETTING_PARAM_SECRET) { if (nm_setting_get_secret_flags (setting, key, &secret_flags, NULL)) { if (secret_flags & NM_SETTING_SECRET_FLAG_NOT_SAVED) *always_ask = TRUE; } } } static gboolean has_always_ask (NMSetting *setting) { gboolean always_ask = FALSE; nm_setting_enumerate_values (setting, check_always_ask_cb, &always_ask); return always_ask; } static gboolean is_connection_always_ask (NMConnection *connection) { NMSettingConnection *s_con; const char *ctype; NMSetting *setting; /* For the given connection type, check if the secrets for that connection * are always-ask or not. */ s_con = nm_connection_get_setting_connection (connection); g_assert (s_con); ctype = nm_setting_connection_get_connection_type (s_con); setting = nm_connection_get_setting_by_name (connection, ctype); g_return_val_if_fail (setting != NULL, FALSE); if (has_always_ask (setting)) return TRUE; /* Try type-specific settings too; be a bit paranoid and only consider * secrets from settings relevant to the connection type. */ if (NM_IS_SETTING_WIRELESS (setting)) { setting = nm_connection_get_setting (connection, NM_TYPE_SETTING_WIRELESS_SECURITY); if (setting && has_always_ask (setting)) return TRUE; setting = nm_connection_get_setting (connection, NM_TYPE_SETTING_802_1X); if (setting && has_always_ask (setting)) return TRUE; } else if (NM_IS_SETTING_WIRED (setting)) { setting = nm_connection_get_setting (connection, NM_TYPE_SETTING_PPPOE); if (setting && has_always_ask (setting)) return TRUE; setting = nm_connection_get_setting (connection, NM_TYPE_SETTING_802_1X); if (setting && has_always_ask (setting)) return TRUE; } return FALSE; } static void keyring_find_secrets_cb (GObject *source, GAsyncResult *result, gpointer user_data) { Request *r = user_data; GError *error = NULL; GError *search_error = NULL; const char *connection_id = NULL; GVariantBuilder builder_setting, builder_connection; GVariant *settings = NULL; GList *list = NULL; GList *iter; gboolean hint_found = FALSE, ask = FALSE; r->keyring_calls--; if (g_cancellable_is_cancelled (r->cancellable)) { /* Callback already called by NM or dispose */ request_free (r); return; } list = secret_service_search_finish (NULL, result, &search_error); connection_id = nm_connection_get_id (r->connection); if (g_error_matches (search_error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { error = g_error_new_literal (NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_USER_CANCELED, "The secrets request was canceled by the user"); g_error_free (search_error); goto done; } else if ( (r->flags & NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION) && g_error_matches (search_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN)) { /* If the connection always asks for secrets, tolerate * keyring service not being present. */ g_clear_error (&search_error); } else if (search_error) { error = g_error_new (NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, "%s.%d - failed to read secrets from keyring (%s)", __FILE__, __LINE__, search_error->message); g_error_free (search_error); goto done; } /* Only ask if we're allowed to, so that eg a connection editor which * requests secrets for its UI, for a connection which doesn't have any * secrets yet, doesn't trigger the applet secrets dialog. */ if ( (r->flags & NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION) && g_list_length (list) == 0) { g_message ("No keyring secrets found for %s/%s; asking user.", connection_id, r->setting_name); ask_for_secrets (r); return; } g_variant_builder_init (&builder_setting, NM_VARIANT_TYPE_SETTING); /* Extract the secrets from the list of matching keyring items */ for (iter = list; iter != NULL; iter = g_list_next (iter)) { SecretItem *item = iter->data; SecretValue *secret; const char *key_name; GHashTable *attributes; secret = secret_item_get_secret (item); if (secret) { attributes = secret_item_get_attributes (item); key_name = g_hash_table_lookup (attributes, KEYRING_SK_TAG); if (!key_name) { g_hash_table_unref (attributes); secret_value_unref (secret); continue; } g_variant_builder_add (&builder_setting, "{sv}", key_name, g_variant_new_string (secret_value_get (secret, NULL))); /* See if this property matches a given hint */ if (r->hints && r->hints[0]) { if (!g_strcmp0 (r->hints[0], key_name) || !g_strcmp0 (r->hints[1], key_name)) hint_found = TRUE; } g_hash_table_unref (attributes); secret_value_unref (secret); break; } } /* If there were hints, and none of the hints were returned by the keyring, * get some new secrets. */ if (r->flags) { if (r->hints && r->hints[0] && !hint_found) ask = TRUE; else if (r->flags & NM_SECRET_AGENT_GET_SECRETS_FLAG_REQUEST_NEW) { g_message ("New secrets for %s/%s requested; ask the user", connection_id, r->setting_name); ask = TRUE; } else if ( (r->flags & NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION) && is_connection_always_ask (r->connection)) ask = TRUE; } /* Returned secrets are a{sa{sv}}; this is the outer a{s...} hash that * will contain all the individual settings hashes. */ g_variant_builder_init (&builder_connection, NM_VARIANT_TYPE_CONNECTION); g_variant_builder_add (&builder_connection, "{sa{sv}}", r->setting_name, &builder_setting); settings = g_variant_builder_end (&builder_connection); done: g_list_free_full (list, g_object_unref); if (ask) { GVariantIter dict_iter; const char *setting_name; GVariant *setting_dict; /* Stuff all the found secrets into the connection for the UI to use */ g_variant_iter_init (&dict_iter, settings); while (g_variant_iter_next (&dict_iter, "{s@a{sv}}", &setting_name, &setting_dict)) { nm_connection_update_secrets (r->connection, setting_name, setting_dict, NULL); g_variant_unref (setting_dict); } ask_for_secrets (r); } else { /* Otherwise send the secrets back to NetworkManager */ r->get_callback (NM_SECRET_AGENT_OLD (r->agent), r->connection, error ? NULL : settings, error, r->callback_data); request_free (r); } if (settings) g_variant_unref (settings); g_clear_error (&error); } static void get_secrets (NMSecretAgentOld *agent, NMConnection *connection, const char *connection_path, const char *setting_name, const char **hints, guint32 flags, NMSecretAgentOldGetSecretsFunc callback, gpointer callback_data) { AppletAgentPrivate *priv = APPLET_AGENT_GET_PRIVATE (agent); Request *r; GError *error = NULL; NMSettingConnection *s_con; NMSetting *setting; const char *uuid, *ctype; GHashTable *attrs; setting = nm_connection_get_setting_by_name (connection, setting_name); if (!setting) { error = g_error_new (NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_INVALID_CONNECTION, "%s.%d - Connection didn't have requested setting '%s'.", __FILE__, __LINE__, setting_name); callback (agent, connection, NULL, error, callback_data); g_error_free (error); return; } uuid = nm_connection_get_uuid (connection); s_con = nm_connection_get_setting_connection (connection); g_assert (s_con); ctype = nm_setting_connection_get_connection_type (s_con); if (!uuid || !ctype) { error = g_error_new (NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_INVALID_CONNECTION, "%s.%d - Connection didn't have required UUID.", __FILE__, __LINE__); callback (agent, connection, NULL, error, callback_data); g_error_free (error); return; } /* Track the secrets request */ r = request_new (agent, connection, connection_path, setting_name, hints, flags, callback, NULL, NULL, callback_data); g_hash_table_insert (priv->requests, GUINT_TO_POINTER (r->id), r); /* VPN passwords are handled by the VPN plugin's auth dialog */ if (!strcmp (ctype, NM_SETTING_VPN_SETTING_NAME)) { ask_for_secrets (r); return; } /* Only handle non-VPN secrets if we're supposed to */ if (priv->vpn_only == TRUE) { error = g_error_new_literal (NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_NO_SECRETS, "Only handling VPN secrets at this time."); callback (agent, connection, NULL, error, callback_data); g_error_free (error); return; } /* For everything else we scrape the keyring for secrets first, and ask * later if required. */ attrs = secret_attributes_build (&network_manager_secret_schema, KEYRING_UUID_TAG, uuid, KEYRING_SN_TAG, setting_name, NULL); secret_service_search (NULL, &network_manager_secret_schema, attrs, SECRET_SEARCH_ALL | SECRET_SEARCH_UNLOCK | SECRET_SEARCH_LOAD_SECRETS, r->cancellable, keyring_find_secrets_cb, r); r->keyring_calls++; g_hash_table_unref (attrs); } /*******************************************************/ static void cancel_get_secrets (NMSecretAgentOld *agent, const char *connection_path, const char *setting_name) { AppletAgentPrivate *priv = APPLET_AGENT_GET_PRIVATE (agent); GHashTableIter iter; Request *r; GError *error; error = g_error_new_literal (NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_AGENT_CANCELED, "Canceled by NetworkManager"); g_hash_table_iter_init (&iter, priv->requests); while (g_hash_table_iter_next (&iter, NULL, (gpointer) &r)) { /* Only care about GetSecrets requests here */ if (r->get_callback == NULL) continue; /* Cancel any matching GetSecrets call */ if ( g_strcmp0 (r->path, connection_path) == 0 && g_strcmp0 (r->setting_name, setting_name) == 0) { /* cancel outstanding keyring operations */ g_cancellable_cancel (r->cancellable); r->get_callback (NM_SECRET_AGENT_OLD (r->agent), r->connection, NULL, error, r->callback_data); g_hash_table_iter_remove (&iter); g_signal_emit (r->agent, signals[CANCEL_SECRETS], 0, GUINT_TO_POINTER (r->id)); } } g_error_free (error); } /*******************************************************/ static void save_request_try_complete (Request *r) { /* Only call the SaveSecrets callback and free the request when all the * secrets have been saved to the keyring. */ if (r->keyring_calls == 0) { if (!g_cancellable_is_cancelled (r->cancellable)) r->save_callback (NM_SECRET_AGENT_OLD (r->agent), r->connection, NULL, r->callback_data); request_free (r); } } static void save_secret_cb (GObject *source, GAsyncResult *result, gpointer user_data) { secret_password_store_finish (result, NULL); save_request_try_complete (user_data); } static GHashTable * _create_keyring_add_attr_list (NMConnection *connection, const char *setting_name, const char *setting_key, char **out_display_name) { const char *connection_id, *connection_uuid; g_return_val_if_fail (connection != NULL, NULL); g_return_val_if_fail (setting_name != NULL, NULL); g_return_val_if_fail (setting_key != NULL, NULL); connection_uuid = nm_connection_get_uuid (connection); g_assert (connection_uuid); connection_id = nm_connection_get_id (connection); g_assert (connection_id); if (out_display_name) { *out_display_name = g_strdup_printf ("Network secret for %s/%s/%s", connection_id, setting_name, setting_key); } return secret_attributes_build (&network_manager_secret_schema, KEYRING_UUID_TAG, connection_uuid, KEYRING_SN_TAG, setting_name, KEYRING_SK_TAG, setting_key, NULL); } static void save_one_secret (Request *r, NMSetting *setting, const char *key, const char *secret, const char *display_name) { GHashTable *attrs; char *alt_display_name = NULL; const char *setting_name; NMSettingSecretFlags secret_flags = NM_SETTING_SECRET_FLAG_NONE; /* Don't system-owned or always-ask secrets */ if (!nm_setting_get_secret_flags (setting, key, &secret_flags, NULL)) return; if (secret_flags != NM_SETTING_SECRET_FLAG_AGENT_OWNED) return; setting_name = nm_setting_get_name (setting); g_assert (setting_name); attrs = _create_keyring_add_attr_list (r->connection, setting_name, key, display_name ? NULL : &alt_display_name); g_assert (attrs); secret_password_storev (&network_manager_secret_schema, attrs, NULL, display_name ? display_name : alt_display_name, secret, r->cancellable, save_secret_cb, r); r->keyring_calls++; g_hash_table_unref (attrs); g_free (alt_display_name); } static void vpn_secret_iter_cb (const char *key, const char *secret, gpointer user_data) { Request *r = user_data; NMSetting *setting; const char *service_name, *id; char *display_name; if (secret && strnlen (secret, sizeof(secret))) { setting = nm_connection_get_setting (r->connection, NM_TYPE_SETTING_VPN); g_assert (setting); service_name = nm_setting_vpn_get_service_type (NM_SETTING_VPN (setting)); g_assert (service_name); id = nm_connection_get_id (r->connection); g_assert (id); display_name = g_strdup_printf ("VPN %s secret for %s/%s/" NM_SETTING_VPN_SETTING_NAME, key, id, service_name); save_one_secret (r, setting, key, secret, display_name); g_free (display_name); } } static void write_one_secret_to_keyring (NMSetting *setting, const char *key, const GValue *value, GParamFlags flags, gpointer user_data) { Request *r = user_data; GType type = G_VALUE_TYPE (value); const char *secret; /* Non-secrets obviously don't get saved in the keyring */ if (!(flags & NM_SETTING_PARAM_SECRET)) return; if (NM_IS_SETTING_VPN (setting) && (g_strcmp0 (key, NM_SETTING_VPN_SECRETS) == 0)) { g_return_if_fail (type == G_TYPE_HASH_TABLE); /* Process VPN secrets specially since it's a hash of secrets, not just one */ nm_setting_vpn_foreach_secret (NM_SETTING_VPN (setting), vpn_secret_iter_cb, r); } else { /* FIXME: password-raw is not string */ if (!g_strcmp0 (key, NM_SETTING_802_1X_PASSWORD_RAW)) return; g_return_if_fail (type == G_TYPE_STRING); secret = g_value_get_string (value); if (secret && strnlen (secret, sizeof(secret))) save_one_secret (r, setting, key, secret, NULL); } } static void save_delete_cb (NMSecretAgentOld *agent, NMConnection *connection, GError *error, gpointer user_data) { Request *r = user_data; /* Ignore errors; now save all new secrets */ nm_connection_for_each_setting_value (connection, write_one_secret_to_keyring, r); /* If no secrets actually got saved there may be nothing to do so * try to complete the request here. If there were secrets to save the * request will get completed when those keyring calls return. */ save_request_try_complete (r); } static void save_secrets (NMSecretAgentOld *agent, NMConnection *connection, const char *connection_path, NMSecretAgentOldSaveSecretsFunc callback, gpointer callback_data) { AppletAgentPrivate *priv = APPLET_AGENT_GET_PRIVATE (agent); Request *r; r = request_new (agent, connection, connection_path, NULL, NULL, FALSE, NULL, callback, NULL, callback_data); g_hash_table_insert (priv->requests, GUINT_TO_POINTER (r->id), r); g_message("save secret ........................"); /* First delete any existing items in the keyring */ nm_secret_agent_old_delete_secrets (agent, connection, save_delete_cb, r); } /*******************************************************/ static void delete_find_items_cb (GObject *source, GAsyncResult *result, gpointer user_data) { Request *r = user_data; GError *secret_error = NULL; GError *error = NULL; r->keyring_calls--; if (g_cancellable_is_cancelled (r->cancellable)) { /* Callback already called by NM or dispose */ request_free (r); return; } secret_password_clear_finish (result, &secret_error); if (secret_error != NULL) { error = g_error_new (NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, "The request could not be completed (%s)", secret_error->message); g_error_free (secret_error); } r->delete_callback (r->agent, r->connection, error, r->callback_data); request_free (r); } static void delete_secrets (NMSecretAgentOld *agent, NMConnection *connection, const char *connection_path, NMSecretAgentOldDeleteSecretsFunc callback, gpointer callback_data) { AppletAgentPrivate *priv = APPLET_AGENT_GET_PRIVATE (agent); Request *r; NMSettingConnection *s_con; const char *uuid; r = request_new (agent, connection, connection_path, NULL, NULL, FALSE, NULL, NULL, callback, callback_data); g_hash_table_insert (priv->requests, GUINT_TO_POINTER (r->id), r); s_con = nm_connection_get_setting_connection (connection); g_assert (s_con); uuid = nm_setting_connection_get_uuid (s_con); g_assert (uuid); secret_password_clear (&network_manager_secret_schema, r->cancellable, delete_find_items_cb, r, KEYRING_UUID_TAG, uuid, NULL); r->keyring_calls++; } void applet_agent_handle_vpn_only (AppletAgent *agent, gboolean vpn_only) { g_return_if_fail (agent != NULL); g_return_if_fail (APPLET_IS_AGENT (agent)); APPLET_AGENT_GET_PRIVATE (agent)->vpn_only = vpn_only; } /*******************************************************/ AppletAgent * applet_agent_new (GError **error) { AppletAgent *agent; agent = g_object_new (APPLET_TYPE_AGENT, NM_SECRET_AGENT_OLD_IDENTIFIER, "org.freedesktop.nm-applet", NM_SECRET_AGENT_OLD_CAPABILITIES, NM_SECRET_AGENT_CAPABILITY_VPN_HINTS, NULL); if (!g_initable_init (G_INITABLE (agent), NULL, error)) { g_object_unref (agent); return NULL; } return agent; } static void applet_agent_init (AppletAgent *self) { AppletAgentPrivate *priv = APPLET_AGENT_GET_PRIVATE (self); priv->requests = g_hash_table_new (g_direct_hash, g_direct_equal); } static void dispose (GObject *object) { AppletAgent *self = APPLET_AGENT (object); AppletAgentPrivate *priv = APPLET_AGENT_GET_PRIVATE (self); if (!priv->disposed) { GHashTableIter iter; Request *r; /* Mark any outstanding requests as canceled */ g_hash_table_iter_init (&iter, priv->requests); while (g_hash_table_iter_next (&iter, NULL, (gpointer) &r)) g_cancellable_cancel (r->cancellable); g_hash_table_destroy (priv->requests); priv->disposed = TRUE; } G_OBJECT_CLASS (applet_agent_parent_class)->dispose (object); } static void applet_agent_class_init (AppletAgentClass *agent_class) { g_message("applet_agent_class_init........................"); GObjectClass *object_class = G_OBJECT_CLASS (agent_class); NMSecretAgentOldClass *parent_class = NM_SECRET_AGENT_OLD_CLASS (agent_class); g_type_class_add_private (agent_class, sizeof (AppletAgentPrivate)); /* virtual methods */ object_class->dispose = dispose; parent_class->get_secrets = get_secrets; parent_class->cancel_get_secrets = cancel_get_secrets; parent_class->save_secrets = save_secrets; parent_class->delete_secrets = delete_secrets; /* Signals */ signals[GET_SECRETS] = g_signal_new (APPLET_AGENT_GET_SECRETS, G_OBJECT_CLASS_TYPE (object_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (AppletAgentClass, get_secrets), NULL, NULL, NULL, G_TYPE_NONE, 7, G_TYPE_POINTER, G_TYPE_POINTER, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_UINT, G_TYPE_POINTER, G_TYPE_POINTER); signals[CANCEL_SECRETS] = g_signal_new (APPLET_AGENT_CANCEL_SECRETS, G_OBJECT_CLASS_TYPE (object_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (AppletAgentClass, cancel_secrets), NULL, NULL, NULL, G_TYPE_NONE, 1, G_TYPE_POINTER); } kylin-nm/src/backend/dbus-interface/kylinnetworkresourcemanager.h0000664000175000017500000002160015167651420024331 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include QString enumToQstring(NetworkManager::AccessPoint::Capabilities cap, NetworkManager::AccessPoint::WpaFlags wpa_flags,NetworkManager::AccessPoint::WpaFlags rsn_flags); class KyNetworkResourceManager : public QObject, public QDBusContext { Q_OBJECT public: static KyNetworkResourceManager* getInstance(); static void Release(); public: explicit KyNetworkResourceManager(QObject *parent = nullptr); ~KyNetworkResourceManager(); void removeActiveConnection(int pos); void clearActiveConnections(); void insertActiveConnections(); void addActiveConnection(NetworkManager::ActiveConnection::Ptr conn); void removeConnection(int pos); void clearConnections(); void insertConnections(); void addConnection(NetworkManager::Connection::Ptr conn); void removeDevice(int pos); void clearDevices(); void insertDevices(); void addDevice(NetworkManager::Device::Ptr conn); void removeWifiNetwork(int pos); void clearWifiNetworks(); void addWifiNetwork(NetworkManager::WirelessNetwork::Ptr net); NetworkManager::ActiveConnection::Ptr findActiveConnection(QString const & path); template NetworkManager::Device::Ptr findDevice(Predicate const & pred); NetworkManager::Device::Ptr findDeviceUni(QString const & uni); NetworkManager::Device::Ptr findDeviceInterface(QString const & interfaceName); NetworkManager::WirelessNetwork::Ptr findWifiNetwork(QString const & ssid, QString const & devUni); void requestScan(NetworkManager::WirelessDevice * dev); void removeConnection(QString const & uuid); void connectionDump(); public: NetworkManager::Device::Ptr getNetworkDevice(const QString ifaceName); NetworkManager::ActiveConnection::Ptr getActiveConnect(const QString activeConnectUuid); NetworkManager::Connection::Ptr getConnect(const QString uuid); NetworkManager::WirelessNetwork::Ptr getWifiNetwork(const QString apName); NetworkManager::ActiveConnection::List getActiveConnectList(); NetworkManager::Connection::List getConnectList(); NetworkManager::Device::List getNetworkDeviceList(); bool isActiveConnection(QString uuid); bool isActivatingConnection(QString uuid); NetworkManager::ActiveConnection::State getActiveConnectionState(const QString uuid); void getConnectivity(NetworkManager::Connectivity &connectivity); bool NetworkManagerIsInited(); Q_SIGNALS: void connectionAdd(QString uuid); void connectionUpdate(QString uuid); void connectionRemove(QString path); void deviceAdd(QString deviceName, QString uni, NetworkManager::Device::Type deviceType); void deviceUpdate(QString deviceName, QString deviceUni); void deviceRemove(QString deviceName, QString uni); void deviceManagedChange(QString deviceName, bool managed); void deviceActiveChanage(QString deviceName, bool deviceActive); void deviceCarrierChanage(QString deviceName, bool pluged); void deviceBitRateChanage(QString deviceName, int bitRate); void deviceMacAddressChanage(QString deviceName, const QString &hwAddress); void deviceConnectivityChanged(QString deviceName, const NetworkManager::Connectivity connectivity); //to KyWirelessNetResource void wifiNetworkRemoved(QString, QString); void wifiNetworkAdded(QString, QString); void wifiNetworkPropertyChange(QString, QString, int, QString, QString); void wifiNetworkSecuChange(NetworkManager::AccessPoint *); void wifiNetworkDeviceDisappear(); void wifiEnabledChanged(bool); void wiredEnabledChanged(bool); void connectivityCheckSpareUriChanged(); void activeConnectionsReset(); void activeConnectionAdd(QString uuid); void activeConnectionUpdate(QString uuid); void activeConnectionRemove(QString uuid); void activeConnectStateChangeReason(QString uuid, NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason); void vpnActiveConnectStateChangeReason(QString uuid, NetworkManager::VpnConnection::State state, NetworkManager::VpnConnection::StateChangeReason reason); void connectivityChanged(NetworkManager::Connectivity connectivity); void stateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason); void needShowDesktop(QString); public Q_SLOTS: void onInitNetwork(); void setWirelessNetworkEnabled(bool enabled); private Q_SLOTS: void insertWifiNetworks(); void onServiceAppear(QString, QString, QString); void onPropertiesChanged(QVariantMap qvm); //connection void onConnectionUpdated(); //void onConnectionRemoved(); //active connection void onActiveConnectionUpdated(); void onActiveConnectionChangedReason(NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason); void onActiveConnectionChanged(NetworkManager::ActiveConnection::State state); void onVpnActiveConnectChanagedReason(NetworkManager::VpnConnection::State state, NetworkManager::VpnConnection::StateChangeReason reason); //device void onDeviceActiveChanage(); void onDeviceUpdated(); void onDeviceManagedChange(); void onDeviceCarrierChanage(bool pluged); void onDeviceBitRateChanage(int bitRate); void onDeviceMacAddressChanage(const QString &hwAddress); void onDeviceStateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason); void onWifiNetworkAppeared(QString const & ssid); void onWifiNetworkDisappeared(QString const & ssid); void onDevicePropertiesChanged(QString interface, QVariantMap qvm); //wifi network void onUpdateWirelessNet(); void onWifiNetworkSecuChang(); //notifier void onDeviceAdded(QString const & uni); void onDeviceRemoved(QString const & uni); void onActiveConnectionAdded(QString const & path); void onActiveConnectionRemoved(QString const & path); //settings notifier void onConnectionAdded(QString const & path); void onConnectionRemoved(QString const & path); private: void onWifiNetworkAdd(NetworkManager::Device * dev, QString const & ssid); void onWifiNetworkUpdate(NetworkManager::WirelessNetwork * net); void onWifiNetworkRemove(NetworkManager::Device * dev, QString const & ssid); void onAccessPointUpdate(NetworkManager::WirelessNetwork * net); void onReferenceAccessPointChanged(); private: bool m_initFinished = false; public: static KyNetworkResourceManager* m_pInstance; NetworkManager::ActiveConnection::List m_activeConns; //已连接资源类 NetworkManager::Connection::List m_connections; //配置文件资源类 NetworkManager::Device::List m_devices; //设备类 NetworkManager::WirelessNetwork::List m_wifiNets; //无线热点类 }; #endif // KYLINNETWORKRESOURCEMANAGER_H kylin-nm/src/backend/dbus-interface/nm-macros-internal.h0000664000175000017500000013641015167651420022202 0ustar fengfeng /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef __NM_MACROS_INTERNAL_H__ #define __NM_MACROS_INTERNAL_H__ #include #include #include #define _nm_packed __attribute__ ((packed)) #define _nm_unused __attribute__ ((unused)) #define _nm_pure __attribute__ ((pure)) #define _nm_const __attribute__ ((const)) #define _nm_printf(a,b) __attribute__ ((__format__ (__printf__, a, b))) #define _nm_align(s) __attribute__ ((aligned (s))) #define _nm_alignof(type) __alignof (type) #define _nm_alignas(type) _nm_align (_nm_alignof (type)) #if __GNUC__ >= 7 #define _nm_fallthrough __attribute__ ((fallthrough)) #else #define _nm_fallthrough #endif /*****************************************************************************/ #ifdef thread_local #define _nm_thread_local thread_local /* * Don't break on glibc < 2.16 that doesn't define __STDC_NO_THREADS__ * see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=53769 */ #elif __STDC_VERSION__ >= 201112L && !(defined(__STDC_NO_THREADS__) || (defined(__GNU_LIBRARY__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 16)) #define _nm_thread_local _Thread_local #else #define _nm_thread_local __thread #endif /*****************************************************************************/ #if 0 #include "nm-glib.h" /*****************************************************************************/ #define nm_offsetofend(t,m) (G_STRUCT_OFFSET (t,m) + sizeof (((t *) NULL)->m)) #define nm_auto(fcn) __attribute__ ((cleanup(fcn))) static inline int nm_close (int fd); /** * nm_auto_free: * * Call free() on a variable location when it goes out of scope. */ #define nm_auto_free nm_auto(_nm_auto_free_impl) GS_DEFINE_CLEANUP_FUNCTION(void*, _nm_auto_free_impl, free) static inline void nm_free_secret (char *secret) { if (secret) { memset (secret, 0, strlen (secret)); g_free (secret); } } static inline void _nm_auto_free_secret_impl (char **v) { nm_free_secret (*v); } /** * nm_auto_free_secret: * * Call g_free() on a variable location when it goes out of scope. * Also, previously, calls memset(loc, 0, strlen(loc)) to clear out * the secret. */ #define nm_auto_free_secret nm_auto(_nm_auto_free_secret_impl) static inline void _nm_auto_unset_gvalue_impl (GValue *v) { g_value_unset (v); } #define nm_auto_unset_gvalue nm_auto(_nm_auto_unset_gvalue_impl) static inline void _nm_auto_unref_gtypeclass (gpointer v) { if (v && *((gpointer *) v)) g_type_class_unref (*((gpointer *) v)); } #define nm_auto_unref_gtypeclass nm_auto(_nm_auto_unref_gtypeclass) static inline void _nm_auto_free_gstring_impl (GString **str) { if (*str) g_string_free (*str, TRUE); } #define nm_auto_free_gstring nm_auto(_nm_auto_free_gstring_impl) static inline void _nm_auto_close_impl (int *pfd) { if (*pfd >= 0) { int errsv = errno; (void) nm_close (*pfd); errno = errsv; } } #define nm_auto_close nm_auto(_nm_auto_close_impl) static inline void _nm_auto_fclose_impl (FILE **pfd) { if (*pfd) { int errsv = errno; (void) fclose (*pfd); errno = errsv; } } #define nm_auto_fclose nm_auto(_nm_auto_fclose_impl) static inline void _nm_auto_protect_errno (int *p_saved_errno) { errno = *p_saved_errno; } #define NM_AUTO_PROTECT_ERRNO(errsv_saved) nm_auto(_nm_auto_protect_errno) _nm_unused const int errsv_saved = (errno) #endif /*****************************************************************************/ /* http://stackoverflow.com/a/11172679 */ #define _NM_UTILS_MACRO_FIRST(...) __NM_UTILS_MACRO_FIRST_HELPER(__VA_ARGS__, throwaway) #define __NM_UTILS_MACRO_FIRST_HELPER(first, ...) first #define _NM_UTILS_MACRO_REST(...) __NM_UTILS_MACRO_REST_HELPER(__NM_UTILS_MACRO_REST_NUM(__VA_ARGS__), __VA_ARGS__) #define __NM_UTILS_MACRO_REST_HELPER(qty, ...) __NM_UTILS_MACRO_REST_HELPER2(qty, __VA_ARGS__) #define __NM_UTILS_MACRO_REST_HELPER2(qty, ...) __NM_UTILS_MACRO_REST_HELPER_##qty(__VA_ARGS__) #define __NM_UTILS_MACRO_REST_HELPER_ONE(first) #define __NM_UTILS_MACRO_REST_HELPER_TWOORMORE(first, ...) , __VA_ARGS__ #define __NM_UTILS_MACRO_REST_NUM(...) \ __NM_UTILS_MACRO_REST_SELECT_30TH(__VA_ARGS__, \ TWOORMORE, TWOORMORE, TWOORMORE, TWOORMORE, TWOORMORE,\ TWOORMORE, TWOORMORE, TWOORMORE, TWOORMORE, TWOORMORE,\ TWOORMORE, TWOORMORE, TWOORMORE, TWOORMORE, TWOORMORE,\ TWOORMORE, TWOORMORE, TWOORMORE, TWOORMORE, TWOORMORE,\ TWOORMORE, TWOORMORE, TWOORMORE, TWOORMORE, TWOORMORE,\ TWOORMORE, TWOORMORE, TWOORMORE, ONE, throwaway) #define __NM_UTILS_MACRO_REST_SELECT_30TH(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, ...) a30 /*****************************************************************************/ /* http://stackoverflow.com/a/2124385/354393 */ #define NM_NARG(...) \ _NM_NARG(__VA_ARGS__,_NM_NARG_RSEQ_N()) #define _NM_NARG(...) \ _NM_NARG_ARG_N(__VA_ARGS__) #define _NM_NARG_ARG_N( \ _1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \ _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \ _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \ _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \ _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \ _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \ _61,_62,_63,N,...) N #define _NM_NARG_RSEQ_N() \ 63,62,61,60, \ 59,58,57,56,55,54,53,52,51,50, \ 49,48,47,46,45,44,43,42,41,40, \ 39,38,37,36,35,34,33,32,31,30, \ 29,28,27,26,25,24,23,22,21,20, \ 19,18,17,16,15,14,13,12,11,10, \ 9,8,7,6,5,4,3,2,1,0 /*****************************************************************************/ #if defined (__GNUC__) #define _NM_PRAGMA_WARNING_DO(warning) G_STRINGIFY(GCC diagnostic ignored warning) #elif defined (__clang__) #define _NM_PRAGMA_WARNING_DO(warning) G_STRINGIFY(clang diagnostic ignored warning) #endif /* you can only suppress a specific warning that the compiler * understands. Otherwise you will get another compiler warning * about invalid pragma option. * It's not that bad however, because gcc and clang often have the * same name for the same warning. */ #if defined (__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) #define NM_PRAGMA_WARNING_DISABLE(warning) \ _Pragma("GCC diagnostic push") \ _Pragma(_NM_PRAGMA_WARNING_DO(warning)) #elif defined (__clang__) #define NM_PRAGMA_WARNING_DISABLE(warning) \ _Pragma("clang diagnostic push") \ _Pragma(_NM_PRAGMA_WARNING_DO(warning)) #else #define NM_PRAGMA_WARNING_DISABLE(warning) #endif #if defined (__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) #define NM_PRAGMA_WARNING_REENABLE \ _Pragma("GCC diagnostic pop") #elif defined (__clang__) #define NM_PRAGMA_WARNING_REENABLE \ _Pragma("clang diagnostic pop") #else #define NM_PRAGMA_WARNING_REENABLE #endif /*****************************************************************************/ /** * NM_G_ERROR_MSG: * @error: (allow-none): the #GError instance * * All functions must follow the convention that when they * return a failure, they must also set the GError to a valid * message. For external API however, we want to be extra * careful before accessing the error instance. Use NM_G_ERROR_MSG() * which is safe to use on NULL. * * Returns: the error message. **/ static inline const char * NM_G_ERROR_MSG (GError *error) { return error ? (error->message ? : "(null)") : "(no-error)"; \ } /*****************************************************************************/ /* macro to return strlen() of a compile time string. */ #define NM_qstrlen(str) ( sizeof ("" str) - 1 ) /* returns the length of a NULL terminated array of pointers, * like g_strv_length() does. The difference is: * - it operats on arrays of pointers (of any kind, requiring no cast). * - it accepts NULL to return zero. */ #define NM_PTRARRAY_LEN(array) \ ({ \ typeof (*(array)) *const _array = (array); \ gsize _n = 0; \ \ if (_array) { \ _nm_unused typeof (*(_array[0])) *_array_check = _array[0]; \ while (_array[_n]) \ _n++; \ } \ _n; \ }) /* Note: @value is only evaluated when *out_val is present. * Thus, * NM_SET_OUT (out_str, g_strdup ("hallo")); * does the right thing. */ #define NM_SET_OUT(out_val, value) \ G_STMT_START { \ typeof(*(out_val)) *_out_val = (out_val); \ \ if (_out_val) { \ *_out_val = (value); \ } \ } G_STMT_END /*****************************************************************************/ #ifndef _NM_CC_SUPPORT_AUTO_TYPE #if (defined (__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9 ))) #define _NM_CC_SUPPORT_AUTO_TYPE 1 #else #define _NM_CC_SUPPORT_AUTO_TYPE 0 #endif #endif #ifndef _NM_CC_SUPPORT_GENERIC #if (defined (__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9 ))) || (defined (__clang__)) #define _NM_CC_SUPPORT_GENERIC 1 #else #define _NM_CC_SUPPORT_GENERIC 0 #endif #endif #if _NM_CC_SUPPORT_AUTO_TYPE #define _nm_auto_type __auto_type #endif #if _NM_CC_SUPPORT_GENERIC #define _NM_CONSTCAST_FULL_1(type, obj_expr, obj) \ (_Generic ((obj_expr), \ const void *const: ((const type *) (obj)), \ const void * : ((const type *) (obj)), \ void *const: (( type *) (obj)), \ void * : (( type *) (obj)), \ const type *const: ((const type *) (obj)), \ const type * : ((const type *) (obj)), \ type *const: (( type *) (obj)), \ type * : (( type *) (obj)))) #define _NM_CONSTCAST_FULL_2(type, obj_expr, obj, alias_type2) \ (_Generic ((obj_expr), \ const void *const: ((const type *) (obj)), \ const void * : ((const type *) (obj)), \ void *const: (( type *) (obj)), \ void * : (( type *) (obj)), \ const alias_type2 *const: ((const type *) (obj)), \ const alias_type2 * : ((const type *) (obj)), \ alias_type2 *const: (( type *) (obj)), \ alias_type2 * : (( type *) (obj)), \ const type *const: ((const type *) (obj)), \ const type * : ((const type *) (obj)), \ type *const: (( type *) (obj)), \ type * : (( type *) (obj)))) #define _NM_CONSTCAST_FULL_3(type, obj_expr, obj, alias_type2, alias_type3) \ (_Generic ((obj_expr), \ const void *const: ((const type *) (obj)), \ const void * : ((const type *) (obj)), \ void *const: (( type *) (obj)), \ void * : (( type *) (obj)), \ const alias_type2 *const: ((const type *) (obj)), \ const alias_type2 * : ((const type *) (obj)), \ alias_type2 *const: (( type *) (obj)), \ alias_type2 * : (( type *) (obj)), \ const alias_type3 *const: ((const type *) (obj)), \ const alias_type3 * : ((const type *) (obj)), \ alias_type3 *const: (( type *) (obj)), \ alias_type3 * : (( type *) (obj)), \ const type *const: ((const type *) (obj)), \ const type * : ((const type *) (obj)), \ type *const: (( type *) (obj)), \ type * : (( type *) (obj)))) #define _NM_CONSTCAST_FULL_4(type, obj_expr, obj, alias_type2, alias_type3, alias_type4) \ (_Generic ((obj_expr), \ const void *const: ((const type *) (obj)), \ const void * : ((const type *) (obj)), \ void *const: (( type *) (obj)), \ void * : (( type *) (obj)), \ const alias_type2 *const: ((const type *) (obj)), \ const alias_type2 * : ((const type *) (obj)), \ alias_type2 *const: (( type *) (obj)), \ alias_type2 * : (( type *) (obj)), \ const alias_type3 *const: ((const type *) (obj)), \ const alias_type3 * : ((const type *) (obj)), \ alias_type3 *const: (( type *) (obj)), \ alias_type3 * : (( type *) (obj)), \ const alias_type4 *const: ((const type *) (obj)), \ const alias_type4 * : ((const type *) (obj)), \ alias_type4 *const: (( type *) (obj)), \ alias_type4 * : (( type *) (obj)), \ const type *const: ((const type *) (obj)), \ const type * : ((const type *) (obj)), \ type *const: (( type *) (obj)), \ type * : (( type *) (obj)))) #define _NM_CONSTCAST_FULL_x(type, obj_expr, obj, n, ...) (_NM_CONSTCAST_FULL_##n (type, obj_expr, obj, ##__VA_ARGS__)) #define _NM_CONSTCAST_FULL_y(type, obj_expr, obj, n, ...) (_NM_CONSTCAST_FULL_x (type, obj_expr, obj, n, ##__VA_ARGS__)) #define NM_CONSTCAST_FULL( type, obj_expr, obj, ...) (_NM_CONSTCAST_FULL_y (type, obj_expr, obj, NM_NARG (dummy, ##__VA_ARGS__), ##__VA_ARGS__)) #else #define NM_CONSTCAST_FULL( type, obj_expr, obj, ...) ((type *) (obj)) #endif #define NM_CONSTCAST(type, obj, ...) \ NM_CONSTCAST_FULL(type, (obj), (obj), ##__VA_ARGS__) #define NM_GOBJECT_CAST(type, obj, is_check, ...) \ ({ \ const void *_obj = (obj); \ \ nm_assert (_obj || (is_check (_obj))); \ NM_CONSTCAST_FULL (type, (obj), _obj, GObject, ##__VA_ARGS__); \ }) #define NM_GOBJECT_CAST_NON_NULL(type, obj, is_check, ...) \ ({ \ const void *_obj = (obj); \ \ nm_assert (is_check (_obj)); \ NM_CONSTCAST_FULL (type, (obj), _obj, GObject, ##__VA_ARGS__); \ }) #if _NM_CC_SUPPORT_GENERIC /* returns @value, if the type of @value matches @type. * This requires support for C11 _Generic(). If no support is * present, this returns @value directly. * * It's useful to check the let the compiler ensure that @value is * of a certain type. */ #define _NM_ENSURE_TYPE(type, value) (_Generic ((value), type: (value))) #else #define _NM_ENSURE_TYPE(type, value) (value) #endif #if _NM_CC_SUPPORT_GENERIC #define NM_PROPAGATE_CONST(test_expr, ptr) \ (_Generic ((test_expr), \ const typeof (*(test_expr)) *: ((const typeof (*(ptr)) *) (ptr)), \ default: (_Generic ((test_expr), \ typeof (*(test_expr)) *: (ptr))))) #else #define NM_PROPAGATE_CONST(test_expr, ptr) (ptr) #endif /*****************************************************************************/ #define _NM_IN_SET_EVAL_1( op, _x, y) (_x == (y)) #define _NM_IN_SET_EVAL_2( op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_1 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_3( op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_2 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_4( op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_3 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_5( op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_4 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_6( op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_5 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_7( op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_6 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_8( op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_7 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_9( op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_8 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_10(op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_9 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_11(op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_10 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_12(op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_11 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_13(op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_12 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_14(op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_13 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_15(op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_14 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_16(op, _x, y, ...) (_x == (y)) op _NM_IN_SET_EVAL_15 (op, _x, __VA_ARGS__) #define _NM_IN_SET_EVAL_N2(op, _x, n, ...) (_NM_IN_SET_EVAL_##n(op, _x, __VA_ARGS__)) #define _NM_IN_SET_EVAL_N(op, type, x, n, ...) \ ({ \ type _x = (x); \ \ /* trigger a -Wenum-compare warning */ \ nm_assert (TRUE || _x == (x)); \ \ !!_NM_IN_SET_EVAL_N2(op, _x, n, __VA_ARGS__); \ }) #define _NM_IN_SET(op, type, x, ...) _NM_IN_SET_EVAL_N(op, type, x, NM_NARG (__VA_ARGS__), __VA_ARGS__) /* Beware that this does short-circuit evaluation (use "||" instead of "|") * which has a possibly unexpected non-function-like behavior. * Use NM_IN_SET_SE if you need all arguments to be evaluted. */ #define NM_IN_SET(x, ...) _NM_IN_SET(||, typeof (x), x, __VA_ARGS__) /* "SE" stands for "side-effect". Contrary to NM_IN_SET(), this does not do * short-circuit evaluation, which can make a difference if the arguments have * side-effects. */ #define NM_IN_SET_SE(x, ...) _NM_IN_SET(|, typeof (x), x, __VA_ARGS__) /* the *_TYPED forms allow to explicitly select the type of "x". This is useful * if "x" doesn't support typeof (bitfields) or you want to gracefully convert * a type using automatic type conversion rules (but not forcing the conversion * with a cast). */ #define NM_IN_SET_TYPED(type, x, ...) _NM_IN_SET(||, type, x, __VA_ARGS__) #define NM_IN_SET_SE_TYPED(type, x, ...) _NM_IN_SET(|, type, x, __VA_ARGS__) /*****************************************************************************/ static inline gboolean _NM_IN_STRSET_streq (const char *x, const char *s) { return s && strcmp (x, s) == 0; } #define _NM_IN_STRSET_EVAL_1( op, _x, y) _NM_IN_STRSET_streq (_x, y) #define _NM_IN_STRSET_EVAL_2( op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_1 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_3( op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_2 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_4( op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_3 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_5( op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_4 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_6( op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_5 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_7( op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_6 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_8( op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_7 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_9( op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_8 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_10(op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_9 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_11(op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_10 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_12(op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_11 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_13(op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_12 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_14(op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_13 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_15(op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_14 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_16(op, _x, y, ...) _NM_IN_STRSET_streq (_x, y) op _NM_IN_STRSET_EVAL_15 (op, _x, __VA_ARGS__) #define _NM_IN_STRSET_EVAL_N2(op, _x, n, ...) (_NM_IN_STRSET_EVAL_##n(op, _x, __VA_ARGS__)) #define _NM_IN_STRSET_EVAL_N(op, x, n, ...) \ ({ \ const char *_x = (x); \ ( ((_x == NULL) && _NM_IN_SET_EVAL_N2 (op, ((const char *) NULL), n, __VA_ARGS__)) \ || ((_x != NULL) && _NM_IN_STRSET_EVAL_N2 (op, _x, n, __VA_ARGS__)) \ ); \ }) /* Beware that this does short-circuit evaluation (use "||" instead of "|") * which has a possibly unexpected non-function-like behavior. * Use NM_IN_STRSET_SE if you need all arguments to be evaluted. */ #define NM_IN_STRSET(x, ...) _NM_IN_STRSET_EVAL_N(||, x, NM_NARG (__VA_ARGS__), __VA_ARGS__) /* "SE" stands for "side-effect". Contrary to NM_IN_STRSET(), this does not do * short-circuit evaluation, which can make a difference if the arguments have * side-effects. */ #define NM_IN_STRSET_SE(x, ...) _NM_IN_STRSET_EVAL_N(|, x, NM_NARG (__VA_ARGS__), __VA_ARGS__) #define NM_STRCHAR_ALL(str, ch_iter, predicate) \ ({ \ gboolean _val = TRUE; \ const char *_str = (str); \ \ if (_str) { \ for (;;) { \ const char ch_iter = _str[0]; \ \ if (ch_iter != '\0') { \ if (predicate) {\ _str++; \ continue; \ } \ _val = FALSE; \ } \ break; \ } \ } \ _val; \ }) #define NM_STRCHAR_ANY(str, ch_iter, predicate) \ ({ \ gboolean _val = FALSE; \ const char *_str = (str); \ \ if (_str) { \ for (;;) { \ const char ch_iter = _str[0]; \ \ if (ch_iter != '\0') { \ if (predicate) { \ ; \ } else { \ _str++; \ continue; \ } \ _val = TRUE; \ } \ break; \ } \ } \ _val; \ }) /*****************************************************************************/ /* NM_CACHED_QUARK() returns the GQuark for @string, but caches * it in a static variable to speed up future lookups. * * @string must be a string literal. */ #define NM_CACHED_QUARK(string) \ ({ \ static GQuark _nm_cached_quark = 0; \ \ (G_LIKELY (_nm_cached_quark != 0) \ ? _nm_cached_quark \ : (_nm_cached_quark = g_quark_from_static_string (""string""))); \ }) /* NM_CACHED_QUARK_FCN() is essentially the same as G_DEFINE_QUARK * with two differences: * - @string must be a quoted string-literal * - @fcn must be the full function name, while G_DEFINE_QUARK() appends * "_quark" to the function name. * Both properties of G_DEFINE_QUARK() are non favorable, because you can no * longer grep for string/fcn -- unless you are aware that you are searching * for G_DEFINE_QUARK() and omit quotes / append _quark(). With NM_CACHED_QUARK_FCN(), * ctags/cscope can locate the use of @fcn (though it doesn't recognize that * NM_CACHED_QUARK_FCN() defines it). */ #define NM_CACHED_QUARK_FCN(string, fcn) \ GQuark \ fcn (void) \ { \ return NM_CACHED_QUARK (string); \ } /*****************************************************************************/ #define nm_streq(s1, s2) (strcmp (s1, s2) == 0) #define nm_streq0(s1, s2) (g_strcmp0 (s1, s2) == 0) /*****************************************************************************/ static inline GString * nm_gstring_prepare (GString **l) { if (*l) g_string_set_size (*l, 0); else *l = g_string_sized_new (30); return *l; } static inline const char * nm_str_not_empty (const char *str) { return str && str[0] ? str : NULL; } static inline char * nm_strdup_not_empty (const char *str) { return str && str[0] ? g_strdup (str) : NULL; } static inline char * nm_str_realloc (char *str) { gs_free char *s = str; /* Returns a new clone of @str and frees @str. The point is that @str * possibly points to a larger chunck of memory. We want to freshly allocate * a buffer. * * We could use realloc(), but that might not do anything or leave * @str in its memory pool for chunks of a different size (bad for * fragmentation). * * This is only useful when we want to keep the buffer around for a long * time and want to re-allocate a more optimal buffer. */ return g_strdup (s); } /*****************************************************************************/ #define NM_PRINT_FMT_QUOTED(cond, prefix, str, suffix, str_else) \ (cond) ? (prefix) : "", \ (cond) ? (str) : (str_else), \ (cond) ? (suffix) : "" #define NM_PRINT_FMT_QUOTE_STRING(arg) NM_PRINT_FMT_QUOTED((arg), "\"", (arg), "\"", "(null)") /*****************************************************************************/ /* glib/C provides the following kind of assertions: * - assert() -- disable with NDEBUG * - g_return_if_fail() -- disable with G_DISABLE_CHECKS * - g_assert() -- disable with G_DISABLE_ASSERT * but they are all enabled by default and usually even production builds have * these kind of assertions enabled. It also means, that disabling assertions * is an untested configuration, and might have bugs. * * Add our own assertion macro nm_assert(), which is disabled by default and must * be explicitly enabled. They are useful for more expensive checks or checks that * depend less on runtime conditions (that is, are generally expected to be true). */ #ifndef NM_MORE_ASSERTS #define NM_MORE_ASSERTS 0 #endif #if NM_MORE_ASSERTS #define nm_assert(cond) G_STMT_START { g_assert (cond); } G_STMT_END #define nm_assert_se(cond) G_STMT_START { if (G_LIKELY (cond)) { ; } else { g_assert (FALSE && (cond)); } } G_STMT_END #define nm_assert_not_reached() G_STMT_START { g_assert_not_reached (); } G_STMT_END #else #define nm_assert(cond) G_STMT_START { if (FALSE) { if (cond) { } } } G_STMT_END #define nm_assert_se(cond) G_STMT_START { if (G_LIKELY (cond)) { ; } } G_STMT_END #define nm_assert_not_reached() G_STMT_START { ; } G_STMT_END #endif /*****************************************************************************/ #define NM_GOBJECT_PROPERTIES_DEFINE_BASE(...) \ typedef enum { \ _PROPERTY_ENUMS_0, \ __VA_ARGS__ \ _PROPERTY_ENUMS_LAST, \ } _PropertyEnums; \ static GParamSpec *obj_properties[_PROPERTY_ENUMS_LAST] = { NULL, } #define NM_GOBJECT_PROPERTIES_DEFINE(obj_type, ...) \ NM_GOBJECT_PROPERTIES_DEFINE_BASE (__VA_ARGS__); \ static inline void \ _notify (obj_type *obj, _PropertyEnums prop) \ { \ nm_assert (G_IS_OBJECT (obj)); \ nm_assert ((gsize) prop < G_N_ELEMENTS (obj_properties)); \ g_object_notify_by_pspec ((GObject *) obj, obj_properties[prop]); \ } /*****************************************************************************/ #define _NM_GET_PRIVATE(self, type, is_check, ...) (&(NM_GOBJECT_CAST_NON_NULL (type, (self), is_check, ##__VA_ARGS__)->_priv)) #if _NM_CC_SUPPORT_AUTO_TYPE #define _NM_GET_PRIVATE_PTR(self, type, is_check, ...) \ ({ \ _nm_auto_type _self = NM_GOBJECT_CAST_NON_NULL (type, (self), is_check, ##__VA_ARGS__); \ \ NM_PROPAGATE_CONST (_self, _self->_priv); \ }) #else #define _NM_GET_PRIVATE_PTR(self, type, is_check, ...) (NM_GOBJECT_CAST_NON_NULL (type, (self), is_check, ##__VA_ARGS__)->_priv) #endif /*****************************************************************************/ static inline gpointer nm_g_object_ref (gpointer obj) { /* g_object_ref() doesn't accept NULL. */ if (obj) g_object_ref (obj); return obj; } #define nm_g_object_ref(obj) ((typeof (obj)) nm_g_object_ref (obj)) static inline void nm_g_object_unref (gpointer obj) { /* g_object_unref() doesn't accept NULL. Usully, we workaround that * by using g_clear_object(), but sometimes that is not convinient * (for example as as destroy function for a hash table that can contain * NULL values). */ if (obj) g_object_unref (obj); } /* Assigns GObject @obj to destination @pdst, and takes an additional ref. * The previous value of @pdst is unrefed. * * It makes sure to first increase the ref-count of @obj, and handles %NULL * @obj correctly. * */ #define nm_g_object_ref_set(pp, obj) \ ({ \ typeof (*(pp)) *const _pp = (pp); \ typeof (**_pp) *const _obj = (obj); \ typeof (**_pp) *_p; \ gboolean _changed = FALSE; \ \ if ( _pp \ && ((_p = *_pp) != _obj)) { \ if (_obj) { \ nm_assert (G_IS_OBJECT (_obj)); \ g_object_ref (_obj); \ } \ if (_p) { \ nm_assert (G_IS_OBJECT (_p)); \ *_pp = NULL; \ g_object_unref (_p); \ } \ *_pp = _obj; \ _changed = TRUE; \ } \ _changed; \ }) /* basically, replaces * g_clear_pointer (&location, g_free) * with * nm_clear_g_free (&location) * * Another advantage is that by using a macro and typeof(), it is more * typesafe and gives you for example a compiler warning when pp is a const * pointer or points to a const-pointer. */ #define nm_clear_g_free(pp) \ ({ \ typeof (*(pp)) *_pp = (pp); \ typeof (**_pp) *_p; \ gboolean _changed = FALSE; \ \ if ( _pp \ && (_p = *_pp)) { \ *_pp = NULL; \ g_free (_p); \ _changed = TRUE; \ } \ _changed; \ }) #define nm_clear_g_object(pp) \ ({ \ typeof (*(pp)) *_pp = (pp); \ typeof (**_pp) *_p; \ gboolean _changed = FALSE; \ \ if ( _pp \ && (_p = *_pp)) { \ nm_assert (G_IS_OBJECT (_p)); \ *_pp = NULL; \ g_object_unref (_p); \ _changed = TRUE; \ } \ _changed; \ }) static inline gboolean nm_clear_g_source (guint *id) { if (id && *id) { g_source_remove (*id); *id = 0; return TRUE; } return FALSE; } static inline gboolean nm_clear_g_signal_handler (gpointer self, gulong *id) { if (id && *id) { g_signal_handler_disconnect (self, *id); *id = 0; return TRUE; } return FALSE; } static inline gboolean nm_clear_g_variant (GVariant **variant) { if (variant && *variant) { g_variant_unref (*variant); *variant = NULL; return TRUE; } return FALSE; } static inline gboolean nm_clear_g_cancellable (GCancellable **cancellable) { if (cancellable && *cancellable) { g_cancellable_cancel (*cancellable); g_object_unref (*cancellable); *cancellable = NULL; return TRUE; } return FALSE; } /*****************************************************************************/ /* Determine whether @x is a power of two (@x being an integer type). * Basically, this returns TRUE, if @x has exactly one bit set. * For negative values and zero, this always returns FALSE. */ #define nm_utils_is_power_of_two(x) ({ \ typeof(x) __x = (x); \ \ ( (__x > ((typeof(__x)) 0)) \ && ((__x & (__x - (((typeof(__x)) 1)))) == ((typeof(__x)) 0))); \ }) /*****************************************************************************/ #define NM_UTILS_LOOKUP_DEFAULT(v) return (v) #define NM_UTILS_LOOKUP_DEFAULT_WARN(v) g_return_val_if_reached (v) #define NM_UTILS_LOOKUP_DEFAULT_NM_ASSERT(v) { nm_assert_not_reached (); return (v); } #define NM_UTILS_LOOKUP_ITEM(v, n) (void) 0; case v: return (n); (void) 0 #define NM_UTILS_LOOKUP_STR_ITEM(v, n) NM_UTILS_LOOKUP_ITEM(v, ""n"") #define NM_UTILS_LOOKUP_ITEM_IGNORE(v) (void) 0; case v: break; (void) 0 #define NM_UTILS_LOOKUP_ITEM_IGNORE_OTHER() (void) 0; default: break; (void) 0 #define _NM_UTILS_LOOKUP_DEFINE(scope, fcn_name, lookup_type, result_type, unknown_val, ...) \ scope result_type \ fcn_name (lookup_type val) \ { \ switch (val) { \ (void) 0, \ __VA_ARGS__ \ (void) 0; \ }; \ { unknown_val; } \ } #define NM_UTILS_LOOKUP_STR_DEFINE(fcn_name, lookup_type, unknown_val, ...) \ _NM_UTILS_LOOKUP_DEFINE (, fcn_name, lookup_type, const char *, unknown_val, __VA_ARGS__) #define NM_UTILS_LOOKUP_STR_DEFINE_STATIC(fcn_name, lookup_type, unknown_val, ...) \ _NM_UTILS_LOOKUP_DEFINE (static, fcn_name, lookup_type, const char *, unknown_val, __VA_ARGS__) /* Call the string-lookup-table function @fcn_name. If the function returns * %NULL, the numeric index is converted to string using a alloca() buffer. * Beware: this macro uses alloca(). */ #define NM_UTILS_LOOKUP_STR(fcn_name, idx) \ ({ \ typeof (idx) _idx = (idx); \ const char *_s; \ \ _s = fcn_name (_idx); \ if (!_s) { \ _s = g_alloca (30); \ \ g_snprintf ((char *) _s, 30, "(%lld)", (long long) _idx); \ } \ _s; \ }) /*****************************************************************************/ /* check if @flags has exactly one flag (@check) set. You should call this * only with @check being a compile time constant and a power of two. */ #define NM_FLAGS_HAS(flags, check) \ ( G_STATIC_ASSERT_EXPR ((check) > 0 && ((check) & ((check) - 1)) == 0), NM_FLAGS_ANY ((flags), (check)) ) #define NM_FLAGS_ANY(flags, check) ( ( ((flags) & (check)) != 0 ) ? TRUE : FALSE ) #define NM_FLAGS_ALL(flags, check) ( ( ((flags) & (check)) == (check) ) ? TRUE : FALSE ) #define NM_FLAGS_SET(flags, val) ({ \ const typeof(flags) _flags = (flags); \ const typeof(flags) _val = (val); \ \ _flags | _val; \ }) #define NM_FLAGS_UNSET(flags, val) ({ \ const typeof(flags) _flags = (flags); \ const typeof(flags) _val = (val); \ \ _flags & (~_val); \ }) #define NM_FLAGS_ASSIGN(flags, val, assign) ({ \ const typeof(flags) _flags = (flags); \ const typeof(flags) _val = (val); \ \ (assign) \ ? _flags | (_val) \ : _flags & (~_val); \ }) /*****************************************************************************/ #define _NM_BACKPORT_SYMBOL_IMPL(VERSION, RETURN_TYPE, ORIG_FUNC, VERSIONED_FUNC, ARGS_TYPED, ARGS) \ RETURN_TYPE VERSIONED_FUNC ARGS_TYPED; \ RETURN_TYPE VERSIONED_FUNC ARGS_TYPED \ { \ return ORIG_FUNC ARGS; \ } \ RETURN_TYPE ORIG_FUNC ARGS_TYPED; \ __asm__(".symver "G_STRINGIFY(VERSIONED_FUNC)", "G_STRINGIFY(ORIG_FUNC)"@"G_STRINGIFY(VERSION)) #define NM_BACKPORT_SYMBOL(VERSION, RETURN_TYPE, FUNC, ARGS_TYPED, ARGS) \ _NM_BACKPORT_SYMBOL_IMPL(VERSION, RETURN_TYPE, FUNC, _##FUNC##_##VERSION, ARGS_TYPED, ARGS) /*****************************************************************************/ #define nm_str_skip_leading_spaces(str) \ ({ \ typeof (*(str)) *_str = (str); \ _nm_unused const char *_str_type_check = _str; \ \ if (_str) { \ while (g_ascii_isspace (_str[0])) \ _str++; \ } \ _str; \ }) static inline char * nm_strstrip (char *str) { /* g_strstrip doesn't like NULL. */ return str ? g_strstrip (str) : NULL; } static inline const char * nm_strstrip_avoid_copy (const char *str, char **str_free) { gsize l; char *s; nm_assert (str_free && !*str_free); if (!str) return NULL; str = nm_str_skip_leading_spaces (str); l = strnlen (str, sizeof(str)); if ( l == 0 || !g_ascii_isspace (str[l - 1])) return str; while ( l > 0 && g_ascii_isspace (str[l - 1])) l--; s = g_new (char, l + 1); memcpy (s, str, l); s[l] = '\0'; *str_free = s; return s; } /* g_ptr_array_sort()'s compare function takes pointers to the * value. Thus, you cannot use strcmp directly. You can use * nm_strcmp_p(). * * Like strcmp(), this function is not forgiving to accept %NULL. */ static inline int nm_strcmp_p (gconstpointer a, gconstpointer b) { const char *s1 = *((const char **) a); const char *s2 = *((const char **) b); return strcmp (s1, s2); } /* like nm_strcmp_p(), suitable for g_ptr_array_sort_with_data(). * g_ptr_array_sort() just casts nm_strcmp_p() to a function of different * signature. I guess, in glib there are knowledgeable people that ensure * that this additional argument doesn't cause problems due to different ABI * for every architecture that glib supports. * For NetworkManager, we'd rather avoid such stunts. **/ static inline int nm_strcmp_p_with_data (gconstpointer a, gconstpointer b, gpointer user_data) { const char *s1 = *((const char **) a); const char *s2 = *((const char **) b); return strcmp (s1, s2); } static inline int nm_cmp_uint32_p_with_data (gconstpointer p_a, gconstpointer p_b, gpointer user_data) { const guint32 a = *((const guint32 *) p_a); const guint32 b = *((const guint32 *) p_b); if (a < b) return -1; if (a > b) return 1; return 0; } /*****************************************************************************/ /* Taken from systemd's UNIQ_T and UNIQ macros. */ #define NM_UNIQ_T(x, uniq) G_PASTE(__unique_prefix_, G_PASTE(x, uniq)) #define NM_UNIQ __COUNTER__ /*****************************************************************************/ /* glib's MIN()/MAX() macros don't have function-like behavior, in that they evaluate * the argument possibly twice. * * Taken from systemd's MIN()/MAX() macros. */ #define NM_MIN(a, b) __NM_MIN(NM_UNIQ, a, NM_UNIQ, b) #define __NM_MIN(aq, a, bq, b) \ ({ \ typeof (a) NM_UNIQ_T(A, aq) = (a); \ typeof (b) NM_UNIQ_T(B, bq) = (b); \ ((NM_UNIQ_T(A, aq) < NM_UNIQ_T(B, bq)) ? NM_UNIQ_T(A, aq) : NM_UNIQ_T(B, bq)); \ }) #define NM_MAX(a, b) __NM_MAX(NM_UNIQ, a, NM_UNIQ, b) #define __NM_MAX(aq, a, bq, b) \ ({ \ typeof (a) NM_UNIQ_T(A, aq) = (a); \ typeof (b) NM_UNIQ_T(B, bq) = (b); \ ((NM_UNIQ_T(A, aq) > NM_UNIQ_T(B, bq)) ? NM_UNIQ_T(A, aq) : NM_UNIQ_T(B, bq)); \ }) #define NM_CLAMP(x, low, high) __NM_CLAMP(NM_UNIQ, x, NM_UNIQ, low, NM_UNIQ, high) #define __NM_CLAMP(xq, x, lowq, low, highq, high) \ ({ \ typeof(x)NM_UNIQ_T(X,xq) = (x); \ typeof(low) NM_UNIQ_T(LOW,lowq) = (low); \ typeof(high) NM_UNIQ_T(HIGH,highq) = (high); \ \ ( (NM_UNIQ_T(X,xq) > NM_UNIQ_T(HIGH,highq)) \ ? NM_UNIQ_T(HIGH,highq) \ : (NM_UNIQ_T(X,xq) < NM_UNIQ_T(LOW,lowq)) \ ? NM_UNIQ_T(LOW,lowq) \ : NM_UNIQ_T(X,xq)); \ }) /*****************************************************************************/ static inline guint nm_encode_version (guint major, guint minor, guint micro) { /* analog to the preprocessor macro NM_ENCODE_VERSION(). */ return (major << 16) | (minor << 8) | micro; } static inline void nm_decode_version (guint version, guint *major, guint *minor, guint *micro) { *major = (version & 0xFFFF0000u) >> 16; *minor = (version & 0x0000FF00u) >> 8; *micro = (version & 0x000000FFu); } /*****************************************************************************/ /* taken from systemd's DECIMAL_STR_MAX() * * Returns the number of chars needed to format variables of the * specified type as a decimal string. Adds in extra space for a * negative '-' prefix (hence works correctly on signed * types). Includes space for the trailing NUL. */ #define NM_DECIMAL_STR_MAX(type) \ (2+(sizeof(type) <= 1 ? 3 : \ sizeof(type) <= 2 ? 5 : \ sizeof(type) <= 4 ? 10 : \ sizeof(type) <= 8 ? 20 : sizeof(int[-2*(sizeof(type) > 8)]))) /*****************************************************************************/ /* if @str is NULL, return "(null)". Otherwise, allocate a buffer using * alloca() of and fill it with @str. @str will be quoted with double quote. * If @str is longer then @trunc_at, the string is truncated and the closing * quote is instead '^' to indicate truncation. * * Thus, the maximum stack allocated buffer will be @trunc_at+3. */ #define nm_strquote_a(trunc_at, str) \ ({ \ const char *const _str = (str); \ \ (_str \ ? ({ \ const gsize _trunc_at = (trunc_at); \ const gsize _qstrlen_trunc = NM_MIN (qstrlen (_str), _trunc_at); \ char *_buf; \ \ _buf = g_alloca (_qstrlen_trunc + 3); \ _buf[0] = '"'; \ memcpy (&_buf[1], _str, _qstrlen_trunc); \ _buf[_qstrlen_trunc + 1] = _str[_qstrlen_trunc] ? '^' : '"'; \ _buf[_qstrlen_trunc + 2] = '\0'; \ _buf; \ }) \ : "(null)"); \ }) #define nm_sprintf_buf(buf, format, ...) \ ({ \ char * _buf = (buf); \ int _buf_len; \ \ /* some static assert trying to ensure that the buffer is statically allocated. * It disallows a buffer size of sizeof(gpointer) to catch that. */ \ G_STATIC_ASSERT (G_N_ELEMENTS (buf) == sizeof (buf) && sizeof (buf) != sizeof (char *)); \ _buf_len = g_snprintf (_buf, sizeof (buf), \ ""format"", ##__VA_ARGS__); \ nm_assert (_buf_len < sizeof (buf)); \ _buf; \ }) #define nm_sprintf_bufa(n_elements, format, ...) \ ({ \ char *_buf; \ int _buf_len; \ typeof (n_elements) _n_elements = (n_elements); \ \ _buf = g_alloca (_n_elements); \ _buf_len = g_snprintf (_buf, _n_elements, \ ""format"", ##__VA_ARGS__); \ nm_assert (_buf_len < _n_elements); \ _buf; \ }) /* aims to alloca() a buffer and fill it with printf(format, name). * Note that format must not contain any format specifier except * "%s". * If the resulting string would be too large for stack allocation, * it allocates a buffer with g_malloc() and assigns it to *p_val_to_free. */ #define nm_construct_name_a(format, name, p_val_to_free) \ ({ \ const char *const _name = (name); \ char **const _p_val_to_free = (p_val_to_free); \ const gsize _name_len = strnlen (_name, sizeof(_name)); \ char *_buf2; \ \ nm_assert (_p_val_to_free && !*_p_val_to_free); \ if (NM_qstrlen (format) + _name_len < 200) \ _buf2 = nm_sprintf_bufa (NM_qstrlen (format) + _name_len, format, _name); \ else { \ _buf2 = g_strdup_printf (format, _name); \ *_p_val_to_free = _buf2; \ } \ (const char *) _buf2; \ }) /*****************************************************************************/ /** * The boolean type _Bool is C99 while we mostly stick to C89. However, _Bool is too * convinient to miss and is effectively available in gcc and clang. So, just use it. * * Usually, one would include "stdbool.h" to get the "bool" define which aliases * _Bool. We provide this define here, because we want to make use of it anywhere. * (also, stdbool.h is again C99). * * Using _Bool has advantages over gboolean: * * - commonly _Bool is one byte large, instead of gboolean's 4 bytes (because gboolean * is a typedef for gint). Especially when having boolean fields in a struct, we can * thereby easily save some space. * * - _Bool type guarantees that two "true" expressions compare equal. E.g. the follwing * will not work: * gboolean v1 = 1; * gboolean v2 = 2; * g_assert_cmpint (v1, ==, v2); // will fail * For that, we often to use !! to coerce gboolean values to 0 or 1: * g_assert_cmpint (!!v2, ==, TRUE); * With _Bool type, this will be handled properly by the compiler. * * - For structs, we might want to safe even more space and use bitfields: * struct s1 { * gboolean v1:1; * }; * But the problem here is that gboolean is signed, so that * v1 will be either 0 or -1 (not 1, TRUE). Thus, the following * fails: * struct s1 s = { .v1 = TRUE, }; * g_assert_cmpint (s1.v1, ==, TRUE); * It will however work just fine with bool/_Bool while retaining the * notion of having a boolean value. * * Also, add the defines for "true" and "false". Those are nicely highlighted by the editor * as special types, contrary to glib's "TRUE"/"FALSE". */ #ifndef bool #define bool _Bool #define true 1 #define false 0 #endif #ifdef _G_BOOLEAN_EXPR /* g_assert() uses G_LIKELY(), which in turn uses _G_BOOLEAN_EXPR(). * As glib's implementation uses a local variable _g_boolean_var_, * we cannot do * g_assert (some_macro ()); * where some_macro() itself expands to ({g_assert(); ...}). * In other words, you cannot have a g_assert() inside a g_assert() * without getting a -Werror=shadow failure. * * Workaround that by re-defining _G_BOOLEAN_EXPR() **/ #undef _G_BOOLEAN_EXPR #define __NM_G_BOOLEAN_EXPR_IMPL(v, expr) \ ({ \ int NM_UNIQ_T(V, v); \ \ if (expr) \ NM_UNIQ_T(V, v) = 1; \ else \ NM_UNIQ_T(V, v) = 0; \ NM_UNIQ_T(V, v); \ }) #define _G_BOOLEAN_EXPR(expr) __NM_G_BOOLEAN_EXPR_IMPL (NM_UNIQ, expr) #endif /*****************************************************************************/ static inline int nm_steal_fd (int *p_fd) { int fd; if ( p_fd && ((fd = *p_fd) >= 0)) { *p_fd = -1; return fd; } return -1; } /** * nm_close: * * Like close() but throws an assertion if the input fd is * invalid. Closing an invalid fd is a programming error, so * it's better to catch it early. */ static inline int nm_close (int fd) { int r; r = close (fd); nm_assert (r != -1 || fd < 0 || errno != EBADF); return r; } #endif /* __NM_MACROS_INTERNAL_H__ */ kylin-nm/src/backend/dbus-interface/kylinconnectitem.h0000664000175000017500000000301315167646234022052 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINCONNECTITEM_H #define KYLINCONNECTITEM_H #include #include "kylinnetworkresourcemanager.h" class KyConnectItem : public QObject { Q_OBJECT public: explicit KyConnectItem(QObject *parent = nullptr); ~KyConnectItem(); public: void dumpInfo(); void setConnectUuid(QString uuid); public: QString m_connectName; QString m_connectUuid; QString m_connectPath; QString m_ifaceName; NetworkManager::ActiveConnection::State m_connectState; //deactive、activing and actived NetworkManager::ConnectionSettings::ConnectionType m_itemType; //wired or wireless vpn etc }; #endif // KYLINWIREDCONNECTITEM_H kylin-nm/src/backend/dbus-interface/kylinvpnconnectitem.h0000664000175000017500000000270015167646234022600 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINVPNCONNECTITEM_H #define KYLINVPNCONNECTITEM_H #include #include #include class KyVpnConnectItem : public QObject { Q_OBJECT public: explicit KyVpnConnectItem(QObject *parent = nullptr); ~KyVpnConnectItem(); public: QString m_vpnName; QString m_vpnUuid; QString m_vpnUser; QString m_vpnGateWay; QString m_vpnIpv4Address; QString m_vpnIpv6Address; bool m_vpnMppe; NetworkManager::VpnConnection::State m_vpnState; }; #endif // KYLINVPNCONNECTITEM_H kylin-nm/src/backend/dbus-interface/kylinactiveconnectresource.cpp0000664000175000017500000007275015167651420024501 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinutil.h" #include "kylinactiveconnectresource.h" #include "kywirelessconnectoperation.h" #include #include #include #define LOG_FLAG "[KyActiveConnectResourse]" KyActiveConnectResourse::KyActiveConnectResourse(QObject *parent) : QObject(parent) { m_networkResourceInstance = KyNetworkResourceManager::getInstance(); m_networkdevice = new KyNetworkDeviceResourse(); connect(m_networkResourceInstance, &KyNetworkResourceManager::activeConnectionRemove, this, &KyActiveConnectResourse::activeConnectRemove); connect(m_networkResourceInstance, &KyNetworkResourceManager::activeConnectStateChangeReason, this, &KyActiveConnectResourse::stateChangeReason); connect(m_networkResourceInstance, &KyNetworkResourceManager::vpnActiveConnectStateChangeReason, this, &KyActiveConnectResourse::vpnConnectChangeReason); } KyActiveConnectResourse::~KyActiveConnectResourse() { m_networkResourceInstance = nullptr; if (nullptr != m_networkdevice) { delete m_networkdevice; m_networkdevice = nullptr; } } KyConnectItem *KyActiveConnectResourse::getActiveConnectionItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr) { qDebug()<<"[KyActiveConnectResourse]"<<"get active connect item"; if (nullptr == activeConnectPtr) { qWarning()<<"[KyActiveConnectResourse]"<<"the active connect is empty"; return nullptr; } if (NetworkManager::ActiveConnection::State::Activated != activeConnectPtr->state()) { qWarning()<<"[KyActiveConnectResourse]"<<"the active connect is not activated" <<"connect name:"<connection()->name() <<"connect state"<< activeConnectPtr->state(); return nullptr; } KyConnectItem *activeConnectItem = new KyConnectItem(); activeConnectItem->m_connectUuid = activeConnectPtr->uuid(); NetworkManager::Connection::Ptr connectPtr = activeConnectPtr->connection(); activeConnectItem->m_connectName = connectPtr->name(); activeConnectItem->m_connectPath = connectPtr->path(); activeConnectItem->m_connectState = NetworkManager::ActiveConnection::State::Activated; return activeConnectItem; } KyConnectItem *KyActiveConnectResourse::getActiveConnectionByUuid(QString connectUuid) { NetworkManager::ActiveConnection::List activeConnectList; activeConnectList.clear(); activeConnectList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectList.empty()) { qWarning()<<"[KyActiveConnectResourse]"<<"the active connect list is empty"; return nullptr; } //可能存在已无效的ActiveConnection,所以使用uuid遍历处理需要满足device不为空且ActiveConnection状态为已连接 NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; KyConnectItem *activeConnectItem = nullptr; bool isFind = false; for (int index = 0; index < activeConnectList.size(); index++) { activeConnectPtr = activeConnectList.at(index); if (activeConnectPtr.isNull()) { continue; } if (connectUuid != activeConnectPtr->uuid()) { continue; } activeConnectItem = getActiveConnectionItem(activeConnectPtr); if (nullptr == activeConnectItem || activeConnectPtr->devices().isEmpty()) { continue; } else { isFind = true; break; } } if (!isFind) { return nullptr; } QString ifaceUni = activeConnectPtr->devices().at(0); NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceUni(ifaceUni); if (devicePtr.isNull()) { return nullptr; } activeConnectItem->m_ifaceName = devicePtr->interfaceName(); activeConnectItem->m_itemType = activeConnectPtr->type(); return activeConnectItem; } KyConnectItem *KyActiveConnectResourse::getActiveConnectionByUuid(QString connectUuid, QString deviceName) { NetworkManager::ActiveConnection::Ptr activeConnectPtr = m_networkResourceInstance->getActiveConnect(connectUuid); if (nullptr == activeConnectPtr) { qWarning()<< "[KyActiveConnectResourse]" <<"it can not find connect "<< connectUuid; return nullptr; } QStringList interfaces = activeConnectPtr->devices(); for (int index = 0; index < interfaces.size(); ++index) { QString ifaceUni = interfaces.at(index); NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceUni(ifaceUni); if (devicePtr.isNull()) { continue; } if (devicePtr->interfaceName() == deviceName) { KyConnectItem *activeConnectItem = getActiveConnectionItem(activeConnectPtr); if (nullptr == activeConnectItem) { return nullptr; } activeConnectItem->m_ifaceName = deviceName; activeConnectItem->m_itemType = activeConnectPtr->type(); return activeConnectItem; } } return nullptr; } void KyActiveConnectResourse::getActiveConnectionList(QString deviceName, NetworkManager::ConnectionSettings::ConnectionType connectionType, QList &activeConnectItemList) { qDebug()<<"[KyActiveConnectResourse]"<<"get activate connect for device" << deviceName <<"connect type:"<getActiveConnectList(); if (activeConnectList.empty()) { qWarning()<<"[KyActiveConnectResourse]"<<"the active connect list is empty"; return; } NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; for (int index = 0; index < activeConnectList.size(); index++) { activeConnectPtr = activeConnectList.at(index); if (activeConnectPtr.isNull()) { continue; } if (connectionType != activeConnectPtr->type()) { qDebug()<<"[KyActiveConnectResourse]" <<"the connect type " << activeConnectPtr->type() <<"connect name" << activeConnectPtr->connection()->name(); continue; } QStringList interfaces = activeConnectPtr->devices(); for (int index = 0; index < interfaces.size(); ++index) { QString ifaceUni = interfaces.at(index); NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceUni(ifaceUni); if (!devicePtr.isNull() && devicePtr->interfaceName() == deviceName) { KyConnectItem *activeConnectItem = getActiveConnectionItem(activeConnectPtr); if (nullptr != activeConnectItem) { activeConnectItem->m_ifaceName = deviceName; activeConnectItem->m_itemType = connectionType; activeConnectItemList << activeConnectItem; //activeConnectItem->dumpInfo(); } activeConnectPtr = nullptr; break; } } } return; } #if 0 void KyActiveConnectResourse::getWiredActivateConnect(QList &wiredActiveConnectItemList) { int index = 0; NetworkManager::ActiveConnection::List activeConnectList; qDebug()<<"[KyActiveConnectResourse]"<<"get wired activate connect"; activeConnectList.clear(); activeConnectList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectList.empty()) { qWarning()<<"[KyActiveConnectResourse]"<<"the active connect list is empty"; return; } NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; for (index = 0; index < activeConnectList.size(); index++) { activeConnectPtr = activeConnectList.at(index); if (NetworkManager::ConnectionSettings::ConnectionType::Wired != activeConnectPtr->type()) { continue; } KyWiredConnectItem *activeConnectItem = getWiredActiveConnectItem(activeConnectPtr); if (nullptr != activeConnectItem) { wiredActiveConnectItemList << activeConnectItem; activeConnectItem->dumpInfo(); } activeConnectPtr = nullptr; } return; } KyWiredConnectItem *KyActiveConnectResourse::getWiredActiveConnectItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr) { qDebug()<<"[KyActiveConnectResourse]"<<"get active connect item"; if (nullptr == activeConnectPtr) { qWarning()<<"[KyActiveConnectResourse]"<<"the active connect is empty"; return nullptr; } if (NetworkManager::ActiveConnection::State::Activated != activeConnectPtr->state()) { qWarning()<<"[KyActiveConnectResourse]"<<"the active connect is not activated" <connection()->name() << activeConnectPtr->state(); return nullptr; } KyWiredConnectItem *wiredItem = new KyWiredConnectItem(); NetworkManager::Connection::Ptr connectPtr = activeConnectPtr->connection(); NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); wiredItem->m_connectName = connectPtr->name(); qDebug() <<"[KyActiveConnectResourse]"<< "connect uuid" << connectPtr->uuid() << "active connect uuid" << activeConnectPtr->uuid(); wiredItem->m_connectUuid = activeConnectPtr->uuid(); wiredItem->m_ifaceName = settingPtr->interfaceName(); getActiveConnectIp(activeConnectPtr, wiredItem->m_ipv4, wiredItem->m_ipv6); m_networkdevice->getWiredHardwareInfo(settingPtr->interfaceName(), wiredItem); wiredItem->m_state = NetworkManager::ActiveConnection::State::Activated; //wiredItem->m_itemType; return wiredItem; } #endif void KyActiveConnectResourse::getActiveConnectIpInfo( const QString &connectUuid, QString &ipv4Address, QString &ipv6Address) { NetworkManager::ActiveConnection::Ptr activeConnectPtr = m_networkResourceInstance->getActiveConnect(connectUuid); if (activeConnectPtr.isNull()) { qWarning()<< "[KyActiveConnectResourse]" <<"it can not find connect "<< connectUuid; return; } getActiveConnectIp(activeConnectPtr, ipv4Address, ipv6Address); return; } void KyActiveConnectResourse::getActiveConnectIp( NetworkManager::ActiveConnection::Ptr activeConnectPtr, QString &ipv4Address, QString &ipv6Address) { qDebug()<<"[KyActiveConnectResourse]"<<"get active connect ip info"; NetworkManager::IpConfig ipv4Config =activeConnectPtr->ipV4Config(); if (ipv4Config.isValid()) { if (!ipv4Config.addresses().isEmpty()) { NetworkManager::IpAddress address = ipv4Config.addresses().at(0); ipv4Address = address.ip().toString(); } else { qWarning()<<"[KyActiveConnectResourse]"<<"the ipv4 address is empty."; } } else { qWarning()<<"[KyActiveConnectResourse]"<<"ipv4 config is not valid"; } NetworkManager::IpConfig ipv6Config =activeConnectPtr->ipV6Config(); if (ipv6Config.isValid()) { if (!ipv6Config.addresses().isEmpty()) { NetworkManager::IpAddress address = ipv6Config.addresses().at(0); ipv6Address = address.ip().toString(); } else { qWarning()<<"[KyActiveConnectResourse]"<<"ipv6 address is empty"; } } else { qWarning()<<"[KyActiveConnectResourse]"<<"ipv6 config is not valid"; } return; } void KyActiveConnectResourse::getActiveConnectDnsInfo( const QString &connectUuid, QList &ipv4Dns, QList &ipv6Dns) { NetworkManager::ActiveConnection::Ptr activeConnectPtr = m_networkResourceInstance->getActiveConnect(connectUuid); if (activeConnectPtr.isNull()) { qWarning()<< "[KyActiveConnectResourse]" <<"it can not find connect "<< connectUuid; return; } getActiveConnectDns(activeConnectPtr, ipv4Dns, ipv6Dns); return; } void KyActiveConnectResourse::getActiveConnectDns( NetworkManager::ActiveConnection::Ptr activeConnectPtr, QList &ipv4Dns, QList &ipv6Dns) { qDebug()<<"[KyActiveConnectResourse]"<<"get active connect nameservice info"; NetworkManager::IpConfig ipv4Config = activeConnectPtr->ipV4Config(); if (ipv4Config.isValid()) { ipv4Dns = ipv4Config.nameservers(); } else { qWarning()<<"[KyActiveConnectResourse]"<<"ipv4 config is not valid"; } NetworkManager::IpConfig ipv6Config =activeConnectPtr->ipV6Config(); if (ipv6Config.isValid()) { ipv6Dns = ipv6Config.nameservers(); } else { qWarning()<<"[KyActiveConnectResourse]"<<"ipv6 config is not valid"; } return; } KyVpnConnectItem *KyActiveConnectResourse::getVpnActiveConnectItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr) { qDebug()<<"[KyActiveConnectResourse]"<<"get vpn active connect item"; if (nullptr == activeConnectPtr) { qWarning()<<"[KyActiveConnectResourse]"<<"get vpn active connect failed, the active connect is empty"; return nullptr; } if (NetworkManager::ActiveConnection::State::Activated != activeConnectPtr->state()) { qWarning()<<"[KyActiveConnectResourse]"<<"the active connect is not activated" <connection()->name() << activeConnectPtr->state(); return nullptr; } KyVpnConnectItem *vpnItem = new KyVpnConnectItem(); NetworkManager::Connection::Ptr connectPtr = activeConnectPtr->connection(); vpnItem->m_vpnName = connectPtr->name(); vpnItem->m_vpnUuid = activeConnectPtr->uuid(); NetworkManager::ConnectionSettings::Ptr settingsPtr = connectPtr->settings(); NetworkManager::VpnSetting::Ptr vpnSetting = settingsPtr->setting(NetworkManager::Setting::Vpn).dynamicCast(); NMStringMap vpnDataMap = vpnSetting->data(); if (vpnDataMap.isEmpty()) { qWarning()<<"[KyActiveConnectResourse]"<<"get vpn connection Data failed, the data is empty"; } else { vpnItem->m_vpnGateWay = vpnDataMap["gateway"]; vpnItem->m_vpnUser = vpnDataMap["user"]; if ( "yes" == vpnDataMap["require-mppe"]) { vpnItem->m_vpnMppe = true; } else { vpnItem->m_vpnMppe = false; qDebug()<<"[KyActiveConnectResourse]"<<"vpn mppe required:"<< vpnDataMap["require-mppe"]; } } getActiveConnectIp(activeConnectPtr, vpnItem->m_vpnIpv4Address, vpnItem->m_vpnIpv6Address); NetworkManager::VpnConnection *p_vpnConnect = qobject_cast(activeConnectPtr.data()); vpnItem->m_vpnState = p_vpnConnect->state(); return vpnItem; } void KyActiveConnectResourse::getVpnActivateConnect(QList &vpnActiveConnectItemList) { int index = 0; NetworkManager::ActiveConnection::List activeConnectList; activeConnectList.clear(); activeConnectList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectList.empty()) { qWarning()<<"[KyActiveConnectResourse]"<<"get vpn active connect failed, the active connect list is empty"; return; } NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; for (index = 0; index < activeConnectList.size(); index++) { activeConnectPtr = activeConnectList.at(index); if (activeConnectPtr.isNull()) { continue; } if (!activeConnectPtr->vpn()) { continue; } KyVpnConnectItem *activeConnectItem = getVpnActiveConnectItem(activeConnectPtr); if (nullptr != activeConnectItem) { vpnActiveConnectItemList << activeConnectItem; } activeConnectPtr = nullptr; } return; } KyBluetoothConnectItem *KyActiveConnectResourse::getBtActiveConnectItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr) { qDebug()<<"[KyActiveConnectResourse]"<<"get bluetooth active connect item"; if (nullptr == activeConnectPtr) { qWarning()<<"[KyActiveConnectResourse]"<<"get bluetooth item failed, the active connect is empty"; return nullptr; } if (NetworkManager::ActiveConnection::State::Activated != activeConnectPtr->state()) { qWarning()<<"[KyActiveConnectResourse]"<<"get bluetooth item failed, the active connect is not activated" <connection()->name() << activeConnectPtr->state(); return nullptr; } KyBluetoothConnectItem *bluetoothItem = new KyBluetoothConnectItem(); NetworkManager::Connection::Ptr connectPtr = activeConnectPtr->connection(); bluetoothItem->m_connectName = connectPtr->name(); bluetoothItem->m_connectUuid = activeConnectPtr->uuid(); bluetoothItem->m_state = NetworkManager::ActiveConnection::State::Activated; getActiveConnectIp(activeConnectPtr, bluetoothItem->m_ipv4Address, bluetoothItem->m_ipv6Address); NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); NetworkManager::BluetoothSetting::Ptr bluetoothSetting = settingPtr->setting(NetworkManager::Setting::Bluetooth).dynamicCast(); bluetoothItem->m_deviceAddress = bluetoothSetting->bluetoothAddress(); QByteArray btAddrArray = bluetoothSetting->bluetoothAddress(); for (int index = 0; index < btAddrArray.size(); ++index) { qDebug("bt address %d %s", index, btAddrArray[index]); } qDebug()<<"bluetooth device address"<m_deviceAddress; //wiredItem->m_itemType; return bluetoothItem; } void KyActiveConnectResourse::getBtActivateConnect(QList &btActiveConnectItemList) { int index = 0; NetworkManager::ActiveConnection::List activeConnectList; activeConnectList.clear(); activeConnectList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectList.empty()) { qWarning()<<"[KyActiveConnectResourse]"<<"get bluetooth active connect failed, the active connect list is empty"; return; } NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; for (index = 0; index < activeConnectList.size(); index++) { activeConnectPtr = activeConnectList.at(index); if (activeConnectPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::ConnectionType::Bluetooth != activeConnectPtr->type()) { continue; } KyBluetoothConnectItem *activeConnectItem = getBtActiveConnectItem(activeConnectPtr); if (nullptr != activeConnectItem) { btActiveConnectItemList << activeConnectItem; } activeConnectPtr = nullptr; } return; } KyApConnectItem *KyActiveConnectResourse::getApActiveConnectItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr) { qDebug()<<"[KyActiveConnectResourse]"<<"get wireless ap active connect item"; if (nullptr == activeConnectPtr) { qWarning()<<"[KyActiveConnectResourse]"<<"get wireless ap item failed, the active connect is empty"; return nullptr; } if (NetworkManager::ActiveConnection::State::Activated != activeConnectPtr->state()) { qWarning()<<"[KyActiveConnectResourse]"<<"get ap item failed, the active connect is not activated" <connection()->name() << activeConnectPtr->state(); return nullptr; } NetworkManager::Connection::Ptr connectPtr = activeConnectPtr->connection(); NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); NetworkManager::WirelessSetting::Ptr wirelessSetting = settingPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); if (NetworkManager::WirelessSetting::NetworkMode::Ap != wirelessSetting->mode()) { qDebug() << "[KyActiveConnectResourse]" <<"get ap item failed, the active connect mode is not ap."; return nullptr; } KyApConnectItem *apConnectItem = new KyApConnectItem(); apConnectItem->m_connectName = connectPtr->name(); apConnectItem->m_connectUuid = activeConnectPtr->uuid(); apConnectItem->m_ifaceName = settingPtr->interfaceName(); QByteArray rawSsid = wirelessSetting->ssid(); apConnectItem->m_connectSsid = getSsidFromByteArray(rawSsid); KyWirelessConnectOperation wirelessOperation; apConnectItem->m_password = wirelessOperation.getPsk(apConnectItem->m_connectUuid); return apConnectItem; } void KyActiveConnectResourse::getApActivateConnect(QList &apConnectItemList) { int index = 0; NetworkManager::ActiveConnection::List activeConnectList; activeConnectList.clear(); activeConnectList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectList.empty()) { qWarning()<<"[KyActiveConnectResourse]" <<"get ap active connect failed, the active connect list is empty"; return; } NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; for (index = 0; index < activeConnectList.size(); index++) { activeConnectPtr = activeConnectList.at(index); if (activeConnectPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::ConnectionType::Wireless != activeConnectPtr->type()) { continue; } KyApConnectItem *apConnectItem = getApActiveConnectItem(activeConnectPtr); if (nullptr != apConnectItem) { apConnectItemList << apConnectItem; } activeConnectPtr = nullptr; } return; } QString KyActiveConnectResourse::getDeviceOfActivateConnect(QString conUuid) { QString deviceName = ""; NetworkManager::ActiveConnection::Ptr activeConnectPtr = m_networkResourceInstance->getActiveConnect(conUuid); if (nullptr == activeConnectPtr) { qWarning()<< "[KyActiveConnectResourse]" <<"it can not find connect "<< conUuid; return deviceName; } QStringList interfaces = activeConnectPtr->devices(); if (interfaces.isEmpty()) { qWarning()<< LOG_FLAG << "get device of active connection failed."; return deviceName; } QString ifaceUni = interfaces.at(0); NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceUni(ifaceUni); if (!devicePtr.isNull()) { deviceName = devicePtr->interfaceName(); } return deviceName; } bool KyActiveConnectResourse::connectionIsVirtual(QString uuid) { NetworkManager::ActiveConnection::Ptr activeConnectPtr = m_networkResourceInstance->getActiveConnect(uuid); if (activeConnectPtr.isNull()) { qWarning()<< LOG_FLAG << "check connection virtual is failed."; return false; } QStringList interfaces = activeConnectPtr->devices(); if (interfaces.isEmpty()) { qWarning()<< LOG_FLAG << "active connection get device failed."; return false; } QString ifaceUni = interfaces.at(0); NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceUni(ifaceUni); if (devicePtr.isNull()) { return false; } return !m_networkdevice->checkDeviceType(devicePtr->interfaceName(), NetworkManager::Device::Type::Ethernet); } bool KyActiveConnectResourse::wiredConnectIsActived() { int index = 0; NetworkManager::ActiveConnection::List activeConnectList; activeConnectList.clear(); activeConnectList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectList.empty()) { qWarning()<<"[KyActiveConnectResourse]" <<"get active connect failed, the active connect list is empty"; return false; } NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; for (index = 0; index < activeConnectList.size(); index++) { activeConnectPtr = activeConnectList.at(index); if (activeConnectPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::ConnectionType::Wired != activeConnectPtr->type()) { continue; } if (connectionIsVirtual(activeConnectPtr->uuid())) { continue; } if (activeConnectPtr->state() == NetworkManager::ActiveConnection::State::Activated) { return true; } } return false; } bool KyActiveConnectResourse::checkWirelessStatus(NetworkManager::ActiveConnection::State state) { int index = 0; NetworkManager::ActiveConnection::List activeConnectList; activeConnectList.clear(); activeConnectList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectList.empty()) { qWarning()<<"[KyActiveConnectResourse]" <<"get active connect failed, the active connect list is empty"; return false; } NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; for (index = 0; index < activeConnectList.size(); index++) { activeConnectPtr = activeConnectList.at(index); if (activeConnectPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::ConnectionType::Wireless != activeConnectPtr->type()) { continue; } if (activeConnectPtr->state() == state) { return true; } } return false; } QString KyActiveConnectResourse::getAcitveConnectionPathByUuid(QString connectUuid) { NetworkManager::ActiveConnection::Ptr activeAonnectPtr = nullptr; activeAonnectPtr = m_networkResourceInstance->getActiveConnect(connectUuid); if (nullptr == activeAonnectPtr) { return nullptr; } return activeAonnectPtr->path(); } int KyActiveConnectResourse::getActivateWifiSignal(QString devName) { int signalStrength = -1; KyNetworkDeviceResourse devResource; QStringList devList; devResource.getNetworkDeviceList(NetworkManager::Device::Type::Wifi, devList); for (int i = 0; i < devList.size(); ++i) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceInterface(devList.at(i)); if (nullptr == connectDevice || !connectDevice->isValid()) { qWarning()<< LOG_FLAG <<"getDeviceActiveAPInfo failed, the device" << devList.at(i) << "is not existed"; continue; } if (connectDevice->type() == NetworkManager::Device::Wifi) { if ((!devName.isEmpty() && connectDevice->interfaceName() == devName) || devName.isEmpty()) { NetworkManager::WirelessDevice *wirelessDevicePtr = qobject_cast(connectDevice.data()); NetworkManager::AccessPoint::Ptr apPtr = wirelessDevicePtr->activeAccessPoint(); if (apPtr.isNull()) { continue; } signalStrength = apPtr->signalStrength(); break; } } } return signalStrength; } bool KyActiveConnectResourse::checkInternetLoading() { int index = 0; NetworkManager::ActiveConnection::List activeConnectList; activeConnectList.clear(); activeConnectList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectList.empty()) { qWarning()<<"[KyActiveConnectResourse]" <<"get active connect failed, the active connect list is empty"; return false; } NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; for (index = 0; index < activeConnectList.size(); index++) { activeConnectPtr = activeConnectList.at(index); if (activeConnectPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::ConnectionType::Wireless != activeConnectPtr->type() && NetworkManager::ConnectionSettings::ConnectionType::Wired != activeConnectPtr->type() && NetworkManager::ConnectionSettings::ConnectionType::Pppoe != activeConnectPtr->type()) { continue; } if (activeConnectPtr->state() == NetworkManager::ActiveConnection::State::Activating || activeConnectPtr->state() == NetworkManager::ActiveConnection::State::Deactivating) { return true; } } return false; } kylin-nm/src/backend/dbus-interface/kylinbluetoothconnectitem.h0000664000175000017500000000313615167646234024006 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINBLUETOOTHCONNECTITEM_H #define KYLINBLUETOOTHCONNECTITEM_H #include #include #include #include class KyBluetoothConnectItem : public QObject { Q_OBJECT public: explicit KyBluetoothConnectItem(QObject *parent = nullptr); ~KyBluetoothConnectItem(); public: void dumpInfo(); public: QString m_connectName; QString m_connectUuid; QString m_deviceAddress; QString m_ipv4Address; QString m_ipv6Address; NetworkManager::ActiveConnection::State m_state; //deactive、activing and actived //QString m_itemType; //activeconnect or connect }; #endif // KYLINBLUETOOTHCONNECTITEM_H kylin-nm/src/backend/dbus-interface/kylinvpnconnectitem.cpp0000664000175000017500000000235515167646234023141 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinvpnconnectitem.h" KyVpnConnectItem::KyVpnConnectItem(QObject *parent) : QObject(parent) { m_vpnName = ""; m_vpnUuid = ""; m_vpnUser = ""; m_vpnGateWay = ""; m_vpnIpv4Address = ""; m_vpnIpv6Address = ""; m_vpnMppe = false; m_vpnState = NetworkManager::VpnConnection::State::Disconnected; } KyVpnConnectItem::~KyVpnConnectItem() { } kylin-nm/src/backend/dbus-interface/kylinutil.h0000664000175000017500000000311315167646234020520 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINUTIL_H #define KYLINUTIL_H #include #include #include #include #include #include #include #include #define KEY_CONNECTION "connection" #define KEY_CONNECT_TYPE "type" #define ETHERNET_TYPE "802-3-ethernet" QString getConnectTypeByDbus(QString &connectPath); QString getSsidFromByteArray(QByteArray &rawSsid); void setWiredEnabledByGDbus(bool enabled); void setDeviceManagedByGDbus(QString dbusPath, bool managed); QString getConnectivityCheckSpareUriByGDbus(); void setConnectivityCheckSpareUriByGDbus(QString str); bool getWiredEnabledByGDbus(); #endif // KYLINUTIL_H kylin-nm/src/backend/dbus-interface/kyenterpricesettinginfo.cpp0000664000175000017500000003742615167646234024023 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kyenterpricesettinginfo.h" void assembleEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &info) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodTls); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setIdentity(info.identity); if (!info.domain.isEmpty()){ wifi_8021x_sett->setDomainSuffixMatch(info.domain); } if (info.bNeedCa) { QByteArray caCerEndWithNull("file://" + info.caCertPath.toUtf8() + '\0'); wifi_8021x_sett->setCaCertificate(caCerEndWithNull); } else { QByteArray caCerEndWithNull(""); wifi_8021x_sett->setCaCertificate(caCerEndWithNull); } QByteArray cliCertEndWithNull("file://" + info.clientCertPath.toUtf8() + '\0'); wifi_8021x_sett->setClientCertificate(cliCertEndWithNull); QByteArray cliPriKeyEndWithNull("file://" + info.clientPrivateKey.toUtf8() + '\0'); wifi_8021x_sett->setPrivateKey(cliPriKeyEndWithNull); wifi_8021x_sett->setPrivateKeyPassword(info.clientPrivateKeyPWD); wifi_8021x_sett->setPrivateKeyPasswordFlags(info.m_privateKeyPWDFlag); NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); return; } void assembleEapMethodPeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPeapInfo &info) { qDebug() << "assembleEapMethodPeapSettings"; NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodPeap); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)info.phase2AuthMethod); wifi_8021x_sett->setIdentity(info.userName); wifi_8021x_sett->setPassword(info.userPWD); wifi_8021x_sett->setPasswordFlags(info.m_passwdFlag); NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); return; } void assembleEapMethodTtlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTtlsInfo &info) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodTtls); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); if (info.authType == KyTtlsAuthMethod::AUTH_EAP) { wifi_8021x_sett->setPhase2AuthEapMethod((NetworkManager::Security8021xSetting::AuthEapMethod)info.authEapMethod);//gtc md5 mschapv2 otp tls } else if (info.authType == KyTtlsAuthMethod::AUTH_NO_EAP) { wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)info.authNoEapMethod);//chap md5 mschapv2 pap gtc mschap otp tls } wifi_8021x_sett->setIdentity(info.userName); wifi_8021x_sett->setPassword(info.userPWD); wifi_8021x_sett->setPasswordFlags(info.m_passwdFlag); NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); return; } void modifyEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &tlsInfo) { NetworkManager::Security8021xSetting::Ptr setting = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); setting->setInitialized(true); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodTls); setting->setEapMethods(list); setting->setIdentity(tlsInfo.identity); if(!tlsInfo.domain.isEmpty()) { setting->setDomainSuffixMatch(tlsInfo.domain); } if (tlsInfo.bNeedCa) { QByteArray caCerEndWithNull("file://" + tlsInfo.caCertPath.toUtf8() + '\0'); setting->setCaCertificate(caCerEndWithNull); } else { QByteArray caCerEndWithNull(""); setting->setCaCertificate(caCerEndWithNull); } QByteArray cliCertEndWithNull("file://" + tlsInfo.clientCertPath.toUtf8() + '\0'); setting->setClientCertificate(cliCertEndWithNull); QByteArray cliPriKeyEndWithNull("file://" + tlsInfo.clientPrivateKey.toUtf8() + '\0'); setting->setPrivateKey(cliPriKeyEndWithNull); setting->setPrivateKeyPasswordFlags(tlsInfo.m_privateKeyPWDFlag); if(tlsInfo.bChanged) { setting->setPrivateKeyPassword(tlsInfo.clientPrivateKeyPWD); } return; } void modifyEapMethodPeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPeapInfo &peapInfo) { qDebug() << "assembleEapMethodPeapSettings"; NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); wifi_8021x_sett->setInitialized(true); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodPeap); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)peapInfo.phase2AuthMethod); wifi_8021x_sett->setIdentity(peapInfo.userName); if(peapInfo.bChanged) { wifi_8021x_sett->setPassword(peapInfo.userPWD); } wifi_8021x_sett->setPasswordFlags(peapInfo.m_passwdFlag); QByteArray caCerEndWithNull(""); wifi_8021x_sett->setCaCertificate(caCerEndWithNull); return; } void modifyEapMethodTtlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTtlsInfo &ttlsInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodTtls); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); if (ttlsInfo.authType == KyTtlsAuthMethod::AUTH_EAP) { wifi_8021x_sett->setPhase2AuthEapMethod((NetworkManager::Security8021xSetting::AuthEapMethod)ttlsInfo.authEapMethod);//gtc md5 mschapv2 otp tls } else if (ttlsInfo.authType == KyTtlsAuthMethod::AUTH_NO_EAP) { wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)ttlsInfo.authNoEapMethod);//chap md5 mschapv2 pap gtc mschap otp tls } wifi_8021x_sett->setIdentity(ttlsInfo.userName); if(ttlsInfo.bChanged) { wifi_8021x_sett->setPassword(ttlsInfo.userPWD); } wifi_8021x_sett->setPasswordFlags(ttlsInfo.m_passwdFlag); QByteArray caCerEndWithNull(""); wifi_8021x_sett->setCaCertificate(caCerEndWithNull); return; } void assembleEapMethodLeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodLeapInfo &leapInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodLeap); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setIdentity(leapInfo.m_userName); wifi_8021x_sett->setPassword(leapInfo.m_userPwd); wifi_8021x_sett->setPasswordFlags(leapInfo.m_passwdFlag); NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); return; } void assembleEapMethodPwdSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPwdInfo &pwdInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodPwd); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setIdentity(pwdInfo.m_userName); wifi_8021x_sett->setPassword(pwdInfo.m_userPwd); wifi_8021x_sett->setPasswordFlags(pwdInfo.m_passwdFlag); NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); return; } void assembleEapMethodFastSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodFastInfo &fastInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodFast); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setAnonymousIdentity(fastInfo.m_anonIdentity); if (fastInfo.m_allowAutoPacFlag) { wifi_8021x_sett->setPhase1FastProvisioning((NetworkManager::Security8021xSetting::FastProvisioning)fastInfo.m_pacProvisioning); } else { wifi_8021x_sett->setPhase1FastProvisioning(NetworkManager::Security8021xSetting::FastProvisioning::FastProvisioningDisabled); } QByteArray pacEndWithNull("file://" + fastInfo.m_pacFilePath.toUtf8() + '\0'); wifi_8021x_sett->setPacFile(pacEndWithNull); wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)fastInfo.m_authMethod); wifi_8021x_sett->setIdentity(fastInfo.m_userName); wifi_8021x_sett->setPassword(fastInfo.m_userPwd); wifi_8021x_sett->setPasswordFlags(fastInfo.m_passwdFlag); NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); return; } void modifyEapMethodLeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodLeapInfo &leapInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); wifi_8021x_sett->setInitialized(true); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodLeap); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setIdentity(leapInfo.m_userName); if(leapInfo.bChanged) { wifi_8021x_sett->setPassword(leapInfo.m_userPwd); } wifi_8021x_sett->setPasswordFlags(leapInfo.m_passwdFlag); QByteArray caCerEndWithNull(""); wifi_8021x_sett->setCaCertificate(caCerEndWithNull); return; } void modifyEapMethodPwdSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPwdInfo &pwdInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); wifi_8021x_sett->setInitialized(true); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodPwd); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setIdentity(pwdInfo.m_userName); if(pwdInfo.bChanged) { wifi_8021x_sett->setPassword(pwdInfo.m_userPwd); } wifi_8021x_sett->setPasswordFlags(pwdInfo.m_passwdFlag); QByteArray caCerEndWithNull(""); wifi_8021x_sett->setCaCertificate(caCerEndWithNull); return; } void modifyEapMethodFastSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodFastInfo &fastInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); wifi_8021x_sett->setInitialized(true); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodFast); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setAnonymousIdentity(fastInfo.m_anonIdentity); if (fastInfo.m_allowAutoPacFlag) { wifi_8021x_sett->setPhase1FastProvisioning((NetworkManager::Security8021xSetting::FastProvisioning)fastInfo.m_pacProvisioning); } else { wifi_8021x_sett->setPhase1FastProvisioning(NetworkManager::Security8021xSetting::FastProvisioning::FastProvisioningDisabled); } QByteArray pacEndWithNull("file://" + fastInfo.m_pacFilePath.toUtf8() + '\0'); wifi_8021x_sett->setPacFile(pacEndWithNull); wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)fastInfo.m_authMethod); wifi_8021x_sett->setIdentity(fastInfo.m_userName); if(fastInfo.bChanged) { wifi_8021x_sett->setPassword(fastInfo.m_userPwd); } wifi_8021x_sett->setPasswordFlags(fastInfo.m_passwdFlag); return; } kylin-nm/src/backend/dbus-interface/kylinconnectresource.cpp0000664000175000017500000010563015167651420023277 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinconnectresource.h" #include "kywirelessconnectoperation.h" #include "kylinutil.h" #include #include #include #include #include const QString str2GBand = "2.4GHz"; const QString str5GBand = "5GHz"; static bool subLanListSort(const KyConnectItem* info1, const KyConnectItem* info2) { QString name1 = info1->m_connectName; QString name2 = info2->m_connectName; bool result = true; if (QString::compare(name1, name2, Qt::CaseInsensitive) > 0) { result = false; } return result; } static bool subVpnListSort(const KyConnectItem* info1, const KyConnectItem* info2) { if (info1->m_connectState != info2->m_connectState) { if (info1->m_connectState == 2) { return true; } if (info2->m_connectState == 2) { return false; } } QString name1 = info1->m_connectName; QString name2 = info2->m_connectName; bool result = true; if (QString::compare(name1, name2, Qt::CaseInsensitive) > 0) { result = false; } return result; } static void lanListSort(QList &list) { std::sort(list.begin(), list.end(), subLanListSort); } static void vpnListSort(QList &list) { std::sort(list.begin(), list.end(), subVpnListSort); } KyConnectResourse::KyConnectResourse(QObject *parent) : QObject(parent) { m_networkResourceInstance = KyNetworkResourceManager::getInstance(); connect(m_networkResourceInstance, &KyNetworkResourceManager::connectionAdd, this, &KyConnectResourse::connectionAdd); connect(m_networkResourceInstance, &KyNetworkResourceManager::connectionRemove, this, &KyConnectResourse::connectionRemove); connect(m_networkResourceInstance, &KyNetworkResourceManager::connectionUpdate, this, &KyConnectResourse::connectionUpdate); connect(m_networkResourceInstance, &KyNetworkResourceManager::connectivityChanged, this, &KyConnectResourse::connectivityChanged); connect(m_networkResourceInstance, &KyNetworkResourceManager::connectivityCheckSpareUriChanged, this, &KyConnectResourse::connectivityCheckSpareUriChanged); connect(m_networkResourceInstance, &KyNetworkResourceManager::needShowDesktop, this, &KyConnectResourse::needShowDesktop); } KyConnectResourse::~KyConnectResourse() { m_networkResourceInstance = nullptr; } KyConnectItem *KyConnectResourse::getConnectionItem(NetworkManager::Connection::Ptr connectPtr, QString devName) { if (nullptr == connectPtr) { qWarning()<<"[KyConnectResourse]"<<"the connect is empty"; return nullptr; } KyConnectItem *connectionItem = new KyConnectItem(); connectionItem->m_connectName = connectPtr->name(); connectionItem->m_connectUuid = connectPtr->uuid(); connectionItem->m_connectPath = connectPtr->path(); NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); connectionItem->m_ifaceName = settingPtr->interfaceName(); connectionItem->m_itemType = settingPtr->connectionType(); if (m_networkResourceInstance->isActivatingConnection(connectPtr->uuid())) { if (connectionItem->m_ifaceName == "" && devName != "") { if (isActiveDevice(connectionItem->m_connectUuid, devName)) { connectionItem->m_connectState = NetworkManager::ActiveConnection::State::Activating; } else { connectionItem->m_connectState = NetworkManager::ActiveConnection::State::Deactivated; } } else { connectionItem->m_connectState = NetworkManager::ActiveConnection::State::Activating; } } else { connectionItem->m_connectState = NetworkManager::ActiveConnection::State::Deactivated; } return connectionItem; } bool KyConnectResourse::isActiveDevice(QString conUuid, QString devName) { QString deviceName = ""; NetworkManager::ActiveConnection::Ptr activeConnectPtr = m_networkResourceInstance->getActiveConnect(conUuid); if (nullptr == activeConnectPtr) { qWarning()<< "[KyConnectResourse]" <<"it can not find activating connect "<< conUuid; return false; } QStringList interfaces = activeConnectPtr->devices(); if (interfaces.isEmpty()) { qWarning()<< "[KyConnectResourse]" << "get device of activing connection failed."; return false; } QString ifaceUni = ""; for (int index=0; index < interfaces.size(); index++) { ifaceUni = interfaces.at(index); NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceUni(ifaceUni); if (!devicePtr.isNull()) { deviceName = devicePtr->interfaceName(); if (deviceName == devName) { return true; } } } return false; } KyConnectItem * KyConnectResourse::getConnectionItemByUuid(QString connectUuid) { NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(connectUuid); if (nullptr == connectPtr) { qWarning()<< "[KyConnectResourse]" <<"get connect failed, connect uuid"<isActiveConnection(connectPtr->uuid())) { qDebug()<<"[KyConnectResourse]"<name()<<"is active connection"; return nullptr; } KyConnectItem *connectItem = getConnectionItem(connectPtr, ""); if (nullptr != connectItem) { //connectItem->dumpInfo(); return connectItem; } return nullptr; } KyConnectItem * KyConnectResourse::getConnectionItemByUuidWithoutActivateChecking(QString connectUuid) { NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(connectUuid); if (nullptr == connectPtr) { qWarning()<< "[KyConnectResourse]" <<"get connect failed, connect uuid"<dumpInfo(); return connectItem; } return nullptr; } KyConnectItem * KyConnectResourse::getConnectionItemByUuid(QString connectUuid, QString deviceName) { NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(connectUuid); if (nullptr == connectPtr) { qWarning()<< "[KyConnectResourse]" <<"get connect failed, connect uuid"<settings()->interfaceName(); if (!connectInterface.isEmpty() && deviceName != connectInterface) { qDebug()<<"[KyConnectResourse]" << "connect name:"<< connectPtr->name() << "connect device name" << connectInterface; return nullptr; } if (m_networkResourceInstance->isActiveConnection(connectPtr->uuid())) { qDebug()<<"[KyConnectResourse]"<name()<<"is active connection"; return nullptr; } KyConnectItem *connectItem = getConnectionItem(connectPtr, deviceName); if (nullptr != connectItem) { //connectItem->dumpInfo(); return connectItem; } return nullptr; } void KyConnectResourse::getVpnAndVirtualConnections(QList &connectItemList) { int index = 0; NetworkManager::Connection::List connectList; qDebug()<<"[KyConnectResourse]"<<"get vpn && virtual connections"; connectList.clear(); connectList = m_networkResourceInstance->getConnectList(); if (connectList.empty()) { qWarning()<<"[KyConnectResourse]"<<"get vpn connections failed, the connect list is empty"; return; } NetworkManager::Connection::Ptr connectPtr = nullptr; for (index = 0; index < connectList.size(); index++) { connectPtr = connectList.at(index); if (connectPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::ConnectionType::Vpn != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Bond != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Bridge != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Vlan != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Team != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::IpTunnel != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Wired != connectPtr->settings()->connectionType()) { continue; } NetworkManager::Device::Ptr devicePtr = nullptr; devicePtr = m_networkResourceInstance->findDeviceInterface(connectPtr->settings()->interfaceName()); if (NetworkManager::ConnectionSettings::ConnectionType::Wired == connectPtr->settings()->connectionType()) { if (devicePtr == nullptr || !devicePtr->udi().startsWith("/sys/devices/virtual/net")) { continue; } } QString devName = ""; if (!devicePtr.isNull()) { devName = devicePtr->interfaceName(); } KyConnectItem *connectItem = getConnectionItem(connectPtr, devName); if (nullptr != connectItem) { connectItemList << connectItem; } connectPtr = nullptr; } if (connectItemList.size() > 1) { vpnListSort(connectItemList); } } void KyConnectResourse::getConnectionList(QString deviceName, NetworkManager::ConnectionSettings::ConnectionType connectionType, QList &connectItemList) { NetworkManager::Connection::List connectList; qDebug()<<"[KyConnectResourse]"<<"get connections item, device" <getConnectList(); if (connectList.empty()) { qWarning()<<"[KyConnectResourse]"<<"get connection failed, the connect list is empty"; return; } NetworkManager::Connection::Ptr connectPtr = nullptr; for (int index = 0; index < connectList.size(); index++) { connectPtr = connectList.at(index); if (connectPtr.isNull()) { continue; } if (connectionType != connectPtr->settings()->connectionType()) { qDebug()<<"[KyConnectResourse]"<<"connect name:" << connectPtr->name() <<"connect type:"<settings()->connectionType(); continue; } QString connectInterface = connectPtr->settings()->interfaceName(); if (!connectInterface.isEmpty() && deviceName != connectInterface) { qDebug() << "[KyConnectResourse]" << "connect name:"<< connectPtr->name() << "connect device name" << connectInterface; continue; } if (m_networkResourceInstance->isActiveConnection(connectPtr->uuid())) { qDebug()<<"[KyConnectResourse]"<name()<<"is active connection"; continue; } KyConnectItem *connectItem = getConnectionItem(connectPtr, deviceName); if (nullptr != connectItem) { // connectItem->m_itemType = connectionType; connectItemList << connectItem; //connectItem->dumpInfo(); } connectPtr = nullptr; } if (connectItemList.size() > 1) { lanListSort(connectItemList); } return; } #if 0 void KyConnectResourse::getWiredConnections(QList &wiredConnectItemList) { int index = 0; NetworkManager::Connection::List connectList; qDebug()<<"[KyConnectResourse]"<<"get wired connections"; connectList.clear(); connectList = m_networkResourceInstance->getConnectList(); if (connectList.empty()) { qWarning()<<"[KyConnectResourse]"<<"get wired connection failed, the connect list is empty"; return; } NetworkManager::Connection::Ptr connectPtr = nullptr; for (index = 0; index < connectList.size(); index++) { connectPtr = connectList.at(index); if (NetworkManager::ConnectionSettings::ConnectionType::Wired != connectPtr->settings()->connectionType()) { qDebug()<<"[KyConnectResourse]"<<"connect name:" << connectPtr->name() <<"connect type:"<settings()->connectionType(); continue; } if (m_networkResourceInstance->isActiveConnection(connectPtr->uuid())) { qDebug()<<"[KyConnectResourse]"<name()<<"is active connection"; continue; } KyWiredConnectItem *connectItem = getWiredConnectItem(connectPtr); if (nullptr != connectItem) { wiredConnectItemList << connectItem; connectItem->dumpInfo(); } connectPtr = nullptr; } return; } KyWiredConnectItem *KyConnectResourse::getWiredConnectItem(NetworkManager::Connection::Ptr connectPtr) { qDebug()<<"[KyConnectResourse]"<<"get connect item"; if (nullptr == connectPtr) { qWarning()<<"[KyConnectResourse]"<<"the connect is empty"; return nullptr; } KyWiredConnectItem *wiredItem = new KyWiredConnectItem(); NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); wiredItem->m_connectName = connectPtr->name(); wiredItem->m_connectUuid = connectPtr->uuid(); wiredItem->m_ifaceName = settingPtr->interfaceName(); getConnectIp(settingPtr, wiredItem->m_ipv4, wiredItem->m_ipv6); m_networkdevice->getWiredHardwareInfo(settingPtr->interfaceName(), wiredItem); wiredItem->m_state = NetworkManager::ActiveConnection::State::Deactivated; //wiredItem->m_itemType; return wiredItem; } #endif void KyConnectResourse::getConnectIp( NetworkManager::ConnectionSettings::Ptr settingPtr, QString &ipv4Address, QString &ipv6Address) { NetworkManager::Ipv4Setting::Ptr ipv4Setting = settingPtr->setting(NetworkManager::Setting::Ipv4).dynamicCast(); if (NetworkManager::Ipv4Setting::Manual == ipv4Setting->method()) { QList ipv4AddressList = ipv4Setting->addresses(); NetworkManager::IpAddress settingIpv4Address = ipv4AddressList.at(0); if (settingIpv4Address.isValid()) { ipv4Address = settingIpv4Address.ip().toString(); } else { qWarning()<<"[KyConnectResourse]"<<"get connect ipv4 failed, ipv4Address is not valid"; } } else { qWarning()<<"[KyConnectResourse]"<<"get connect ipv4 failed, ipv4 config with dhcp"; } NetworkManager::Ipv6Setting::Ptr ipv6Setting = settingPtr->setting(NetworkManager::Setting::Ipv6).dynamicCast(); if (nullptr !=ipv6Setting && NetworkManager::Ipv4Setting::Manual == ipv6Setting->method()) { QList ipv6AddressList = ipv6Setting->addresses(); NetworkManager::IpAddress settingIpv6Address = ipv6AddressList.at(0); if (settingIpv6Address.isValid()) { ipv6Address = settingIpv6Address.ip().toString(); } else { qWarning()<<"[KyConnectResourse]"<<"get connect ipv6 failed, ipv6Address is not valid"; } } else { qWarning()<<"[KyConnectResourse]"<<"get connect ipv6 failed, ipv6 config with dhcp"; } return; } void KyConnectResourse::getIpv4ConnectSetting( NetworkManager::Ipv4Setting::Ptr &ipv4Setting, KyConnectSetting &connectSetting) { if (ipv4Setting.isNull()) { connectSetting.m_ipv4Dns.clear(); connectSetting.m_ipv4ConfigIpType = CONFIG_IP_DHCP; connectSetting.m_ipv4Address.clear(); return; } connectSetting.m_ipv4Dns = ipv4Setting->dns(); if (NetworkManager::Ipv4Setting::Automatic == ipv4Setting->method()) { connectSetting.m_ipv4ConfigIpType = CONFIG_IP_DHCP; return; } connectSetting.m_ipv4ConfigIpType = CONFIG_IP_MANUAL; connectSetting.m_ipv4Address = ipv4Setting->addresses(); } void KyConnectResourse::getIpv6ConnectSetting( NetworkManager::Ipv6Setting::Ptr &ipv6Setting, KyConnectSetting &connectSetting) { if (ipv6Setting.isNull()) { connectSetting.m_ipv6Dns.clear(); connectSetting.m_ipv6ConfigIpType = CONFIG_IP_DHCP; connectSetting.m_ipv6Address.clear(); return; } connectSetting.m_ipv6Dns = ipv6Setting->dns(); if (NetworkManager::Ipv6Setting::Automatic == ipv6Setting->method()) { connectSetting.m_ipv6ConfigIpType = CONFIG_IP_DHCP; return; } connectSetting.m_ipv6ConfigIpType = CONFIG_IP_MANUAL; connectSetting.m_ipv6Address = ipv6Setting->addresses(); } void KyConnectResourse::getConnectivity(NetworkManager::Connectivity &connectivity) { m_networkResourceInstance->getConnectivity(connectivity); } NetworkManager::ActiveConnection::State KyConnectResourse::getActiveConnectionState(const QString uuid) { return m_networkResourceInstance->getActiveConnectionState(uuid); } void KyConnectResourse::getConnectionSetting(QString connectUuid, KyConnectSetting &connectSetting) { qDebug() <<"[KyConnectResourse]" << connectUuid <<"get connect setting info, connect uuid"; NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(connectUuid); if (nullptr == connectPtr || !connectPtr->isValid()) { qWarning() <<"[KyConnectResourse]" << "it can not find valid connection" << connectUuid; return; } connectSetting.m_connectName = connectPtr->name(); NetworkManager::ConnectionSettings::Ptr connectionSettings = connectPtr->settings(); connectSetting.m_ifaceName = connectionSettings->interfaceName(); connectSetting.m_isAutoConnect = connectionSettings->autoconnect(); NetworkManager::Ipv4Setting::Ptr ipv4Setting = connectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); getIpv4ConnectSetting(ipv4Setting, connectSetting); NetworkManager::Ipv6Setting::Ptr ipv6Setting = connectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); getIpv6ConnectSetting(ipv6Setting, connectSetting); return; } bool KyConnectResourse::getInterfaceByUuid(QString &deviceName, const QString connUuid) { deviceName.clear(); NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(connUuid); if (nullptr == connectPtr) { qWarning()<<"getInterfaceByUuid failed, connect uuid"<settings(); if (connectSettingPtr.isNull()) { qWarning()<<"getInterfaceByUuid failed, connect uuid"<settings()->interfaceName(); qDebug() << "getInterfaceByUuid success " << deviceName; return true; } void KyConnectResourse::getVpnConnectData(NetworkManager::ConnectionSettings::Ptr settingsPtr, KyVpnConnectItem *vpnItem) { NetworkManager::VpnSetting::Ptr vpnSetting = settingsPtr->setting(NetworkManager::Setting::Vpn).dynamicCast(); NMStringMap vpnDataMap = vpnSetting->data(); if (vpnDataMap.isEmpty()) { qWarning()<<"get vpn connection Data failed, the data is empty"; return; } vpnItem->m_vpnGateWay = vpnDataMap["gateway"]; vpnItem->m_vpnUser = vpnDataMap["user"]; if ( "yes" == vpnDataMap["require-mppe"]) { vpnItem->m_vpnMppe = true; } else { vpnItem->m_vpnMppe = false; qDebug()<<"vpn mppe required:"<< vpnDataMap["require-mppe"]; } return; } KyVpnConnectItem *KyConnectResourse::getVpnConnectItem(NetworkManager::Connection::Ptr connectPtr) { if (nullptr == connectPtr) { qWarning()<<"[KyConnectResourse]"<<"get vpn connection item failed, the connect is empty"; return nullptr; } KyVpnConnectItem *vpnItem = new KyVpnConnectItem(); NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); vpnItem->m_vpnName = connectPtr->name(); vpnItem->m_vpnUuid = connectPtr->uuid(); vpnItem->m_vpnState = NetworkManager::VpnConnection::State::Disconnected; getConnectIp(settingPtr, vpnItem->m_vpnIpv4Address, vpnItem->m_vpnIpv6Address); getVpnConnectData(settingPtr, vpnItem); return vpnItem; } void KyConnectResourse::getVpnConnections(QList &vpnConnectItemList) { int index = 0; NetworkManager::Connection::List connectList; qDebug()<<"[KyConnectResourse]"<<"get vpn connections"; connectList.clear(); connectList = m_networkResourceInstance->getConnectList(); if (connectList.empty()) { qWarning()<<"[KyConnectResourse]"<<"get vpn connections failed, the connect list is empty"; return; } NetworkManager::Connection::Ptr connectPtr = nullptr; for (index = 0; index < connectList.size(); index++) { connectPtr = connectList.at(index); if (connectPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::ConnectionType::Vpn != connectPtr->settings()->connectionType()) { qDebug()<<"[KyConnectResourse]"<<"connect name:" << connectPtr->name() <<"connect type:"<settings()->connectionType(); continue; } if (m_networkResourceInstance->isActiveConnection(connectPtr->uuid())) { qDebug()<<"[KyConnectResourse]"<name()<<"is active connection"; continue; } KyVpnConnectItem *connectItem = getVpnConnectItem(connectPtr); if (nullptr != connectItem) { vpnConnectItemList << connectItem; //connectItem->dumpInfo(); } connectPtr = nullptr; } return; } KyBluetoothConnectItem *KyConnectResourse::getBluetoothConnectItem(NetworkManager::Connection::Ptr connectPtr) { if (nullptr == connectPtr) { qWarning()<<"[KyConnectResourse]"<<"get bluetooth connection item failed, the connect is empty"; return nullptr; } KyBluetoothConnectItem *bluetoothItem = new KyBluetoothConnectItem(); bluetoothItem->m_connectName = connectPtr->name(); bluetoothItem->m_connectUuid = connectPtr->uuid(); bluetoothItem->m_state = NetworkManager::ActiveConnection::State::Deactivated; NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); getConnectIp(settingPtr, bluetoothItem->m_ipv4Address, bluetoothItem->m_ipv6Address); NetworkManager::BluetoothSetting::Ptr bluetoothSetting = settingPtr->setting(NetworkManager::Setting::Bluetooth).dynamicCast(); bluetoothItem->m_deviceAddress = bluetoothSetting->bluetoothAddress(); QByteArray btAddrArray = bluetoothSetting->bluetoothAddress(); for (int index = 0; index < btAddrArray.size(); ++index) { qDebug("bt address %d %s", index, btAddrArray[index]); } // qDebug()<<"bt address 0:"<< btAddrArray[0]; // qDebug()<<"bt address 1:"<< btAddrArray[1]; // qDebug()<<"array size:"<m_deviceAddress.toInt(nullptr, 16); return bluetoothItem; } void KyConnectResourse::getBluetoothConnections(QList &bluetoothConnectItemList) { int index = 0; NetworkManager::Connection::List connectList; qDebug()<<"[KyConnectResourse]"<<"get bluetooth connections"; connectList.clear(); connectList = m_networkResourceInstance->getConnectList(); if (connectList.empty()) { qWarning()<<"[KyConnectResourse]"<<"get bluetooth connections failed, the connect list is empty"; return; } NetworkManager::Connection::Ptr connectPtr = nullptr; for (index = 0; index < connectList.size(); index++) { connectPtr = connectList.at(index); if (connectPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::ConnectionType::Bluetooth != connectPtr->settings()->connectionType()) { qDebug()<<"[KyConnectResourse]"<<"connect name:" << connectPtr->name() <<"connect type:"<settings()->connectionType(); continue; } if (m_networkResourceInstance->isActiveConnection(connectPtr->uuid())) { qDebug()<<"[KyConnectResourse]"<name()<<"is active connection"; continue; } KyBluetoothConnectItem *connectItem = getBluetoothConnectItem(connectPtr); if (nullptr != connectItem) { bluetoothConnectItemList << connectItem; //connectItem->dumpInfo(); } connectPtr = nullptr; } return; } KyApConnectItem *KyConnectResourse::getApConnectItem(NetworkManager::Connection::Ptr connectPtr) { if (nullptr == connectPtr) { qWarning()<<"[KyConnectResourse]"<<"get bluetooth connection item failed, the connect is empty"; return nullptr; } NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); NetworkManager::WirelessSetting::Ptr wirelessSetting = settingPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); if (NetworkManager::WirelessSetting::NetworkMode::Ap != wirelessSetting->mode()) { qDebug() << "[KyConnectResourse]" <<"get ap item failed, the active connect mode is not ap."; return nullptr; } #ifdef CHECKDEVICE KyNetworkDeviceResourse deviceResource; if (!deviceResource.wirelessDeviceIsExist(settingPtr->interfaceName())) { qDebug() << "[KyConnectResourse]" <<"get ap item failed, the ap device is not exist yet"; return nullptr; } #endif QByteArray rawSsid = wirelessSetting->ssid(); KyApConnectItem *apConnectItem = new KyApConnectItem(); apConnectItem->m_connectName = connectPtr->name(); apConnectItem->m_connectSsid = getSsidFromByteArray(rawSsid); apConnectItem->m_connectUuid = connectPtr->uuid(); if (wirelessSetting->band() == NetworkManager::WirelessSetting::FrequencyBand::A) { apConnectItem->m_band = str5GBand; } else if (wirelessSetting->band() == NetworkManager::WirelessSetting::FrequencyBand::Bg) { apConnectItem->m_band = str2GBand; } apConnectItem->m_ifaceName = settingPtr->interfaceName(); apConnectItem->m_isActivated = m_networkResourceInstance->isActiveConnection(connectPtr->uuid()); //NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting // = settingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); KyWirelessConnectOperation wirelessOperation; apConnectItem->m_password = wirelessOperation.getPsk(apConnectItem->m_connectUuid);// wirelessSecuritySetting->psk(); return apConnectItem; } KyApConnectItem *KyConnectResourse::getApConnectionByUuid(QString connectUuid) { NetworkManager::Connection::Ptr connectPtr = nullptr; connectPtr = m_networkResourceInstance->getConnect(connectUuid); if (nullptr == connectPtr) { return nullptr; } if (NetworkManager::ConnectionSettings::ConnectionType::Wireless != connectPtr->settings()->connectionType()) { return nullptr; } KyApConnectItem *connectItem = getApConnectItem(connectPtr); return connectItem; } QString KyConnectResourse::getApConnectionPathByUuid(QString connectUuid) { NetworkManager::Connection::Ptr connectPtr = nullptr; connectPtr = m_networkResourceInstance->getConnect(connectUuid); if (nullptr == connectPtr) { return nullptr; } return connectPtr->path(); } void KyConnectResourse::getApConnections(QList &apConnectItemList) { QList apActiveConnectItemList; QList apDeactiveConnectItemList; int index = 0; NetworkManager::Connection::List connectList; qDebug()<<"[KyConnectResourse]"<<"get ap connections"; connectList.clear(); connectList = m_networkResourceInstance->getConnectList(); if (connectList.empty()) { qWarning()<<"[KyConnectResourse]"<<"get ap connections failed, the connect list is empty"; return; } NetworkManager::Connection::Ptr connectPtr = nullptr; for (index = 0; index < connectList.size(); index++) { connectPtr = connectList.at(index); if (NetworkManager::ConnectionSettings::ConnectionType::Wireless != connectPtr->settings()->connectionType()) { qDebug()<<"[KyConnectResourse]"<<"connect name:" << connectPtr->name() <<"connect type:"<settings()->connectionType(); continue; } KyApConnectItem *connectItem = getApConnectItem(connectPtr); if (nullptr != connectItem) { if (connectItem->m_isActivated) { apActiveConnectItemList << connectItem; } else { apDeactiveConnectItemList << connectItem; } } connectPtr = nullptr; } apConnectItemList << apActiveConnectItemList << apDeactiveConnectItemList; return; } bool KyConnectResourse::isVirtualConncection(QString uuid) { NetworkManager::Connection::Ptr connectPtr = nullptr; connectPtr = m_networkResourceInstance->getConnect(uuid); if (nullptr == connectPtr) { return false; } if (NetworkManager::ConnectionSettings::ConnectionType::Vpn == connectPtr->settings()->connectionType() ||NetworkManager::ConnectionSettings::ConnectionType::Bond == connectPtr->settings()->connectionType() ||NetworkManager::ConnectionSettings::ConnectionType::Bridge == connectPtr->settings()->connectionType() ||NetworkManager::ConnectionSettings::ConnectionType::Vlan == connectPtr->settings()->connectionType() ||NetworkManager::ConnectionSettings::ConnectionType::Team == connectPtr->settings()->connectionType() ||NetworkManager::ConnectionSettings::ConnectionType::IpTunnel == connectPtr->settings()->connectionType()) { return true; } NetworkManager::Device::Ptr devicePtr = nullptr; devicePtr = m_networkResourceInstance->findDeviceInterface(connectPtr->settings()->interfaceName()); if (devicePtr.isNull()) { return false; } if (devicePtr->udi().startsWith("/sys/devices/virtual/net")) { return true; } return false; } bool KyConnectResourse::isWiredConnection(QString uuid) { NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(uuid); if (connectPtr.isNull()) { qWarning()<<"[KyConnectResourse]"<<"can not find wired connection"<path(); QString connectionType = getConnectTypeByDbus(connectPath); if (ETHERNET_TYPE == connectionType) { return true; } return false; } bool KyConnectResourse::isWirelessConnection(QString uuid) { NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(uuid); if (connectPtr.isNull()) { qWarning()<<"[KyConnectResourse]"<<"can not find wireless connection"<isValid()) { NetworkManager::ConnectionSettings::Ptr connectSettingPtr = connectPtr->settings(); if (connectSettingPtr.isNull()) { qWarning()<<"[KyConnectResourse]"<<"get connect setting failed, connect uuid"<settings()->connectionType()) { return true; } } return false; } bool KyConnectResourse::isPppoeConnection(QString uuid) { NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(uuid); if (connectPtr.isNull()) { qWarning()<<"[KyConnectResourse]"<<"can not find wireless connection"<isValid()) { NetworkManager::ConnectionSettings::Ptr connectSettingPtr = connectPtr->settings(); if (connectSettingPtr.isNull()) { qWarning()<<"[KyConnectResourse]"<<"get connect setting failed, connect uuid"<settings()->connectionType()) { return true; } } return false; } bool KyConnectResourse::isActivatedConnection(QString uuid) { return m_networkResourceInstance->isActiveConnection(uuid); } bool KyConnectResourse::isApConnection(QString uuid) { NetworkManager::Connection::Ptr connectPtr = nullptr; connectPtr = m_networkResourceInstance->getConnect(uuid); if (nullptr == connectPtr) { return false; } if (NetworkManager::ConnectionSettings::ConnectionType::Wireless != connectPtr->settings()->connectionType()) { return false; } NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); NetworkManager::WirelessSetting::Ptr wirelessSetting = settingPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); if (NetworkManager::WirelessSetting::NetworkMode::Ap != wirelessSetting->mode()) { return false; } return true; } kylin-nm/src/backend/dbus-interface/kylinconnectresource.h0000664000175000017500000001060615167651420022742 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINCONNECTRESOURCE_H #define KYLINCONNECTRESOURCE_H #include #include "kylinnetworkresourcemanager.h" #include "kylinconnectitem.h" #include "kylinvpnconnectitem.h" #include "kylinbluetoothconnectitem.h" #include "kylinnetworkdeviceresource.h" #include "kylinconnectsetting.h" #include "kylinapconnectitem.h" class KyConnectResourse : public QObject { Q_OBJECT public: explicit KyConnectResourse(QObject *parent = nullptr); ~KyConnectResourse(); public: KyConnectItem *getConnectionItemByUuid(QString connectUuid); KyConnectItem *getConnectionItemByUuidWithoutActivateChecking(QString connectUuid); KyConnectItem *getConnectionItemByUuid(QString connectUuid, QString deviceName); void getVpnAndVirtualConnections(QList &connectItemList); void getConnectionList(QString deviceName, NetworkManager::ConnectionSettings::ConnectionType connectionType, QList &connectItemList); // void getWiredConnections(QList &wiredConnectItemList); void getVpnConnections(QList &vpnConnectItemList); void getBluetoothConnections(QList &bluetoothConnectItemList); void getApConnections(QList &apConnectItemList); KyApConnectItem *getApConnectionByUuid(QString connectUuid); QString getApConnectionPathByUuid(QString connectUuid); QString getApAcitveConnectionPathByUuid(QString connectUuid); void getConnectionSetting(QString connectUuid, KyConnectSetting &connectSetting); bool getInterfaceByUuid(QString &deviceName, const QString connUuid); void getConnectivity(NetworkManager::Connectivity &connectivity); NetworkManager::ActiveConnection::State getActiveConnectionState(const QString uuid); bool isVirtualConncection(QString uuid); bool isWiredConnection(QString uuid); bool isWirelessConnection(QString uuid); bool isPppoeConnection(QString uuid); bool isActivatedConnection(QString uuid); bool isApConnection(QString uuid); private: bool isActiveDevice(QString conUuid, QString devName); KyConnectItem *getConnectionItem(NetworkManager::Connection::Ptr connectPtr, QString devName); void getConnectIp(NetworkManager::ConnectionSettings::Ptr settingPtr, QString &ipv4Address, QString &ipv6Address); // KyWiredConnectItem *getWiredConnectItem(NetworkManager::Connection::Ptr connectPtr); void getVpnConnectData(NetworkManager::ConnectionSettings::Ptr settingPtr, KyVpnConnectItem *vpnItem); KyVpnConnectItem *getVpnConnectItem(NetworkManager::Connection::Ptr connectPtr); KyBluetoothConnectItem *getBluetoothConnectItem(NetworkManager::Connection::Ptr connectPtr); KyApConnectItem *getApConnectItem(NetworkManager::Connection::Ptr connectPtr); void getIpv4ConnectSetting(NetworkManager::Ipv4Setting::Ptr &ipv4Setting, KyConnectSetting &connectSetting); void getIpv6ConnectSetting(NetworkManager::Ipv6Setting::Ptr &ipv6Setting, KyConnectSetting &connectSetting); Q_SIGNALS: void connectionAdd(QString uuid); void connectionUpdate(QString uuid); void connectionRemove(QString path); void connectivityChanged(NetworkManager::Connectivity connectivity); void connectivityCheckSpareUriChanged(); void needShowDesktop(QString); private: KyNetworkResourceManager *m_networkResourceInstance = nullptr; }; #endif // KYLINCONNECTRESOURCE_H kylin-nm/src/backend/dbus-interface/kylinvpnrequest.h0000664000175000017500000000371415167651420021757 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLIN_VPN_REQUEST_H #define KYLIN_VPN_REQUEST_H #include #include "kylinagent.h" typedef struct _SecretsRequest SecretsRequest; typedef void (*SecretsRequestFreeFunc) (SecretsRequest *req); struct _SecretsRequest { size_t totsize; gpointer reqid; char *setting_name; char **hints; guint32 flags; AppletAgent *agent; AppletAgentSecretsCallback callback; gpointer callback_data; NMConnection *connection; /* Class-specific stuff */ SecretsRequestFreeFunc free_func; }; size_t applet_vpn_request_get_secrets_size(void); void applet_secrets_request_complete (SecretsRequest *req, GVariant *settings, GError *error); void applet_secrets_request_free (SecretsRequest *req); void applet_secrets_request_set_free_func (SecretsRequest *req, SecretsRequestFreeFunc free_func); gboolean applet_vpn_request_get_secrets(SecretsRequest *req, GError **error); #endif /* APPLET_VPN_REQUEST_H */ kylin-nm/src/backend/dbus-interface/kylinconnectsetting.h0000664000175000017500000000427215167646234022601 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include //#include #include #include #include #include #include typedef enum { CONFIG_IP_MANUAL, CONFIG_IP_DHCP, }KyIpConfigType; typedef enum { IPADDRESS_V4, IPADDRESS_V6, }KyIpAddressType; class KyConnectSetting/* : public QObject*/ { // Q_OBJECT public: /* explicit*/ KyConnectSetting(/*QObject *parent = nullptr*/); ~KyConnectSetting(); public: void setIfaceName(QString &ifaceName); void setConnectName(QString &connectName); int setIpConfigType(KyIpAddressType ipType, KyIpConfigType configType); void ipv4DnsConstruct(QList &ipv4Dns); void ipv4AddressConstruct(QString &ipv4Address, QString &ipv4NetMask, QString &ipv4GateWay); void ipv6DnsConstruct(QList &ipv6Dns); void ipv6AddressConstruct(QString &ipv6Address, QString &ipv6NetMask, QString &ipv6GateWay); void dumpInfo(); public: QString m_connectName; QString m_ifaceName; KyIpConfigType m_ipv4ConfigIpType; QList m_ipv4Address; QList m_ipv4Dns; KyIpConfigType m_ipv6ConfigIpType; QList m_ipv6Address; QList m_ipv6Dns; bool m_isAutoConnect; }; #endif // KYLINCONNECTSETTING_H kylin-nm/src/backend/dbus-interface/kylinactiveconnectresource.h0000664000175000017500000001056415167651420024141 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINACTIVECONNECTRESOURCE_H #define KYLINACTIVECONNECTRESOURCE_H #include #include "kylinnetworkresourcemanager.h" #include "kylinconnectitem.h" #include "kylinnetworkdeviceresource.h" #include "kylinvpnconnectitem.h" #include "kylinbluetoothconnectitem.h" #include "kylinapconnectitem.h" class KyActiveConnectResourse : public QObject { Q_OBJECT public: explicit KyActiveConnectResourse(QObject *parent = nullptr); ~KyActiveConnectResourse(); public: KyConnectItem *getActiveConnectionByUuid(QString connectUuid); KyConnectItem *getActiveConnectionByUuid(QString connectUuid, QString deviceName); void getActiveConnectionList(QString deviceName, NetworkManager::ConnectionSettings::ConnectionType connectionType, QList &connectItemList); void getActiveConnectIpInfo(const QString &uuid, QString &ipv4Address, QString &ipv6Address); void getActiveConnectDnsInfo(const QString &uuid, QList &ipv4Dns, QList &ipv6Dns); //void getWiredActivateConnect(QList &wiredActiveConnectItemList); void getVpnActivateConnect(QList &vpnActiveConnectItemList); void getBtActivateConnect(QList &btActiveConnectItemList); void getApActivateConnect(QList &apConnectItemList); QString getDeviceOfActivateConnect(QString conUuid); bool connectionIsVirtual(QString uuid); bool wiredConnectIsActived(); bool checkWirelessStatus(NetworkManager::ActiveConnection::State state); QString getAcitveConnectionPathByUuid(QString uuid); int getActivateWifiSignal(QString devName = ""); bool checkInternetLoading(); private: void getActiveConnectIp(NetworkManager::ActiveConnection::Ptr activeConnectPtr, QString &ipv4Address, QString &ipv6Address); void getActiveConnectDns(NetworkManager::ActiveConnection::Ptr activeConnectPtr, QList &ipv4Dns, QList &ipv6Dns); KyConnectItem *getActiveConnectionItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr); // KyWiredConnectItem *getWiredActiveConnectItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr); KyVpnConnectItem *getVpnActiveConnectItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr); KyBluetoothConnectItem *getBtActiveConnectItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr); KyApConnectItem *getApActiveConnectItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr); Q_SIGNALS: void activeConnectAdd(QString activeConnectUuid); void updateActiveConnect(QString activeConnectUuid); void activeConnectRemove(QString activeConnectUuid); void stateChangeReason(QString uuid, NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason); void vpnConnectChangeReason(QString uuid, NetworkManager::VpnConnection::State state, NetworkManager::VpnConnection::StateChangeReason reason); private: KyNetworkResourceManager *m_networkResourceInstance = nullptr; KyNetworkDeviceResourse *m_networkdevice = nullptr; }; #endif // KYLINACTIVECONNECTRESOURCE_H kylin-nm/src/backend/dbus-interface/kylinagent.h0000664000175000017500000000562015167646234020646 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef __KYLINNMANGENT_H__ #define __KYLINNMANGENT_H__ #ifdef __cplusplus extern "C"{ #endif #include #include #include #include #include #define APPLET_TYPE_AGENT (applet_agent_get_type ()) #define APPLET_AGENT(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), APPLET_TYPE_AGENT, AppletAgent)) #define APPLET_AGENT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), APPLET_TYPE_AGENT, AppletAgentClass)) #define APPLET_IS_AGENT(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), APPLET_TYPE_AGENT)) #define APPLET_IS_AGENT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), APPLET_TYPE_AGENT)) #define APPLET_AGENT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), APPLET_TYPE_AGENT, AppletAgentClass)) #define APPLET_AGENT_GET_SECRETS "get-secrets" #define APPLET_AGENT_CANCEL_SECRETS "cancel-secrets" typedef struct { NMSecretAgentOld parent; } AppletAgent; typedef void (*AppletAgentSecretsCallback) (AppletAgent *self, GVariant *secrets, GError *error, gpointer user_data); typedef struct { NMSecretAgentOldClass parent_class; void (*get_secrets) (AppletAgent *self, void *request_id, NMConnection *connection, const char *setting_name, const char **hints, guint32 flags, AppletAgentSecretsCallback callback, gpointer callback_data); void (*cancel_secrets) (AppletAgent *self, void *request_id); } AppletAgentClass; GType applet_agent_get_type (void) G_GNUC_CONST; AppletAgent *applet_agent_new (GError **error); void applet_agent_handle_vpn_only (AppletAgent *agent, gboolean vpn_only); #ifdef __cplusplus } #endif #endif kylin-nm/src/backend/dbus-interface/kylinbluetoothconnectitem.cpp0000664000175000017500000000264015167646234024340 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinbluetoothconnectitem.h" KyBluetoothConnectItem::KyBluetoothConnectItem(QObject *parent) : QObject(parent) { m_connectName = ""; m_connectUuid = ""; m_deviceAddress = ""; m_ipv4Address = ""; m_ipv6Address = ""; m_state = NetworkManager::ActiveConnection::State::Deactivated; } KyBluetoothConnectItem::~KyBluetoothConnectItem() { m_connectName = ""; m_connectUuid = ""; m_deviceAddress = ""; m_ipv4Address = ""; m_ipv6Address = ""; m_state = NetworkManager::ActiveConnection::State::Deactivated; } kylin-nm/src/backend/dbus-interface/kylinapconnectitem.h0000664000175000017500000000244715167646234022405 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINAPCONNECTITEM_H #define KYLINAPCONNECTITEM_H #include class KyApConnectItem : public QObject { Q_OBJECT public: explicit KyApConnectItem(QObject *parent = nullptr); ~KyApConnectItem(); public: QString m_connectName; QString m_connectSsid; QString m_connectUuid; QString m_ifaceName; QString m_password; QString m_band; bool m_isActivated; }; #endif // KYLINAPCONNECTITEM_H kylin-nm/src/backend/dbus-interface/kylinagentinterface.c0000664000175000017500000003443615167651420022522 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include GSList * secrets_reqs; #if 0 typedef struct _SecretsRequest SecretsRequest; typedef void (*SecretsRequestFreeFunc) (SecretsRequest *req); struct _SecretsRequest { size_t totsize; gpointer reqid; char *setting_name; char **hints; guint32 flags; AppletAgent *agent; AppletAgentSecretsCallback callback; gpointer callback_data; NMConnection *connection; /* Class-specific stuff */ SecretsRequestFreeFunc free_func; }; #endif typedef struct { SecretsRequest req; GtkWidget *dialog; } NMWifiInfo; static AppletAgent * kylinAgent = NULL; void applet_secrets_request_set_free_func (SecretsRequest *req, SecretsRequestFreeFunc free_func) { req->free_func = free_func; } static void show_ignore_focus_stealing_prevention (GtkWidget *widget) { gtk_widget_realize (widget); gtk_widget_show (widget); gtk_window_present (GTK_WINDOW (widget)); } static GVariant * remove_unwanted_secrets (GVariant *secrets, gboolean keep_8021X) { GVariant *copy, *setting_dict; const char *setting_name; GVariantBuilder conn_builder; GVariantIter conn_iter; g_variant_builder_init (&conn_builder, NM_VARIANT_TYPE_CONNECTION); g_variant_iter_init (&conn_iter, secrets); while (g_variant_iter_next (&conn_iter, "{&s@a{sv}}", &setting_name, &setting_dict)) { if ( !strcmp (setting_name, NM_SETTING_WIRELESS_SECURITY_SETTING_NAME) || (!strcmp (setting_name, NM_SETTING_802_1X_SETTING_NAME) && keep_8021X)) g_variant_builder_add (&conn_builder, "{s@a{sv}}", setting_name, setting_dict); g_variant_unref (setting_dict); } copy = g_variant_builder_end (&conn_builder); g_variant_unref (secrets); return copy; } static void free_wifi_info (SecretsRequest *req) { NMWifiInfo *info = (NMWifiInfo *) req; if (info->dialog) { gtk_widget_hide (info->dialog); gtk_widget_destroy (info->dialog); info->dialog = NULL; } } void applet_secrets_request_free (SecretsRequest *req) { g_return_if_fail (req != NULL); if (req->free_func) req->free_func (req); secrets_reqs = g_slist_remove (secrets_reqs, req); g_object_unref (req->connection); g_free (req->setting_name); g_strfreev (req->hints); memset (req, 0, req->totsize); g_free (req); } void applet_secrets_request_complete (SecretsRequest *req, GVariant *settings, GError *error) { req->callback (req->agent, error ? NULL : settings, error, req->callback_data); } static void get_secrets_dialog_response_cb (GtkDialog *foo, gint response, gpointer user_data) { SecretsRequest *req = user_data; NMWifiInfo *info = (NMWifiInfo *) req; NMAWifiDialog *dialog = NMA_WIFI_DIALOG (info->dialog); NMConnection *connection = NULL; NMSettingWirelessSecurity *s_wireless_sec; GVariant *secrets = NULL; const char *key_mgmt, *auth_alg; gboolean keep_8021X = FALSE; GError *error = NULL; if (response != GTK_RESPONSE_OK) { g_set_error (&error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_USER_CANCELED, "%s.%d (%s): canceled", __FILE__, __LINE__, __func__); goto done; } connection = nma_wifi_dialog_get_connection (dialog, NULL, NULL); if (!connection) { g_set_error (&error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, "%s.%d (%s): couldn't get connection from Wi-Fi dialog.", __FILE__, __LINE__, __func__); goto done; } /* Second-guess which setting NM wants secrets for. */ s_wireless_sec = nm_connection_get_setting_wireless_security (connection); if (!s_wireless_sec) { g_set_error (&error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_INVALID_CONNECTION, "%s.%d (%s): requested setting '802-11-wireless-security'" " didn't exist in the connection.", __FILE__, __LINE__, __func__); goto done; /* Unencrypted */ } secrets = nm_connection_to_dbus (connection, NM_CONNECTION_SERIALIZE_ONLY_SECRETS); if (!secrets) { g_set_error (&error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, "%s.%d (%s): failed to hash connection '%s'.", __FILE__, __LINE__, __func__, nm_connection_get_id (connection)); goto done; } /* If the user chose an 802.1x-based auth method, return 802.1x secrets, * not wireless secrets. Can happen with Dynamic WEP, because NM doesn't * know the capabilities of the AP (since Dynamic WEP APs don't broadcast * beacons), and therefore defaults to requesting WEP secrets from the * wireless-security setting, not the 802.1x setting. */ key_mgmt = nm_setting_wireless_security_get_key_mgmt (s_wireless_sec); if (!strcmp (key_mgmt, "ieee8021x") || !strcmp (key_mgmt, "wpa-eap")) { /* LEAP secrets aren't in the 802.1x setting */ auth_alg = nm_setting_wireless_security_get_auth_alg (s_wireless_sec); if (!auth_alg || strcmp (auth_alg, "leap")) { NMSetting8021x *s_8021x; s_8021x = nm_connection_get_setting_802_1x (connection); if (!s_8021x) { g_set_error (&error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_INVALID_CONNECTION, "%s.%d (%s): requested setting '802-1x' didn't" " exist in the connection.", __FILE__, __LINE__, __func__); goto done; } keep_8021X = TRUE; } } /* Remove all not-relevant secrets (inner dicts) */ secrets = remove_unwanted_secrets (secrets, keep_8021X); g_variant_take_ref (secrets); done: applet_secrets_request_complete (req, secrets, error); applet_secrets_request_free (req); if (secrets) g_variant_unref (secrets); if (connection) nm_connection_clear_secrets (connection); } static gboolean wifi_get_secrets (SecretsRequest *req, GError **error) { NMWifiInfo *info = (NMWifiInfo *) req; g_return_val_if_fail (!info->dialog, FALSE); #if GTK_CHECK_VERSION(3,90,0) gtk_init (); #else int argc = 0; char ***argv = NULL; gtk_init (&argc, argv); #endif NMClient *nm_client = nm_client_new (NULL, NULL); if (!nm_client) { g_set_error (error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, "%s.%d (%s): create nm client failed.", __FILE__, __LINE__, __func__); g_warning ("create nm client failed"); goto l_out; } info->dialog = nma_wifi_dialog_new_for_secrets (nm_client, req->connection, req->setting_name, (const char *const*) req->hints); if (info->dialog) { applet_secrets_request_set_free_func (req, free_wifi_info); g_signal_connect (info->dialog, "response", G_CALLBACK (get_secrets_dialog_response_cb), info); show_ignore_focus_stealing_prevention (info->dialog); } else { g_set_error (error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, "%s.%d (%s): couldn't display secrets UI", __FILE__, __LINE__, __func__); } g_clear_object(&nm_client); l_out: return !!info->dialog; //return 0; } static SecretsRequest * applet_secrets_request_new (size_t totsize, NMConnection *connection, gpointer request_id, const char *setting_name, const char **hints, guint32 flags, AppletAgentSecretsCallback callback, gpointer callback_data, AppletAgent *agent) { SecretsRequest *req; g_return_val_if_fail (totsize >= sizeof (SecretsRequest), NULL); g_return_val_if_fail (connection != NULL, NULL); req = g_malloc0 (totsize); req->totsize = totsize; req->connection = g_object_ref (connection); req->reqid = request_id; req->setting_name = g_strdup (setting_name); req->hints = g_strdupv ((char **) hints); req->flags = flags; req->callback = callback; req->callback_data = callback_data; req->agent = agent; return req; } static void get_existing_secrets_cb (NMSecretAgentOld *agent, NMConnection *connection, GVariant *secrets, GError *secrets_error, gpointer user_data) { SecretsRequest *req = user_data; //NMADeviceClass *dclass; GError *error = NULL; if (secrets) nm_connection_update_secrets (connection, req->setting_name, secrets, NULL); else nm_connection_clear_secrets (connection); /* Let the device class handle secrets */ if (!wifi_get_secrets(req, &error)) { g_warning ("%s:%d - %s", __func__, __LINE__, error ? error->message : "(unknown)"); applet_secrets_request_complete (req, NULL, error); applet_secrets_request_free (req); g_error_free (error); } /* Otherwise success; wait for the secrets callback */ } static void applet_agent_get_secrets_cb (AppletAgent *agent, gpointer request_id, NMConnection *connection, const char *setting_name, const char **hints, guint32 flags, AppletAgentSecretsCallback callback, gpointer callback_data, gpointer user_data) { NMSettingConnection *s_con; GError *error = NULL; SecretsRequest *req = NULL; s_con = nm_connection_get_setting_connection (connection); g_return_if_fail (s_con != NULL); /* VPN secrets get handled a bit differently */ if (!strcmp (nm_setting_connection_get_connection_type (s_con), NM_SETTING_VPN_SETTING_NAME)) { req = applet_secrets_request_new (applet_vpn_request_get_secrets_size (), connection, request_id, setting_name, hints, flags, callback, callback_data, agent); if (!applet_vpn_request_get_secrets (req, &error)) goto error; secrets_reqs = g_slist_prepend (secrets_reqs, req); return; } req = applet_secrets_request_new (sizeof (NMWifiInfo), connection, request_id, setting_name, hints, flags, callback, callback_data, agent); secrets_reqs = g_slist_prepend (secrets_reqs, req); /* Get existing secrets, if any */ nm_secret_agent_old_get_secrets (NM_SECRET_AGENT_OLD (agent), connection, setting_name, hints, NM_SECRET_AGENT_GET_SECRETS_FLAG_NONE, get_existing_secrets_cb, req); return; error: g_warning ("%s", error->message); callback (agent, NULL, error, callback_data); g_error_free (error); if (req) applet_secrets_request_free (req); } static void applet_agent_cancel_secrets_cb (AppletAgent *agent, gpointer request_id, gpointer user_data) { GSList *iter, *next; for (iter = secrets_reqs; iter; iter = next) { SecretsRequest *req = iter->data; next = g_slist_next (iter); if (req->reqid == request_id) { /* cancel and free this password request */ applet_secrets_request_free (req); break; } } } void agent_init() { if (NULL != kylinAgent) { return; } GError *error = NULL; kylinAgent = applet_agent_new (&error); g_signal_connect (kylinAgent, APPLET_AGENT_GET_SECRETS, G_CALLBACK (applet_agent_get_secrets_cb), NULL); g_signal_connect (kylinAgent, APPLET_AGENT_CANCEL_SECRETS, G_CALLBACK (applet_agent_cancel_secrets_cb), NULL); return; } void agent_clear() { if (NULL == kylinAgent) { return; } g_clear_object (&kylinAgent); kylinAgent = NULL; } kylin-nm/src/backend/dbus-interface/kywirelessnetresource.h0000664000175000017500000001006715167646234023162 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYWIRELESSNETRESOURCE_H #define KYWIRELESSNETRESOURCE_H #include #include "kywirelessnetitem.h" #include "kylinnetworkresourcemanager.h" #include "kyenterpricesettinginfo.h" #include "kylinconnectresource.h" #include "kywirelessconnectoperation.h" #include "kylinnetworkdeviceresource.h" //class KyWirelessNetItem; class KyWirelessNetResource : public QObject { Q_OBJECT public: explicit KyWirelessNetResource(QObject *parent = nullptr); ~KyWirelessNetResource(); //ui层调用接口 bool getWifiNetwork(const QString &devIfaceName, const QString &ssid, KyWirelessNetItem &wirelessNetResource); bool getAllDeviceWifiNetwork(QMap> &map); bool getDeviceWifiNetwork(QString devIfaceName, QList &wirelessNetResource); bool getEnterPriseInfoTls(QString &uuid, KyEapMethodTlsInfo &info); bool getEnterPriseInfoPeap(QString &uuid, KyEapMethodPeapInfo &info); bool getEnterPriseInfoTtls(QString &uuid, KyEapMethodTtlsInfo &info); bool getEnterPriseInfoLeap(QString &uuid, KyEapMethodLeapInfo &info); bool getEnterPriseInfoPwd(QString &uuid, KyEapMethodPwdInfo &info); bool getEnterPriseInfoFast(QString &uuid, KyEapMethodFastInfo &info); void getWirelessActiveConnection(NetworkManager::ActiveConnection::State state, QMap &map); bool getActiveWirelessNetItem(QString deviceName, KyWirelessNetItem &wirelessNetItem); QString getActiveConnectSsidByDevice(QString deviceName); void getSsidByUuid(const QString uuid, QString &ssid); void getDeviceByUuid(const QString uuid, QString &deviceName); private: void kyWirelessNetItemListInit(); QString getDeviceIFace(NetworkManager::WirelessNetwork::Ptr net); QString getDeviceIFace(NetworkManager::ActiveConnection::Ptr actConn, QString &wirelessNetResourcessid); public Q_SLOTS: void onWifiNetworkAdded(QString, QString); void onWifiNetworkRemoved(QString, QString); void onWifiNetworkPropertyChange(QString interface, QString ssid, int signal, QString bssid, QString sec); void onWifiNetworkSecuChange(NetworkManager::AccessPoint *accessPointPtr); void onWifiNetworkDeviceDisappear(); void onConnectionAdd(QString uuid); void onConnectionUpdate(QString uuid); void onConnectionRemove(QString); void onDeviceAdd(QString deviceName, NetworkManager::Device::Type deviceType); void onDeviceRemove(QString deviceName); void onDeviceNameUpdate(QString oldName, QString newName); Q_SIGNALS: void signalStrengthChange(QString, QString, int); void bssidChange(QString, QString, QString); void secuTypeChange(QString, QString, QString); void connectionRemove(QString, QString, QString); void connectionAdd(QString, QString); void connectionUpdate(QString, QString); void wifiNetworkUpdate(); void wifiNetworkAdd(QString, KyWirelessNetItem&); void wifiNetworkRemove(QString, QString); private: KyNetworkResourceManager *m_networkResourceInstance = nullptr; KyWirelessConnectOperation *m_operation = nullptr; KyNetworkDeviceResourse *m_networkDevice = nullptr; QMap > m_WifiNetworkList; }; #endif // KYWIRELESSNETRESOURCE_H kylin-nm/src/backend/dbus-interface/kylinconnectitem.cpp0000664000175000017500000000321315167646234022407 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinconnectitem.h" KyConnectItem::KyConnectItem(QObject *parent) : QObject(parent) { m_connectName = ""; m_connectUuid = ""; m_connectPath = ""; m_ifaceName = ""; m_connectState = NetworkManager::ActiveConnection::State::Unknown; //deactive、activing and actived m_itemType = NetworkManager::ConnectionSettings::ConnectionType::Unknown; } KyConnectItem::~KyConnectItem() { } void KyConnectItem::setConnectUuid(QString uuid) { m_connectUuid = uuid; } void KyConnectItem::dumpInfo() { qDebug()<<"wired connection item info:"; qDebug()<<"connect name:"<("NetworkManager::Device::State"); qRegisterMetaType("NetworkManager::Device::StateChangeReason"); qRegisterMetaType("NetworkManager::Connectivity"); m_networkResourceInstance = KyNetworkResourceManager::getInstance(); m_deviceMap.clear(); initDeviceMap(); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceAdd, this, &KyNetworkDeviceResourse::onDeviceAdd/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceRemove, this, &KyNetworkDeviceResourse::onDeviceRemove/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceUpdate, this, &KyNetworkDeviceResourse::onDeviceUpdate/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::stateChanged, this, &KyNetworkDeviceResourse::stateChanged/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceCarrierChanage, this, &KyNetworkDeviceResourse::carrierChanage); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceBitRateChanage, this, &KyNetworkDeviceResourse::deviceBitRateChanage); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceMacAddressChanage, this, &KyNetworkDeviceResourse::deviceMacAddressChanage); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceActiveChanage, this, &KyNetworkDeviceResourse::deviceActiveChanage); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceManagedChange, this, &KyNetworkDeviceResourse::deviceManagedChange); } KyNetworkDeviceResourse::~KyNetworkDeviceResourse() { m_networkResourceInstance = nullptr; } void KyNetworkDeviceResourse::initDeviceMap() { NetworkManager::Device::List deviceList = m_networkResourceInstance->getNetworkDeviceList(); if (deviceList.isEmpty()) { qDebug() << LOG_FLAG << "there is not interface in computer."; return; } NetworkManager::Device::Ptr devicePtr = nullptr; for (int index = 0; index < deviceList.size(); ++index) { devicePtr = deviceList.at(index); if (devicePtr.isNull()) { continue; } m_deviceMap.insert(devicePtr->uni(), devicePtr->interfaceName()); } return; } void KyNetworkDeviceResourse::getNetworkDeviceList( NetworkManager::Device::Type deviceType, QStringList &networkDeviceList) { NetworkManager::Device::List deviceList = m_networkResourceInstance->getNetworkDeviceList(); if (deviceList.isEmpty()) { qDebug() << LOG_FLAG <<"network device is not exist. device type" << deviceType; return; } NetworkManager::Device::Ptr devicePtr = nullptr; for (int index = 0; index < deviceList.size(); ++index) { devicePtr = deviceList.at(index); if (devicePtr.isNull()) { continue; } if (devicePtr->type() == deviceType) { if (NetworkManager::Device::Type::Ethernet == deviceType) { //为了区分有线网卡和虚拟网卡 qDebug()<< LOG_FLAG << "device uni" << devicePtr->udi(); if (devicePtr->udi().startsWith(VIRTURAL_DEVICE_PATH)) { continue; } } networkDeviceList<interfaceName(); } } return; } void KyNetworkDeviceResourse::getHardwareInfo(QString ifaceName, QString &hardAddress, int &bandWith) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->getNetworkDevice(ifaceName); if (nullptr == connectDevice || !connectDevice->isValid()) { qWarning()<< LOG_FLAG <<"get hardware info failed, the device" << ifaceName << "is not existed"; hardAddress.clear(); bandWith = 0; return; } switch (connectDevice->type()) { case NetworkManager::Device::Ethernet: { NetworkManager::WiredDevice *wiredDevicePtr = qobject_cast(connectDevice.data()); hardAddress = wiredDevicePtr->hardwareAddress(); bandWith = wiredDevicePtr->bitRate(); break; } case NetworkManager::Device::Wifi: { NetworkManager::WirelessDevice *wirelessDevicePtr = qobject_cast(connectDevice.data()); hardAddress = wirelessDevicePtr->hardwareAddress(); bandWith = wirelessDevicePtr->bitRate(); break; } default: { hardAddress = ""; bandWith = 0; qWarning()<< LOG_FLAG << "the network device type is undefined" << connectDevice->type(); break; } } return; } NetworkManager::Device::State KyNetworkDeviceResourse::getDeviceState(QString deviceName) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceInterface(deviceName); if (!connectDevice.isNull() && connectDevice->isValid()) { return connectDevice->state(); } qWarning()<< LOG_FLAG <<"get device state failed, the device is " << deviceName; return NetworkManager::Device::State::UnknownState; } bool KyNetworkDeviceResourse::wiredDeviceIsCarriered(QString deviceName) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceInterface(deviceName); if (connectDevice.isNull()) { qDebug()<< LOG_FLAG << "check device carriered failed."; return false; } if (connectDevice->isValid() && NetworkManager::Device::Type::Ethernet == connectDevice->type()) { NetworkManager::WiredDevice *wiredDevicePtr = qobject_cast(connectDevice.data()); return wiredDevicePtr->carrier(); } qWarning()<< LOG_FLAG << deviceName <<" can not get carrier state."; return false; } void KyNetworkDeviceResourse::setDeviceRefreshRate(QString deviceName, int ms) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceInterface(deviceName); if (connectDevice.isNull()) { return; } if (connectDevice->isValid()) { NetworkManager::DeviceStatistics::Ptr deviceStatistics = connectDevice->deviceStatistics(); deviceStatistics->setRefreshRateMs(ms); } return; } qulonglong KyNetworkDeviceResourse::getDeviceRxRefreshRate(QString deviceName) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceInterface(deviceName); if (connectDevice->isValid()) { NetworkManager::DeviceStatistics::Ptr deviceStatistics = connectDevice->deviceStatistics(); qulonglong rx = 0; rx = deviceStatistics->rxBytes(); if (rx != 0) { return rx; } else { qDebug() << "connectDevice is invalid we do not get rxrate"; } } return 0; } qulonglong KyNetworkDeviceResourse::getDeviceTxRefreshRate(QString deviceName) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceInterface(deviceName); if (connectDevice->isValid()) { NetworkManager::DeviceStatistics::Ptr deviceStatistics = connectDevice->deviceStatistics(); qulonglong tx = 0; tx = deviceStatistics->txBytes(); if (tx != 0){ return tx; } else { qDebug() << "connectDevice is invalid we do not get txrate"; } } return 0; } void KyNetworkDeviceResourse::getDeviceConnectivity(const QString &deviceName, NetworkManager::Connectivity &connectivity) { connectivity = NetworkManager::Connectivity::UnknownConnectivity; QString dbusPath; NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceInterface(deviceName); if (connectDevice != nullptr && connectDevice->isValid()) { dbusPath = connectDevice->uni(); } else { qWarning() << "[KyNetworkDeviceResourse] can not find device " << deviceName; return; } QDBusInterface *ip4ConnectivityDbus = new QDBusInterface("org.freedesktop.NetworkManager", dbusPath, "org.freedesktop.DBus.Properties", QDBusConnection::systemBus()); if (ip4ConnectivityDbus == nullptr || !ip4ConnectivityDbus->isValid()) { qWarning() << "[KyNetworkDeviceResourse] get device properties failed"; return; } QDBusReply reply = ip4ConnectivityDbus->call("Get", "org.freedesktop.NetworkManager.Device", "Ip4Connectivity"); if (reply.isValid()) { connectivity = (NetworkManager::Connectivity) reply.value().toUInt(); } else { qWarning() << "[KyNetworkDeviceResourse] get device properties failed"; } delete ip4ConnectivityDbus; ip4ConnectivityDbus = nullptr; } bool KyNetworkDeviceResourse::getActiveConnectionInfo(const QString devName, int &signalStrength, QString &uni, QString &secuType) { signalStrength = 0; uni = ""; NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->getNetworkDevice(devName); if (nullptr == connectDevice || !connectDevice->isValid()) { qWarning()<< LOG_FLAG <<"getDeviceActiveAPInfo failed, the device" << devName << "is not existed"; return false; } if (connectDevice->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice *wirelessDevicePtr = qobject_cast(connectDevice.data()); NetworkManager::AccessPoint::Ptr apPtr = wirelessDevicePtr->activeAccessPoint(); if (apPtr.isNull()) { return false; } signalStrength = apPtr->signalStrength(); uni = apPtr->uni(); NetworkManager::AccessPoint::Capabilities cap = apPtr->capabilities(); NetworkManager::AccessPoint::WpaFlags wpaFlag = apPtr->wpaFlags(); NetworkManager::AccessPoint::WpaFlags rsnFlag = apPtr->rsnFlags(); secuType = enumToQstring(cap, wpaFlag, rsnFlag); return true; } else { return false; } } const QMap g_bFreqs = { {2412, 1}, {2417, 2}, {2422, 3}, {2427, 4}, {2432, 5}, {2437, 6}, {2442, 7}, {2447, 8}, {2452, 9}, {2457, 10}, {2462, 11}, {2467, 12}, {2472, 13}, {2484, 14} }; const QMap g_aFreqs = { {5035, 7}, {5040, 8}, {5045, 9}, {5055, 11}, {5060, 12}, {5080, 16}, {5170, 34}, {5180, 36}, {5190, 38}, {5200, 40}, {5210, 42}, {5220, 44}, {5230, 46}, {5240, 48}, {5260, 52}, {5280, 56}, {5300, 60}, {5320, 64}, {5500, 100}, {5520, 104}, {5540, 108}, {5560, 112}, {5580, 116}, {5600, 120}, {5620, 124}, {5640, 128}, {5660, 132}, {5680, 136}, {5700, 140}, {5745, 149}, {5765, 153}, {5785, 157}, {5805, 161}, {5825, 165}, {4915, 183}, {4920, 184}, {4925, 185}, {4935, 187}, {4940, 188}, {4945, 189}, {4960, 192}, {4980, 196} }; uint KyNetworkDeviceResourse::kyFindChannel(uint freq) { uint channel = 0; QMap freqMap; if (freq < 2500) { freqMap = g_bFreqs; } else { freqMap = g_aFreqs; } for (auto freqKey : freqMap.keys()) { if (freqKey <= freq) { channel = freqMap.value(freqKey); if (freqKey == freq) { break; } } else { break; } } return channel; } void KyNetworkDeviceResourse::getDeviceActiveAPInfo(const QString devName, QString &strMac, uint &iHz, uint &iChan, QString &secuType) { strMac.clear(); iHz = 0; iChan = 0; secuType.clear(); NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->getNetworkDevice(devName); if (nullptr == connectDevice || !connectDevice->isValid()) { qWarning()<< LOG_FLAG <<"getDeviceActiveAPInfo failed, the device" << devName << "is not existed"; return; } switch (connectDevice->type()) { case NetworkManager::Device::Wifi: { NetworkManager::WirelessDevice *wirelessDevicePtr = qobject_cast(connectDevice.data()); NetworkManager::AccessPoint::Ptr apPtr = wirelessDevicePtr->activeAccessPoint(); if (apPtr.isNull()) { break; } strMac = apPtr->hardwareAddress(); iHz = apPtr->frequency(); iChan = kyFindChannel(iHz); NetworkManager::AccessPoint::Capabilities cap = apPtr->capabilities(); NetworkManager::AccessPoint::WpaFlags wpaFlag = apPtr->wpaFlags(); NetworkManager::AccessPoint::WpaFlags rsnFlag = apPtr->rsnFlags(); secuType = enumToQstring(cap, wpaFlag, rsnFlag); break; } case NetworkManager::Device::Ethernet: break; default: break; } return; } int KyNetworkDeviceResourse::getWirelessDeviceCapability(const QString deviceName) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceInterface(deviceName); if (connectDevice->isValid() && NetworkManager::Device::Type::Wifi == connectDevice->type()) { NetworkManager::WirelessDevice *wirelessDevicePtr = qobject_cast(connectDevice.data()); int cap = 0x00; if (wirelessDevicePtr->wirelessCapabilities() & NetworkManager::WirelessDevice::ApCap) { cap = cap | 0x02; } else { return 0x01; } QDBusInterface dbusInterface("org.freedesktop.NetworkManager", connectDevice->uni(), "org.freedesktop.NetworkManager.Device.Wireless", QDBusConnection::systemBus()); QDBusReply reply = dbusInterface.call("GetHotspotCapabilities"); if (reply.isValid()) { if (reply.value() == 1) { cap = cap | 0x04; } } return cap; } else { qWarning()<<"[KyNetworkDeviceResourse]"<findDeviceInterface(deviceName); if (devicePtr.isNull()) { qDebug() << LOG_FLAG << "check device type failed, it is not exist"; return false; } if (deviceType == devicePtr->type()) { if (NetworkManager::Device::Type::Ethernet == deviceType) { if (!devicePtr->udi().startsWith(VIRTURAL_DEVICE_PATH)) { return true; } } else { return true; } } return false; } void KyNetworkDeviceResourse::setDeviceManaged(QString devName, bool managed) { QString dbusPath; NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceInterface(devName); if (connectDevice->isValid()) { dbusPath = connectDevice->uni(); } else { qWarning()<<"[KyNetworkDeviceResourse] can not find device " << devName; return; } setDeviceManagedByGDbus(dbusPath, managed); #if 0 QDBusInterface dbusInterface("org.freedesktop.NetworkManager", dbusPath, "org.freedesktop.NetworkManager.Device", QDBusConnection::systemBus()); if (!dbusInterface.isValid()) { qWarning() << dbusPath << "invalid"; setDeviceManagedByGDbus(dbusPath, managed); return; } QDBusReply reply = dbusInterface.call("SetStateDevice", "", managed); if (!reply.isValid()) { qWarning() << "SetStateDevice error" << reply.error().message(); setDeviceManagedByGDbus(dbusPath, managed); return; } #endif } bool KyNetworkDeviceResourse::getDeviceManaged(QString deviceName) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceInterface(deviceName); if (connectDevice != nullptr && connectDevice->isValid()) { return connectDevice->managed(); } else { qWarning()<<"[KyNetworkDeviceResourse] can not find device " << deviceName; return false; } } kylin-nm/src/backend/dbus-interface/kylinutil.cpp0000664000175000017500000002673515167651420021063 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinutil.h" #include #include #include #include #include #define LOG_FLAG "[kylin-util]" QString getConnectTypeByDbus(QString &connectPath) { QString connectType = ""; if (connectPath.isEmpty()) { qWarning()<< LOG_FLAG << "connect path is empty, so can not get connect type"; return connectType; } QDBusInterface dbusInterface("org.freedesktop.NetworkManager", connectPath, "org.freedesktop.NetworkManager.Settings.Connection", QDBusConnection::systemBus()); QDBusMessage result = dbusInterface.call("GetSettings"); const QDBusArgument &dbusArg1st = result.arguments().at( 0 ).value(); QMap> map; dbusArg1st >> map; if (map.isEmpty()) { qWarning() << LOG_FLAG <<"get connection settings failed."; return connectType; } QMap connectMap = map.value(KEY_CONNECTION); if (connectMap.isEmpty()) { qWarning() << LOG_FLAG <<"threre is not connection settings"; return connectType; } connectType = connectMap.value(KEY_CONNECT_TYPE).toString(); return connectType; } QString getSsidFromByteArray(QByteArray &rawSsid) { QString wifiSsid = ""; if (rawSsid.isEmpty()) { qWarning() << LOG_FLAG << "wifi raw ssid is empty"; return wifiSsid; } /* * 由于区分GB2312和UTF-8的方法比较困难,加之会存在中英文混合的情况,所以暂时 * 不区分,统一经过gb2312转换,经过测试没有影响。 */ // QTextCodec *p_textGBK = QTextCodec::codecForName("GB2312"); // wifiSsid = p_textGBK->toUnicode(rawSsid); QStringDecoder utf8Decoder(QStringDecoder::Utf8); wifiSsid = utf8Decoder(rawSsid); // 如果解码出错或包含替换字符,尝试GBK if (utf8Decoder.hasError() || wifiSsid.contains(QChar::ReplacementCharacter)) { QStringDecoder gbkDecoder("GBK"); if(gbkDecoder.isValid()){ wifiSsid = gbkDecoder(rawSsid); } //gbk不行回退到latin if(gbkDecoder.hasError()){ return QString::fromLatin1(rawSsid); } } return wifiSsid; } void setWiredEnabledByGDbus(bool enabled) { GDBusProxy *props_proxy; GVariant *ret = NULL; GError *error = NULL; /* Create a D-Bus object proxy for the active connection object's properties */ props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.DBus.Properties", NULL, NULL); g_assert (props_proxy); /* Get the object path of the Connection details */ ret = g_dbus_proxy_call_sync (props_proxy, "Set", g_variant_new ("(ssv)", "org.freedesktop.NetworkManager", "WiredEnabled", g_variant_new_boolean(enabled)), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (!ret) { g_dbus_error_strip_remote_error (error); qDebug() << "failed to setWiredEnabledByGDbus"; g_error_free (error); } out: if (ret) g_variant_unref (ret); g_object_unref (props_proxy); } bool getWiredEnabledByGDbus() { GDBusProxy *props_proxy; GVariant *ret = NULL, *path_value = NULL; GError *error = NULL; gboolean bRet = false; /* Create a D-Bus object proxy for the active connection object's properties */ props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.DBus.Properties", NULL, NULL); g_assert (props_proxy); /* Get the object path of the Connection details */ ret = g_dbus_proxy_call_sync (props_proxy, "Get", g_variant_new ("(ss)", "org.freedesktop.NetworkManager", "WiredEnabled"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (!ret) { g_dbus_error_strip_remote_error (error); qDebug() << "failed to setWiredEnabledByGDbus"; g_error_free (error); } g_variant_get (ret, "(v)", &path_value); if (!g_variant_is_of_type (path_value, G_VARIANT_TYPE_BOOLEAN)) { g_warning ("Unexpected type returned getting Connection property: %s", g_variant_get_type_string (path_value)); goto out; } bRet = g_variant_get_boolean (path_value); out: if (path_value) g_variant_unref (path_value); if (ret) g_variant_unref (ret); g_object_unref (props_proxy); return bRet; } void setDeviceManagedByGDbus(QString dbusPath, bool managed) { GDBusProxy *props_proxy; GVariant *ret = NULL; GError *error = NULL; /* Create a D-Bus object proxy for the active connection object's properties */ props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.NetworkManager", dbusPath.toStdString().c_str(), "org.freedesktop.DBus.Properties", NULL, NULL); g_assert (props_proxy); /* Get the object path of the Connection details */ ret = g_dbus_proxy_call_sync (props_proxy, "Set", g_variant_new ("(ssv)", "org.freedesktop.NetworkManager.Device", "Managed", g_variant_new_boolean(managed)), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (!ret) { g_dbus_error_strip_remote_error (error); qDebug() << "failed to setWiredEnabledByGDbus"; g_error_free (error); } out: if (ret) g_variant_unref (ret); g_object_unref (props_proxy); } QString getConnectivityCheckSpareUriByGDbus() { GDBusProxy *props_proxy; GVariant *ret = NULL, *path_value = NULL; GError *error = NULL; QString str; /* Create a D-Bus object proxy for the active connection object's properties */ props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.DBus.Properties", NULL, NULL); g_assert (props_proxy); /* Get the object path of the Connection details */ ret = g_dbus_proxy_call_sync (props_proxy, "Get", g_variant_new ("(ss)", "org.freedesktop.NetworkManager", "ConnectivityCheckSpareUri"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (!ret) { g_dbus_error_strip_remote_error (error); qDebug() << "failed to getConnectivityCheckSpareUri"; g_error_free (error); } g_variant_get (ret, "(v)", &path_value); // if (!g_variant_is_of_type (path_value, G_VARIANT_TYPE_VARIANT)) { // g_warning ("Unexpected type returned getting Connection property: %s", // g_variant_get_type_string (path_value)); // goto out; // } str = QString(g_variant_get_string(path_value, NULL)); out: if (path_value) g_variant_unref (path_value); if (ret) g_variant_unref (ret); g_object_unref (props_proxy); return str; } void setConnectivityCheckSpareUriByGDbus(QString uri) { GDBusProxy *props_proxy; GVariant *ret = NULL; GError *error = NULL; /* Create a D-Bus object proxy for the active connection object's properties */ props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.DBus.Properties", NULL, NULL); g_assert (props_proxy); /* Get the object path of the Connection details */ ret = g_dbus_proxy_call_sync (props_proxy, "Set", g_variant_new ("(ssv)", "org.freedesktop.NetworkManager", "ConnectivityCheckSpareUri", g_variant_new_string(uri.toStdString().c_str())), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (!ret) { g_dbus_error_strip_remote_error (error); qDebug() << "failed to setConnectivityCheckSpareUri"; g_error_free (error); } out: if (ret) g_variant_unref (ret); g_object_unref (props_proxy); } kylin-nm/src/backend/dbus-interface/kylinwiredconnectoperation.cpp0000664000175000017500000002365315167651420024507 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include #include #include #include KyWiredConnectOperation::KyWiredConnectOperation(QObject *parent) : KyConnectOperation(parent) { connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredEnabledChanged, this, &KyWiredConnectOperation::wiredEnabledChanged); } KyWiredConnectOperation::~KyWiredConnectOperation() { } void KyWiredConnectOperation::setWiredEnabled(bool enabled) { setWiredEnabledByGDbus(enabled); } bool KyWiredConnectOperation::getWiredEnabled() { return getWiredEnabledByGDbus(); } void KyWiredConnectOperation::createWiredConnect(KyConnectSetting &connectSettingsInfo) { qDebug()<<"[KyWiredConnectOperation]" << "create connect "; connectSettingsInfo.dumpInfo(); NetworkManager::ConnectionSettings::Ptr wiredConnectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(NetworkManager::ConnectionSettings::Wired)); connectSettingSet(wiredConnectionSettings, connectSettingsInfo); NetworkManager::Ipv4Setting::Ptr ipv4Setting = wiredConnectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); ipv4SettingSet(ipv4Setting, connectSettingsInfo); NetworkManager::Ipv6Setting::Ptr ipv6Setting = wiredConnectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); ipv6SettingSet(ipv6Setting, connectSettingsInfo); NetworkManager::WiredSetting::Ptr wiredSetting = wiredConnectionSettings->setting(NetworkManager::Setting::Wired).dynamicCast(); wiredSetting->setInitialized(true); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(wiredConnectionSettings->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wired connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } else { qDebug()<<"create wired connect complete"; } watcher->deleteLater(); }); return; } void KyWiredConnectOperation::updateWiredConnect(const QString &connectUuid, const KyConnectSetting &connectSettingsInfo) { qDebug()<<"update connect"<settings(); updateConnect(connectSettingPtr, connectSettingsInfo); NMVariantMapMap mapmap1 = connectSettingPtr->toMap(); if (mapmap1.contains("ipv4")) { QVariantMap map1 = mapmap1.value(QLatin1String("ipv4")); bool isAuto = false; if (map1.contains("method") && map1["method"] == "auto") { qDebug() << "[KyWiredConnectOperation] set ipv4 method auto, clear address-data && addresses && gateway"; isAuto = true; } if (isAuto) { if (map1.contains("address-data")) { map1.remove("address-data"); } if (map1.contains("addresses")) { map1.remove("addresses"); } if (map1.contains("gateway")) { map1.remove("gateway"); } } mapmap1["ipv4"] = map1; } if (mapmap1.contains("ipv6")) { QVariantMap map2 = mapmap1.value(QLatin1String("ipv6")); bool isAuto = false; if (map2.contains("method") && map2["method"] == "auto") { qDebug() << "[KyWiredConnectOperation] set ipv6 method auto, clear address-data && addresses && gateway"; isAuto = true; } if (isAuto) { if (map2.contains("address-data")) { map2.remove("address-data"); } if (map2.contains("addresses")) { map2.remove("addresses"); } if (map2.contains("gateway")) { map2.remove("gateway"); } } mapmap1["ipv6"] = map2; } connectPtr->update(mapmap1); return ; } void KyWiredConnectOperation::deleteWiredConnect(const QString &connectUuid) { qDebug()<<"delete wired connect uuid " << connectUuid; deleteConnect(connectUuid); return ; } void KyWiredConnectOperation::activateWiredConnection(const QString connectUuid, const QString devName) { activateConnection(connectUuid, devName); return ; } void KyWiredConnectOperation::deactivateWiredConnection(const QString activeConnectName, const QString &activeConnectUuid, bool concise, QString devName) { qDebug()<<"deactivetate connect name"<value(deviceName).toString(); if (settingValue.isEmpty()) { p_settings->setValue(deviceName, connectUuid); p_settings->sync(); } delete p_settings; p_settings = nullptr; return; } void KyWiredConnectOperation::getActiveConnection(QString &deviceName, QString &connectUuid) { QSettings *p_settings = new QSettings(WIRED_NETWORK_STATE_CONF_FILE, QSettings::IniFormat); connectUuid = p_settings->value(deviceName).toString(); p_settings->remove(deviceName); delete p_settings; p_settings = nullptr; return; } int KyWiredConnectOperation::closeWiredNetworkWithDevice(QString deviceName) { NetworkManager::Device::Ptr wiredDevicePtr = m_networkResourceInstance->findDeviceInterface(deviceName); if (wiredDevicePtr.isNull()) { qWarning()<<"[KyWiredConnectOperation]"<<"the network device" << deviceName <<"is not exist."; return -ENXIO; } if (NetworkManager::Device::Type::Ethernet != wiredDevicePtr->type()) { qWarning()<<"[KyWiredConnectOperation]"<<"the device type" << wiredDevicePtr->type() <<"is not Ethernet."; return -EINVAL; } NetworkManager::ActiveConnection::Ptr activeConnectPtr = wiredDevicePtr->activeConnection(); if (nullptr != activeConnectPtr) { QString activeConnectUuid = activeConnectPtr->uuid(); if (!activeConnectUuid.isEmpty()) { qDebug()<<"[KyWiredConnectOperation]" <<"close wired network save connection uuid" << activeConnectUuid <<"device name " << deviceName; saveActiveConnection(deviceName, activeConnectUuid); } } //wiredDevicePtr->setAutoconnect(false); wiredDevicePtr->disconnectInterface(); return 0; } int KyWiredConnectOperation::setWiredDeviceAutoconnect(QString deviceName,bool autoconnectstate) { NetworkManager::Device::Ptr wiredDevicePtr = m_networkResourceInstance->findDeviceInterface(deviceName); if (wiredDevicePtr.isNull() || !wiredDevicePtr->isValid()) { qWarning()<<"[KyWiredConnectOperation]"<<"the network device" << deviceName <<"is not exist."; return -ENXIO; } if (NetworkManager::Device::Type::Ethernet != wiredDevicePtr->type()) { qWarning()<<"[KyWiredConnectOperation]"<<"the device type" << wiredDevicePtr->type() <<"is not Ethernet."; return -EINVAL; } wiredDevicePtr->setAutoconnect(autoconnectstate); return 0; } int KyWiredConnectOperation::openWiredNetworkWithDevice(QString deviceName) { NetworkManager::Device::Ptr wiredDevicePtr = m_networkResourceInstance->findDeviceInterface(deviceName); if (wiredDevicePtr.isNull() || !wiredDevicePtr->isValid()) { qWarning()<<"[KyWiredConnectOperation]"<<"the network device" << deviceName <<"is not exist."; return -ENXIO; } if (NetworkManager::Device::Type::Ethernet != wiredDevicePtr->type()) { qWarning()<<"[KyWiredConnectOperation]"<<"the device type" << wiredDevicePtr->type() <<"is not Ethernet."; return -EINVAL; } NetworkManager::WiredDevice *p_wiredDevice = qobject_cast(wiredDevicePtr.data()); if (p_wiredDevice->carrier()) { QString connectUuid; getActiveConnection(deviceName, connectUuid); if (!connectUuid.isEmpty()) { qDebug()<<"[KyWiredConnectOperation]" << "open wired network active connection" << connectUuid <<"device name" << deviceName; activateConnection(connectUuid, deviceName); } } wiredDevicePtr->setAutoconnect(true); return 0; } kylin-nm/src/backend/dbus-interface/kywirelessconnectoperation.h0000664000175000017500000002047115167646234024176 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYWIRELESSCONNECTOPERATION_H #define KYWIRELESSCONNECTOPERATION_H #include #include #include #include "kyenterpricesettinginfo.h" #include "kylinconnectoperation.h" #include "kyenterpricesettinginfo.h" #include "../../common/common.h" #define KEY_802_11_WIRELESS "802-11-wireless" #define KEY_BLACKLIST_HOSTNAME "blacklist-hostname" const QByteArray GSETTINGS_SCHEMA = "org.ukui.kylin-nm.switch"; const QString WIRELESS_SWITCH = "wirelessswitch"; const QString WIFI_BAND_2_4GHZ = "2.4GHz"; const QString WIFI_BAND_5GHZ = "5GHz"; // enum KySecuType { // NONE = 0, // WPA_AND_WPA2_PERSONAL, // WPA_AND_WPA2_ENTERPRISE, // WPA3_PERSONAL, // WPA_AND_WPA3, // }; // enum KyKeyMgmt { // Unknown = -1, // Wep, Ieee8021x, // WpaNone, // WpaPsk, // WpaEap, // SAE // }; class KyWirelessConnectSetting : public KyConnectSetting { // Q_OBJECT public: QString m_ssid; bool isAutoConnect; QString m_psk; NetworkManager::Setting::SecretFlags m_secretFlag; KyKeyMgmt m_type; //only if m_type == WpaEap KyEapMethodType m_eapMethodType; }; class KyWirelessConnectOperation : public KyConnectOperation { Q_OBJECT public: explicit KyWirelessConnectOperation(QObject *parent = nullptr); ~KyWirelessConnectOperation(); //无线开关 void setWirelessEnabled(bool enabled); bool getWirelessEnabled(); //获取密码保存策略 bool getConnSecretFlags(QString &connUuid, NetworkManager::Setting::SecretFlags &); //获取KeyMgmt KyKeyMgmt getConnectKeyMgmt(const QString &uuid); //获取企业网类型 bool getEnterpiseEapMethod(const QString &uuid, KyEapMethodType &type); //激活连接 void activeWirelessConnect(QString , QString); //断开连接 void deActivateWirelessConnection(const QString activeConnectName, const QString &activeConnectUuid); //新增普通连接 void addConnect(const KyWirelessConnectSetting &connSettingInfo); //新增TLS连接 void addTlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTlsInfo &tlsinfo); //新增PEAP连接 void addPeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPeapInfo &peapInfo); //新增TTLS连接 void addTtlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTtlsInfo &ttlsInfo); //新增LEAP连接 void addLeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodLeapInfo &leapInfo); //新增PWD连接 void addPwdConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPwdInfo &pwdInfo); //新增FAST连接 void addFastConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodFastInfo &fastInfo); //新增连接并激活(普通wifi) void addAndActiveWirelessConnect(QString & devIface,KyWirelessConnectSetting &connSettingInfo,bool isHidden); //新增连接并激活(企业wifi) void addAndActiveWirelessEnterPriseTlsConnect(KyEapMethodTlsInfo &info, KyWirelessConnectSetting &connSettingInfo, QString & devIface, bool isHidden); void addAndActiveWirelessEnterPrisePeapConnect(KyEapMethodPeapInfo &info, KyWirelessConnectSetting &connSettingInfo, QString & devIface, bool isHidden); void addAndActiveWirelessEnterPriseTtlsConnect(KyEapMethodTtlsInfo &info, KyWirelessConnectSetting &connSettingInfo, QString & devIface, bool isHidden); void addAndActiveWirelessEnterPriseLeapConnect(KyEapMethodLeapInfo &info, KyWirelessConnectSetting &connSettingInfo, QString & devIface, bool isHidden); void addAndActiveWirelessEnterPrisePwdConnect(KyEapMethodPwdInfo &info, KyWirelessConnectSetting &connSettingInfo, QString & devIface, bool isHidden); void addAndActiveWirelessEnterPriseFastConnect(KyEapMethodFastInfo &info, KyWirelessConnectSetting &connSettingInfo, QString & devIface, bool isHidden); //属性页 page1 AutoConnect void setWirelessAutoConnect(const QString &uuid, bool bAutoConnect); //属性页 page2 page3 ipv6 void updateIpv4AndIpv6SettingInfo(const QString &uuid, const KyConnectSetting &connectSettingsInfo); //属性页 page4 wifi Security //连接修改(安全改为个人/None) void updateWirelessPersonalConnect(const QString &uuid, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange); //连接修改(安全改为改为企业) void updateWirelessEnterPriseTlsConnect(const QString &uuid, const KyEapMethodTlsInfo &tlsinfo); void updateWirelessEnterPrisePeapConnect(const QString &uuid, const KyEapMethodPeapInfo &peapInfo); void updateWirelessEnterPriseTtlsConnect(const QString &uuid, const KyEapMethodTtlsInfo &ttlsInfo); void updateWirelessEnterPriseLeapConnect(const QString &uuid, const KyEapMethodLeapInfo &leapInfo); void updateWirelessEnterPrisePwdConnect(const QString &uuid, const KyEapMethodPwdInfo &pwdInfo); void updateWirelessEnterPriseFastConnect(const QString &uuid, const KyEapMethodFastInfo &fastInfo); //忘记 void deleteWirelessConnect(const QString &connectUuid); //获取密码 QString getPsk(const QString &connectUuid); QString getPrivateKeyPassword(const QString &connectUuid); QString get8021xPassword(const QString &connectUuid); //申请扫描 void requestWirelessScan(); void activeWirelessAp(const QString apUuid, const QString apName, const QString apPassword, const QString apDevice, const QString wirelessBand); void deactiveWirelessAp(const QString apName, const QString apUuid); private: NetworkManager::ConnectionSettings::Ptr createWirelessApSetting(const QString apSsid, const QString apPassword, const QString apDevice, const QString wirelessBand); void updateWirelessApSetting(NetworkManager::Connection::Ptr apConnectPtr, const QString apName, const QString apPassword, const QString apDevice, const QString wirelessBand); QStringList getBlackListHostName(QString apConnectPath); Q_SIGNALS: void wifiEnabledChanged(bool); void enabledWirelessNetwork(bool enabled); void addAndActivateConnectionError(QString errorMessage); private: NetworkManager::WirelessNetwork::Ptr checkWifiNetExist(QString ssid, QString devName); void updateWirelessSecu(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange = false); void setIpv4AndIpv6Setting(NetworkManager::ConnectionSettings::Ptr connSetting, const KyConnectSetting &connSettingInfo); void setWirelessSecuWpaXEap(NetworkManager::ConnectionSettings::Ptr connSettingPtr); void activateApConnectionByUuid(const QString apUuid, const QString apDevice); }; #endif // KYWIRELESSCONNECTOPERATION_H kylin-nm/src/backend/dbus-interface/kywirelessnetitem.cpp0000664000175000017500000003275115167651420022621 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kywirelessnetitem.h" #include "kylinactiveconnectresource.h" #include #include "kylinutil.h" const QString ENTERPRICE_TYPE = "802.1X"; //const QString WPA1_AND_WPA2 = "WPA"; const QString WPA1 = "WPA1"; const QString WPA2 = "WPA2"; const QString WPA3 = "WPA3"; #define FREQ_5GHZ 5000 KyWirelessNetItem::KyWirelessNetItem(NetworkManager::WirelessNetwork::Ptr net) { m_networkResourceInstance = KyNetworkResourceManager::getInstance(); m_bssid = ""; m_connectUuid = ""; m_isConfigured = false; m_connName = ""; m_connDbusPath = ""; m_secuType = ""; m_kySecuType = KYLIN_NM::NONE; m_device = ""; m_channel = 0; m_isMix = false; init(net); } KyWirelessNetItem::~KyWirelessNetItem() { m_networkResourceInstance = nullptr; } void KyWirelessNetItem::init(NetworkManager::WirelessNetwork::Ptr net) { // m_NetSsid = net->ssid(); NetworkManager::AccessPoint::Ptr accessPointPtr = net->referenceAccessPoint(); if (accessPointPtr->ssid().isEmpty()) { qDebug() << accessPointPtr->uni() << "ssid isEmpty"; NetworkManager::AccessPoint::List list = net->accessPoints(); if (list.size() > 1) { for (int i = 0; i < list.size(); ++i) { if (!list.at(i)->ssid().isEmpty()) { qDebug() << "use" << accessPointPtr->uni(); accessPointPtr = list.at(i); break; } } } } if (accessPointPtr->ssid().isEmpty()) { return; } QByteArray rawSsid = accessPointPtr->rawSsid(); m_NetSsid = getSsidFromByteArray(rawSsid); m_signalStrength = accessPointPtr->signalStrength(); m_frequency = accessPointPtr->frequency(); m_channel = NetworkManager::findChannel(m_frequency); NetworkManager::AccessPoint::Capabilities cap = accessPointPtr->capabilities(); NetworkManager::AccessPoint::WpaFlags wpaFlag = accessPointPtr->wpaFlags(); NetworkManager::AccessPoint::WpaFlags rsnFlag = accessPointPtr->rsnFlags(); m_secuType = enumToQstring(cap, wpaFlag, rsnFlag); // if (m_secuType.indexOf(ENTERPRICE_TYPE) >= 0) { // m_kySecuType = WPA_AND_WPA2_ENTERPRISE; // } else if (m_secuType.indexOf(WPA3) >= 0) { // m_kySecuType = WPA3_PERSONAL; // } else if ( m_secuType.indexOf(WPA1_AND_WPA2) >= 0) { // m_kySecuType = WPA_AND_WPA2_PERSONAL; // } setKySecuType(m_secuType); m_bssid = accessPointPtr->hardwareAddress(); m_device = net->device(); m_uni = accessPointPtr->uni(); NetworkManager::Device::Ptr devicePtr = nullptr; devicePtr = m_networkResourceInstance->findDeviceInterface(m_device); if (!devicePtr.isNull()) { QString devUni = devicePtr->uni(); NetworkManager::WirelessNetwork::Ptr wirelessPtr = nullptr; wirelessPtr = m_networkResourceInstance->findWifiNetwork(m_NetSsid, devUni); if (!wirelessPtr.isNull()) { NetworkManager::AccessPoint::List apList = wirelessPtr->accessPoints(); bool b2G = false; bool b5G = false; if (!apList.empty()) { for (int i = 0; i < apList.count(); ++i) { if (apList.at(i)->frequency() < FREQ_5GHZ) { b2G = true; } if (apList.at(i)->frequency() >= FREQ_5GHZ) { b5G = true; } if (b2G && b5G) { m_isMix = true; break; } } } devicePtr = m_networkResourceInstance->findDeviceInterface(m_device); if (!devicePtr.isNull()) { QString devUni = devicePtr->uni(); NetworkManager::WirelessNetwork::Ptr wirelessPtr = nullptr; wirelessPtr = m_networkResourceInstance->findWifiNetwork(m_NetSsid, devUni); if (!wirelessPtr.isNull()) { NetworkManager::AccessPoint::List apList = wirelessPtr->accessPoints(); bool b2G = false; bool b5G = false; if (!apList.empty()) { for (int i = 0; i < apList.count(); ++i) { if (apList.at(i)->frequency() < FREQ_5GHZ) { b2G = true; } if (apList.at(i)->frequency() >= FREQ_5GHZ) { b5G = true; } if (b2G && b5G) { m_isMix = true; break; } } } } } } } updatewirelessItemConnectInfoEx(this); } int KyWirelessNetItem::getCategory(QString uni) { QDBusInterface interface( "org.freedesktop.NetworkManager", uni, "org.freedesktop.DBus.Properties", QDBusConnection::systemBus() ); if (!interface.isValid()) { qDebug() << Q_FUNC_INFO << "dbus is invalid"; return -1; } QDBusReply reply = interface.call("Get", "org.freedesktop.NetworkManager.AccessPoint", "Category"); if (!reply.isValid()) { //qDebug()<<"can not get the attribute 'Category' in func getCategory()"; return 0; } else { return reply.value().toInt(); } } void KyWirelessNetItem::setKySecuType(QString strSecuType) { if (strSecuType.indexOf(ENTERPRICE_TYPE) >= 0) { m_kySecuType = WPA_AND_WPA2_ENTERPRISE; } else if (strSecuType.indexOf(WPA3) >= 0) { if (strSecuType.indexOf(WPA1) >= 0 || strSecuType.indexOf(WPA2) >= 0) { m_kySecuType = WPA_AND_WPA3; } else { m_kySecuType = WPA3_PERSONAL; } } else if ( strSecuType.indexOf(WPA1) >= 0 || strSecuType.indexOf(WPA2) >= 0) { m_kySecuType = WPA_AND_WPA2_PERSONAL; } else { m_kySecuType = KYLIN_NM::NONE; } } bool updatewirelessItemConnectInfo(KyWirelessNetItem& item) { KyNetworkResourceManager *networkResourceInstance = KyNetworkResourceManager::getInstance(); bool findHotspot = false; bool findInfrastructure = false; KyWirelessNetItem hotspotItem; KyWirelessNetItem connectItem; for (auto const & conn : networkResourceInstance->m_connections) { NetworkManager::ConnectionSettings::Ptr settings = conn->settings(); if (settings->connectionType() != NetworkManager::ConnectionSettings::Wireless) { continue; } NetworkManager::WirelessSetting::Ptr wifi_sett = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); QString devName(""); NetworkManager::Device::Ptr devicePtr = networkResourceInstance->findDeviceUni(item.getDevice()); if (devicePtr != nullptr) { devName = devicePtr->interfaceName(); } QByteArray rawSsid = wifi_sett->ssid(); QString wifiSsid = getSsidFromByteArray(rawSsid); if (wifiSsid == item.m_NetSsid && (settings->interfaceName().compare(devName) == 0 || settings->interfaceName().isEmpty())) { /* * 如果有激活的链接,则取激活的链接,没有则取最后一个,因为一个热点可以创建多个链接, 有WIFI的则用WIFI,否则用adhoc */ KyActiveConnectResourse actResource; KyConnectItem * kyItem = actResource.getActiveConnectionByUuid(settings->uuid(), devName); if (nullptr != kyItem) { item.m_connectUuid = settings->uuid(); item.m_connName = conn->name(); item.m_connDbusPath = conn->path(); item.m_isConfigured = true; return (wifi_sett->mode() == NetworkManager::WirelessSetting::NetworkMode::Infrastructure); } if (wifi_sett->mode() != NetworkManager::WirelessSetting::NetworkMode::Infrastructure) { hotspotItem.m_connectUuid = settings->uuid(); hotspotItem.m_connName = conn->name(); hotspotItem.m_connDbusPath = conn->path(); hotspotItem.m_isConfigured = true; findHotspot = true; } else { connectItem.m_connectUuid = settings->uuid(); connectItem.m_connName = conn->name(); connectItem.m_connDbusPath = conn->path(); connectItem.m_isConfigured = true; findInfrastructure = true; } } } if (findInfrastructure) { item.m_connectUuid = connectItem.m_connectUuid; item.m_connName = connectItem.m_connName; item.m_connDbusPath = connectItem.m_connDbusPath; item.m_isConfigured = connectItem.m_isConfigured; return true; } else if (findHotspot) { item.m_connectUuid = hotspotItem.m_connectUuid; item.m_connName = hotspotItem.m_connName; item.m_connDbusPath = hotspotItem.m_connDbusPath; item.m_isConfigured = hotspotItem.m_isConfigured; } else { item.m_connectUuid.clear(); item.m_connName.clear(); item.m_connDbusPath.clear(); item.m_isConfigured = false; } return false; } void updatewirelessItemConnectInfoEx(KyWirelessNetItem* item) { KyNetworkResourceManager *networkResourceInstance = KyNetworkResourceManager::getInstance(); bool findHotspot = false; bool findInfrastructure = false; KyWirelessNetItem hotspotItem; KyWirelessNetItem connectItem; for (auto const & conn : networkResourceInstance->m_connections) { NetworkManager::ConnectionSettings::Ptr settings = conn->settings(); if (settings->connectionType() != NetworkManager::ConnectionSettings::Wireless) { continue; } NetworkManager::WirelessSetting::Ptr wifi_sett = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); QString devName = networkResourceInstance->findDeviceUni(item->getDevice())->interfaceName(); QByteArray rawSsid = wifi_sett->ssid(); QString wifiSsid = getSsidFromByteArray(rawSsid); if (wifiSsid == item->m_NetSsid && (settings->interfaceName().compare(devName) == 0 || settings->interfaceName().isEmpty())) { /* * 如果有激活的链接,则取激活的链接,没有则取最后一个,因为一个热点可以创建多个链接, 有WIFI的则用WIFI,否则用adhoc */ //qDebug()<<"mqtest updatewirelessItemConnectInfo uuid"<uuid()<name()<uuid(), devName); if (nullptr != kyItem) { item->m_connectUuid = settings->uuid(); item->m_connName = conn->name(); item->m_connDbusPath = conn->path(); item->m_isConfigured = true; //qDebug()<<"mqtest updatewirelessItemConnectInfo come in update"<m_connName<m_connectUuid;//mqtest return; } if (wifi_sett->mode() != NetworkManager::WirelessSetting::NetworkMode::Infrastructure) { hotspotItem.m_connectUuid = settings->uuid(); hotspotItem.m_connName = conn->name(); hotspotItem.m_connDbusPath = conn->path(); hotspotItem.m_isConfigured = true; findHotspot = true; } else { connectItem.m_connectUuid = settings->uuid(); connectItem.m_connName = conn->name(); connectItem.m_connDbusPath = conn->path(); connectItem.m_isConfigured = true; findInfrastructure = true; } } } //qDebug()<<"mqtest updatewirelessItemConnectInfo findInfrastructure"<m_connectUuid = connectItem.m_connectUuid; item->m_connName = connectItem.m_connName; item->m_connDbusPath = connectItem.m_connDbusPath; item->m_isConfigured = connectItem.m_isConfigured; } else if (findHotspot) { item->m_connectUuid = hotspotItem.m_connectUuid; item->m_connName = hotspotItem.m_connName; item->m_connDbusPath = hotspotItem.m_connDbusPath; item->m_isConfigured = hotspotItem.m_isConfigured; } else { item->m_connectUuid.clear(); item->m_connName.clear(); item->m_connDbusPath.clear(); item->m_isConfigured = false; } } kylin-nm/src/backend/dbus-interface/kylinnetworkdeviceresource.h0000664000175000017500000000734515167651420024170 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINNETORKDEVICERESOURCE_H #define KYLINNETORKDEVICERESOURCE_H #include #include "kylinnetworkresourcemanager.h" #include "kylinconnectitem.h" #include "kylinwiredconnectoperation.h" class KyNetworkDeviceResourse : public QObject { Q_OBJECT public: explicit KyNetworkDeviceResourse(QObject *parent = nullptr); ~KyNetworkDeviceResourse(); Q_SIGNALS: void deviceAdd(QString deviceName, NetworkManager::Device::Type deviceType); void deviceRemove(QString deviceName); void deviceUpdate(QString deviceName); void deviceNameUpdate(QString oldName, QString newName); void stateChange(QString deviceName, int state); void carrierChanage(QString deviceName, bool pluged); void deviceBitRateChanage(QString deviceName, int bitRate); void deviceMacAddressChanage(QString deviceName, const QString &hwAddress); void deviceActiveChanage(QString deviceName, bool deivceActive); void deviceManagedChange(QString deviceName, bool managed); void stateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason); void deviceConnectivityChanged(QString deviceName, const NetworkManager::Connectivity connectivity); public Q_SLOTS: void onDeviceAdd(QString deviceName, QString uni, NetworkManager::Device::Type deviceType); void onDeviceRemove(QString deviceName, QString uni); void onDeviceUpdate(QString interface, QString dbusPath); public: void getNetworkDeviceList(NetworkManager::Device::Type deviceType, QStringList &networkDeviceList); void getHardwareInfo(QString ifaceName, QString &hardAddress, int &bandWith); void getDeviceActiveAPInfo(const QString devName, QString &strMac, uint &iHz, uint &iChan, QString &secuType); int getWirelessDeviceCapability(const QString deviceName); NetworkManager::Device::State getDeviceState(QString deviceName); bool getActiveConnectionInfo(const QString devName, int &signalStrength, QString &uni, QString &secuType); bool wiredDeviceIsCarriered(QString deviceName); bool wirelessDeviceIsExist(const QString devName); bool checkDeviceType(QString deviceName, NetworkManager::Device::Type deviceType); void setDeviceRefreshRate(QString deviceName, int ms); void setDeviceManaged(QString devName, bool managed); bool getDeviceManaged(QString devName); qulonglong getDeviceRxRefreshRate(QString deviceName); qulonglong getDeviceTxRefreshRate(QString deviceName); void getDeviceConnectivity(const QString &deviceName, NetworkManager::Connectivity &connectivity); private: void initDeviceMap(); uint kyFindChannel(uint freq); private: KyWiredConnectOperation wiredOperation; KyNetworkResourceManager *m_networkResourceInstance = nullptr; QStringList m_activeConnectUuidList; QMap m_deviceMap; }; #endif // KYLINNETORKDEVICERESOURCE_H kylin-nm/src/backend/dbus-interface/kyenterpricesettinginfo.h0000664000175000017500000002016515167646234023460 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYENTERPRICESETTINGINFO_H #define KYENTERPRICESETTINGINFO_H #include #include #include "kylinnetworkresourcemanager.h" #include enum KyEapMethodType { TLS = 0, PEAP, TTLS, LEAP, PWD, FAST }; class KyEapMethodTlsInfo { public: QString identity; QString domain; QString devIfaceName; QString caCertPath; bool bNeedCa; QString clientCertPath; QString clientPrivateKey; QString clientPrivateKeyPWD; NetworkManager::Setting::SecretFlags m_privateKeyPWDFlag; // only valid when update bool bChanged; inline bool operator == (const KyEapMethodTlsInfo& info) const { if (this->identity == info.identity && this->domain == info.domain // && this->devIfaceName == info.devIfaceName && this->caCertPath == info.caCertPath && this->bNeedCa == info.bNeedCa && this->clientCertPath == info.clientCertPath && this->clientPrivateKey == info.clientPrivateKey && this->clientPrivateKeyPWD == info.clientPrivateKeyPWD && this->m_privateKeyPWDFlag == info.m_privateKeyPWDFlag) { return true; } else { return false; } } }; typedef enum { KyAuthEapMethodUnknown = 0, KyAuthEapMethodMd5, KyAuthEapMethodMschapv2, KyAuthEapMethodOtp, KyAuthEapMethodGtc, KyAuthEapMethodTls } KyEapMethodAuth; typedef enum{ KyAuthMethodUnknown = 0, KyAuthMethodPap, KyAuthMethodChap, KyAuthMethodMschap, KyAuthMethodMschapv2, KyAuthMethodGtc, KyAuthMethodOtp, KyAuthMethodMd5, KyAuthMethodTls } KyNoEapMethodAuth; class KyEapMethodPeapInfo { public: KyNoEapMethodAuth phase2AuthMethod; QString userName; QString userPWD; NetworkManager::Setting::SecretFlags m_passwdFlag; // only valid when update bool bChanged; inline bool operator == (const KyEapMethodPeapInfo& info) const { if (this->phase2AuthMethod == info.phase2AuthMethod && this->userName == info.userName && this->userPWD == info.userPWD && this->m_passwdFlag == info.m_passwdFlag) { return true; } else { return false; } } }; enum KyTtlsAuthMethod { AUTH_EAP, AUTH_NO_EAP }; class KyEapMethodTtlsInfo { public: KyTtlsAuthMethod authType; KyEapMethodAuth authEapMethod; KyNoEapMethodAuth authNoEapMethod; QString userName; QString userPWD; NetworkManager::Setting::SecretFlags m_passwdFlag; // only valid when update bool bChanged; inline bool operator == (const KyEapMethodTtlsInfo& info) const { if (this->authType == info.authType) { if (authType == AUTH_EAP) { if (this->authEapMethod == info.authEapMethod && this ->userName == info.userName && this->userPWD == info.userPWD && this->m_passwdFlag == info.m_passwdFlag) { return true; } } else { if (authType == AUTH_EAP) { if (this->authNoEapMethod == info.authNoEapMethod && this ->userName == info.userName && this->userPWD == info.userPWD && this->m_passwdFlag == info.m_passwdFlag) { return true; } } } } return false; } }; typedef enum { KyFastProvisioningUnknown = -1, KyFastProvisioningDisabled, KyFastProvisioningAllowUnauthenticated, KyFastProvisioningAllowAuthenticated, KyFastProvisioningAllowBoth }KyFastProvisioning; class KyEapMethodLeapInfo { public: QString m_userName; QString m_userPwd; NetworkManager::Setting::SecretFlags m_passwdFlag; // only valid when update bool bChanged; inline bool operator == (const KyEapMethodLeapInfo& info) const { if (this->m_userName == info.m_userName && this->m_userPwd == info.m_userPwd && this->m_passwdFlag == info.m_passwdFlag) { return true; } else { return false; } } }; class KyEapMethodPwdInfo { public: QString m_userName; QString m_userPwd; NetworkManager::Setting::SecretFlags m_passwdFlag; // only valid when update bool bChanged; inline bool operator == (const KyEapMethodPwdInfo& info) const { if (this->m_userName == info.m_userName && this->m_userPwd == info.m_userPwd && this->m_passwdFlag == info.m_passwdFlag) { return true; } else { return false; } } }; class KyEapMethodFastInfo { public: QString m_anonIdentity; KyFastProvisioning m_pacProvisioning; bool m_allowAutoPacFlag; QString m_pacFilePath; KyNoEapMethodAuth m_authMethod; QString m_userName; QString m_userPwd; NetworkManager::Setting::SecretFlags m_passwdFlag; // only valid when update bool bChanged; inline bool operator == (const KyEapMethodFastInfo& info) const { if (this->m_anonIdentity == info.m_anonIdentity && this->m_pacProvisioning == info.m_pacProvisioning && this->m_allowAutoPacFlag == info.m_allowAutoPacFlag && this->m_pacFilePath == info.m_pacFilePath && this->m_authMethod == info.m_authMethod && this->m_userName == info.m_userName && this->m_userPwd == info.m_userPwd && this->m_passwdFlag == info.m_passwdFlag) { return true; } else { return false; } } }; void assembleEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &tlsInfo); void assembleEapMethodPeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPeapInfo &peapInfo); void assembleEapMethodTtlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTtlsInfo &ttlsInfo); void assembleEapMethodLeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodLeapInfo &leapInfo); void assembleEapMethodPwdSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPwdInfo &pwdInfo); void assembleEapMethodFastSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodFastInfo &fastInfo); void modifyEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &tlsInfo); void modifyEapMethodPeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPeapInfo &peapInfo); void modifyEapMethodTtlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTtlsInfo &ttlsInfo); void modifyEapMethodLeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodLeapInfo &leapInfo); void modifyEapMethodPwdSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPwdInfo &pwdInfo); void modifyEapMethodFastSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodFastInfo &fastInfo); #endif // KYENTERPRICESETTINGINFO_H kylin-nm/src/backend/dbus-interface/kylinvpnrequest.c0000664000175000017500000006204715167651420021756 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinvpnrequest.h" #include #include #include #include #include #include #include #include "gsystem-local-alloc.h" #include "nma-vpn-password-dialog.h" #include "nm-macros-internal.h" extern char **environ; /*****************************************************************************/ typedef struct { char *name; char *label; char *value; gboolean is_secret; gboolean should_ask; } EuiSecret; typedef struct { char *uuid; char *id; char *service_type; guint watch_id; GPid pid; int child_stdout; GString *child_response; GIOChannel *channel; guint channel_eventid; GVariantBuilder secrets_builder; gboolean external_ui_mode; /* These are just for the external UI mode */ EuiSecret *eui_secrets; } RequestData; typedef struct { SecretsRequest req; RequestData *req_data; } VpnSecretsInfo; gint _nm_utils_ascii_str_to_bool (const char *str, gint default_value) { gsize len; char *s = NULL; if (!str) return default_value; while (str[0] && g_ascii_isspace (str[0])) str++; if (!str[0]) return default_value; len = strnlen (str, sizeof(str)); if (g_ascii_isspace (str[len - 1])) { s = g_strdup (str); g_strchomp (s); str = s; } if (!g_ascii_strcasecmp (str, "true") || !g_ascii_strcasecmp (str, "yes") || !g_ascii_strcasecmp (str, "on") || !g_ascii_strcasecmp (str, "1")) default_value = TRUE; else if (!g_ascii_strcasecmp (str, "false") || !g_ascii_strcasecmp (str, "no") || !g_ascii_strcasecmp (str, "off") || !g_ascii_strcasecmp (str, "0")) default_value = FALSE; if (s) g_free (s); return default_value; } /*****************************************************************************/ static void request_data_free (RequestData *req_data); static void complete_request (VpnSecretsInfo *info); /*****************************************************************************/ size_t applet_vpn_request_get_secrets_size (void) { return sizeof (VpnSecretsInfo); } /*****************************************************************************/ static void external_ui_add_secrets (VpnSecretsInfo *info) { RequestData *req_data = info->req_data; EuiSecret *secret; guint i; for (i = 0; req_data->eui_secrets[i].name; i++) { secret = &req_data->eui_secrets[i]; if ( secret->is_secret && secret->value && secret->value[0]) { g_variant_builder_add (&req_data->secrets_builder, "{ss}", secret->name, secret->value); } } } static void external_ui_dialog_response (GtkDialog *dialog, int response_id, gpointer user_data) { VpnSecretsInfo *info = user_data; RequestData *req_data = info->req_data; NMAVpnPasswordDialog *vpn_dialog = NMA_VPN_PASSWORD_DIALOG (dialog); EuiSecret *secret; const char *value; guint i_secret, i_pw; for (i_secret = 0, i_pw = 0; req_data->eui_secrets[i_secret].name; i_secret++) { secret = &req_data->eui_secrets[i_secret]; if ( secret->is_secret && secret->should_ask) { switch (i_pw) { case 0: value = nma_vpn_password_dialog_get_password (vpn_dialog); break; case 1: value = nma_vpn_password_dialog_get_password_secondary (vpn_dialog); break; case 2: value = nma_vpn_password_dialog_get_password_ternary (vpn_dialog); break; default: continue; } g_free (secret->value); secret->value = g_strdup (value); i_pw++; } } gtk_widget_destroy (GTK_WIDGET (dialog)); external_ui_add_secrets (info); complete_request (info); } static gboolean external_ui_from_child_response (VpnSecretsInfo *info, GError **error) { RequestData *req_data = info->req_data; gs_unref_keyfile GKeyFile *keyfile = NULL; gs_strfreev char **groups = NULL; NMAVpnPasswordDialog *dialog = NULL; gs_free char *version = NULL; gs_free char *title = NULL; gs_free char *message = NULL; gsize num_groups; guint num_ask = 0; guint i_group, i_secret, i_pw; /* Parse response key file */ keyfile = g_key_file_new (); if (!g_key_file_load_from_data (keyfile, req_data->child_response->str, req_data->child_response->len, G_KEY_FILE_NONE, error)) { return FALSE; } groups = g_key_file_get_groups (keyfile, &num_groups); if (g_strcmp0 (groups[0], "VPN Plugin UI") != 0) { g_set_error_literal (error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, "Expected [VPN Plugin UI]"); return FALSE; } version = g_key_file_get_string (keyfile, "VPN Plugin UI", "Version", error); if (!version) return FALSE; if (strcmp (version, "2") != 0) { g_set_error_literal (error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, "Expected Version=2"); return FALSE; } title = g_key_file_get_string (keyfile, "VPN Plugin UI", "Title", error); if (!title) return FALSE; message = g_key_file_get_string (keyfile, "VPN Plugin UI", "Description", error); if (!message) return FALSE; /* Create a secret instance for each group */ req_data->eui_secrets = g_new0 (EuiSecret, num_groups); for (i_group = 1, i_secret = 0; i_group < num_groups; i_group++) { EuiSecret *secret = &req_data->eui_secrets[i_secret]; const char *group = groups[i_group]; char *label; label = g_key_file_get_string (keyfile, group, "Label", NULL); if (!label) { g_warning ("Skipping entry: no label\n"); continue; } secret->name = g_strdup (group); secret->label = label; secret->value = g_key_file_get_string (keyfile, group, "Value", NULL); secret->is_secret = g_key_file_get_boolean (keyfile, group, "IsSecret", NULL); secret->should_ask = g_key_file_get_boolean (keyfile, group, "ShouldAsk", NULL); i_secret++; if (secret->is_secret && secret->should_ask) num_ask++; } /* If there are any secrets that must be asked to user, * create a dialog and display it. */ if (num_ask > 0) { /* In external UI mode, avoid spawning GTK dialog inside Qt app to prevent crashes. * Defer to upper layer to collect secrets or cancel gracefully. */ if (req_data->external_ui_mode) { g_set_error_literal (error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_USER_CANCELED, "External UI mode enabled: skip GTK password dialog"); return FALSE; } dialog = (NMAVpnPasswordDialog *) nma_vpn_password_dialog_new (title, message, NULL); g_object_ref_sink (dialog); nma_vpn_password_dialog_set_show_password (dialog, FALSE); nma_vpn_password_dialog_set_show_password_secondary (dialog, FALSE); nma_vpn_password_dialog_set_show_password_ternary (dialog, FALSE); for (i_secret = 0, i_pw = 0; req_data->eui_secrets[i_secret].name; i_secret++) { EuiSecret *secret = &req_data->eui_secrets[i_secret]; if ( secret->is_secret && secret->should_ask) { switch (i_pw) { case 0: nma_vpn_password_dialog_set_show_password (dialog, TRUE); nma_vpn_password_dialog_set_password_label (dialog, secret->label); if (secret->value) nma_vpn_password_dialog_set_password (dialog, secret->value); break; case 1: nma_vpn_password_dialog_set_show_password_secondary (dialog, TRUE); nma_vpn_password_dialog_set_password_secondary_label (dialog, secret->label); if (secret->value) nma_vpn_password_dialog_set_password_secondary (dialog, secret->value); break; case 2: nma_vpn_password_dialog_set_show_password_ternary (dialog, TRUE); nma_vpn_password_dialog_set_password_ternary_label (dialog, secret->label); if (secret->value) nma_vpn_password_dialog_set_password_ternary (dialog, secret->value); break; default: g_warning ("Skipping entry: more than 3 passwords not supported\n"); continue; } i_pw++; } } g_signal_connect (dialog, "response", G_CALLBACK (external_ui_dialog_response), info); gtk_widget_show (GTK_WIDGET (dialog)); return TRUE; } /* Nothing to ask, return known secrets */ external_ui_add_secrets (info); complete_request (info); return TRUE; } /*****************************************************************************/ static void complete_request (VpnSecretsInfo *info) { SecretsRequest *req = (SecretsRequest *) info; RequestData *req_data = info->req_data; GVariantBuilder settings_builder, vpn_builder; gs_unref_variant GVariant *settings = NULL; g_variant_builder_init (&settings_builder, NM_VARIANT_TYPE_CONNECTION); g_variant_builder_init (&vpn_builder, NM_VARIANT_TYPE_SETTING); g_variant_builder_add (&vpn_builder, "{sv}", NM_SETTING_VPN_SECRETS, g_variant_builder_end (&req_data->secrets_builder)); g_variant_builder_add (&settings_builder, "{sa{sv}}", NM_SETTING_VPN_SETTING_NAME, &vpn_builder); settings = g_variant_builder_end (&settings_builder); applet_secrets_request_complete (req, settings, NULL); applet_secrets_request_free (req); } static void process_child_response (VpnSecretsInfo *info) { SecretsRequest *req = (SecretsRequest *) info; RequestData *req_data = info->req_data; gs_free_error GError *error = NULL; if (req_data->external_ui_mode) { if (!external_ui_from_child_response (info, &error)) { applet_secrets_request_complete (req, NULL, error); applet_secrets_request_free (req); } } else { char **lines = g_strsplit (req_data->child_response->str, "\n", -1); int i; for (i = 0; lines[i] && *(lines[i]); i += 2) { if (lines[i + 1] == NULL) break; g_variant_builder_add (&req_data->secrets_builder, "{ss}", lines[i], lines[i + 1]); } g_strfreev (lines); complete_request (info); } } static void child_finished_cb (GPid pid, int status, gpointer user_data) { VpnSecretsInfo *info = user_data; SecretsRequest *req = (SecretsRequest *) info; RequestData *req_data = info->req_data; gs_free_error GError *error = NULL; req_data->pid = 0; req_data->watch_id = 0; if (status) { error = g_error_new (NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_USER_CANCELED, "%s.%d (%s): canceled", __FILE__, __LINE__, __func__); applet_secrets_request_complete (req, NULL, error); applet_secrets_request_free (req); } else if (req_data->channel_eventid == 0) { /* We now have both the child response and its exit status. Process it. */ process_child_response (info); } } static gboolean child_stdout_data_cb (GIOChannel *source, GIOCondition condition, gpointer user_data) { SecretsRequest *req = user_data; VpnSecretsInfo *info = (VpnSecretsInfo *) req; RequestData *req_data = info->req_data; GIOStatus status; char buf[4096]; size_t bytes_read; gs_free_error GError *error = NULL; status = g_io_channel_read_chars (source, buf, sizeof (buf)-1, &bytes_read, &error); switch (status) { case G_IO_STATUS_ERROR: req_data->channel_eventid = 0; applet_secrets_request_complete (req, NULL, error); applet_secrets_request_free (req); return FALSE; case G_IO_STATUS_EOF: req_data->channel_eventid = 0; if (req_data->pid == 0) { /* We now have both the childe respons and * its exit status. Process it. */ process_child_response (info); } return FALSE; case G_IO_STATUS_NORMAL: g_string_append_len (req_data->child_response, buf, bytes_read); break; default: /* What just happened... */ g_return_val_if_reached (FALSE); } return TRUE; } /*****************************************************************************/ static void _str_append (GString *str, const char *tag, const char *val) { const char *s; gsize i; nm_assert (str); nm_assert (tag && tag[0]); nm_assert (val); g_string_append (str, tag); g_string_append_c (str, '='); s = strchr (val, '\n'); if (s) { gs_free char *val2 = g_strdup (val); for (i = 0; val2[i]; i++) { if (val2[i] == '\n') val2[i] = ' '; } g_string_append (str, val2); } else g_string_append (str, val); g_string_append_c (str, '\n'); } static char * connection_to_data (NMConnection *connection, gsize *out_length, GError **error) { NMSettingVpn *s_vpn; GString *buf; const char **keys; guint i, len; g_return_val_if_fail (NM_IS_CONNECTION (connection), NULL); s_vpn = nm_connection_get_setting_vpn (connection); if (!s_vpn) { g_set_error_literal (error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, ("Connection had no VPN setting")); return NULL; } buf = g_string_new_len (NULL, 100); keys = nm_setting_vpn_get_data_keys (s_vpn, &len); for (i = 0; i < len; i++) { _str_append (buf, "DATA_KEY", keys[i]); _str_append (buf, "DATA_VAL", nm_setting_vpn_get_data_item (s_vpn, keys[i])); } nm_clear_g_free (&keys); keys = nm_setting_vpn_get_secret_keys (s_vpn, &len); for (i = 0; i < len; i++) { _str_append (buf, "SECRET_KEY", keys[i]); _str_append (buf, "SECRET_VAL", nm_setting_vpn_get_secret (s_vpn, keys[i])); } nm_clear_g_free (&keys); g_string_append (buf, "DONE\n\nQUIT\n\n"); NM_SET_OUT (out_length, buf->len); return g_string_free (buf, FALSE); } /*****************************************************************************/ static gboolean connection_to_fd (NMConnection *connection, int fd, GError **error) { gs_free char *data = NULL; gsize data_len; gssize w; int errsv; data = connection_to_data (connection, &data_len, error); if (!data) return FALSE; again: w = write (fd, data, data_len); if (w < 0) { errsv = errno; if (errsv == EINTR) goto again; g_set_error (error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, ("Failed to write connection to VPN UI: %s (%d)"), g_strerror (errsv), errsv); return FALSE; } if ((gsize) w != data_len) { g_set_error_literal (error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, ("Failed to write connection to VPN UI: incomplete write")); return FALSE; } return TRUE; } /*****************************************************************************/ static void vpn_child_setup (gpointer user_data) { /* We are in the child process at this point */ pid_t pid = getpid (); setpgid (pid, pid); } static gboolean auth_dialog_spawn (const char *con_id, const char *con_uuid, const char *const*hints, const char *auth_dialog, const char *service_type, gboolean supports_hints, gboolean external_ui_mode, guint32 flags, GPid *out_pid, int *out_stdin, int *out_stdout, GError **error) { gsize hints_len; gsize i, j; gs_free const char **argv = NULL; gs_free const char **envp = NULL; gsize environ_len; g_return_val_if_fail (con_id, FALSE); g_return_val_if_fail (con_uuid, FALSE); g_return_val_if_fail (auth_dialog, FALSE); g_return_val_if_fail (service_type, FALSE); g_return_val_if_fail (out_pid, FALSE); g_return_val_if_fail (out_stdin, FALSE); g_return_val_if_fail (out_stdout, FALSE); hints_len = NM_PTRARRAY_LEN (hints); argv = g_new (const char *, 11 + (2 * hints_len)); i = 0; argv[i++] = auth_dialog; argv[i++] = "-u"; argv[i++] = con_uuid; argv[i++] = "-n"; argv[i++] = con_id; argv[i++] = "-s"; argv[i++] = service_type; if (flags & NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION) argv[i++] = "-i"; if (flags & NM_SECRET_AGENT_GET_SECRETS_FLAG_REQUEST_NEW) argv[i++] = "-r"; for (j = 0; supports_hints && (j < hints_len); j++) { argv[i++] = "-t"; argv[i++] = hints[j]; } if (external_ui_mode) argv[i++] = "--external-ui-mode"; nm_assert (i <= 10 + (2 * hints_len)); argv[i++] = NULL; environ_len = NM_PTRARRAY_LEN (environ); envp = g_new (const char *, environ_len + 1); memcpy (envp, environ, sizeof (const char *) * environ_len); for (i = 0, j = 0; i < environ_len; i++) { const char *e = environ[i]; if (g_str_has_prefix (e, "G_MESSAGES_DEBUG=")) { /* skip this environment variable. We interact with the auth-dialog via stdout. * G_MESSAGES_DEBUG may enable additional debugging messages from GTK. */ continue; } envp[j++] = e; } envp[j] = NULL; if (!g_spawn_async_with_pipes (NULL, (char **) argv, (char **) envp, G_SPAWN_DO_NOT_REAP_CHILD, vpn_child_setup, NULL, out_pid, out_stdin, out_stdout, NULL, error)) return FALSE; return TRUE; } /*****************************************************************************/ static void free_vpn_secrets_info (SecretsRequest *req) { request_data_free (((VpnSecretsInfo *) req)->req_data); } gboolean applet_vpn_request_get_secrets (SecretsRequest *req, GError **error) { VpnSecretsInfo *info = (VpnSecretsInfo *) req; RequestData *req_data; NMSettingConnection *s_con; NMSettingVpn *s_vpn; const char *connection_type; const char *service_type; const char *auth_dialog; gs_unref_object NMVpnPluginInfo *plugin = NULL; int child_stdin; applet_secrets_request_set_free_func (req, free_vpn_secrets_info); s_con = nm_connection_get_setting_connection (req->connection); s_vpn = nm_connection_get_setting_vpn (req->connection); connection_type = nm_setting_connection_get_connection_type (s_con); g_return_val_if_fail (nm_streq0 (connection_type, NM_SETTING_VPN_SETTING_NAME), FALSE); service_type = nm_setting_vpn_get_service_type (s_vpn); g_return_val_if_fail (service_type, FALSE); plugin = nm_vpn_plugin_info_new_search_file (NULL, service_type); auth_dialog = plugin ? nm_vpn_plugin_info_get_auth_dialog (plugin) : NULL; if (!auth_dialog) { g_set_error (error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, "Could not find the authentication dialog for VPN connection type '%s'", service_type); return FALSE; } info->req_data = g_slice_new0 (RequestData); if (!info->req_data) { g_set_error_literal (error, NM_SECRET_AGENT_ERROR, NM_SECRET_AGENT_ERROR_FAILED, "Could not create VPN secrets request object"); return FALSE; } req_data = info->req_data; g_variant_builder_init (&req_data->secrets_builder, G_VARIANT_TYPE ("a{ss}")); req_data->external_ui_mode = _nm_utils_ascii_str_to_bool ( nm_vpn_plugin_info_lookup_property (plugin, "GNOME", "supports-external-ui-mode"), FALSE); if (!auth_dialog_spawn (nm_setting_connection_get_id (s_con), nm_setting_connection_get_uuid (s_con), (const char *const*) req->hints, auth_dialog, service_type, nm_vpn_plugin_info_supports_hints (plugin), req_data->external_ui_mode, req->flags, &req_data->pid, &child_stdin, &req_data->child_stdout, error)) return FALSE; /* catch when child is reaped */ req_data->watch_id = g_child_watch_add (req_data->pid, child_finished_cb, info); /* listen to what child has to say */ req_data->channel = g_io_channel_unix_new (req_data->child_stdout); req_data->child_response = g_string_sized_new (4096); req_data->channel_eventid = g_io_add_watch (req_data->channel, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL, child_stdout_data_cb, info); if (!connection_to_fd (req->connection, child_stdin, error)) return FALSE; close (child_stdin); g_io_channel_set_encoding (req_data->channel, NULL, NULL); /* Dump parts of the connection to the child */ return TRUE; } /*****************************************************************************/ static gboolean ensure_killed (gpointer data) { pid_t pid = GPOINTER_TO_INT (data); if (kill (pid, 0) == 0) kill (pid, SIGKILL); /* ensure the child is reaped */ waitpid (pid, NULL, 0); return FALSE; } static void request_data_free (RequestData *req_data) { guint i; if (!req_data) return; g_free (req_data->uuid); g_free (req_data->id); g_free (req_data->service_type); nm_clear_g_source (&req_data->watch_id); nm_clear_g_source (&req_data->channel_eventid); if (req_data->channel) g_io_channel_unref (req_data->channel); if (req_data->pid) { g_spawn_close_pid (req_data->pid); if (kill (req_data->pid, SIGTERM) == 0) g_timeout_add_seconds (2, ensure_killed, GINT_TO_POINTER (req_data->pid)); else { kill (req_data->pid, SIGKILL); /* ensure the child is reaped */ waitpid (req_data->pid, NULL, 0); } } if (req_data->child_response) g_string_free (req_data->child_response, TRUE); g_variant_builder_clear (&req_data->secrets_builder); if (req_data->eui_secrets) { for (i = 0; req_data->eui_secrets[i].name; i++) { g_free (req_data->eui_secrets[i].name); g_free (req_data->eui_secrets[i].label); g_free (req_data->eui_secrets[i].value); } g_free (req_data->eui_secrets); } g_slice_free (RequestData, req_data); } kylin-nm/src/backend/dbus-interface/gsystem-local-alloc.h0000664000175000017500000001403515167646234022354 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef __GSYSTEM_LOCAL_ALLOC_H__ #define __GSYSTEM_LOCAL_ALLOC_H__ #include G_BEGIN_DECLS #define GS_DEFINE_CLEANUP_FUNCTION(Type, name, func) \ static inline void name (void *v) \ { \ func (*(Type*)v); \ } #define GS_DEFINE_CLEANUP_FUNCTION0(Type, name, func) \ static inline void name (void *v) \ { \ if (*(Type*)v) \ func (*(Type*)v); \ } /* These functions shouldn't be invoked directly; * they are stubs that: * 1) Take a pointer to the location (typically itself a pointer). * 2) Provide %NULL-safety where it doesn't exist already (e.g. g_object_unref) */ /** * gs_free: * * Call g_free() on a variable location when it goes out of scope. */ #define gs_free __attribute__ ((cleanup(gs_local_free))) GS_DEFINE_CLEANUP_FUNCTION(void*, gs_local_free, g_free) /** * gs_unref_object: * * Call g_object_unref() on a variable location when it goes out of * scope. Note that unlike g_object_unref(), the variable may be * %NULL. */ #define gs_unref_object __attribute__ ((cleanup(gs_local_obj_unref))) GS_DEFINE_CLEANUP_FUNCTION0(GObject*, gs_local_obj_unref, g_object_unref) /** * gs_unref_variant: * * Call g_variant_unref() on a variable location when it goes out of * scope. Note that unlike g_variant_unref(), the variable may be * %NULL. */ #define gs_unref_variant __attribute__ ((cleanup(gs_local_variant_unref))) GS_DEFINE_CLEANUP_FUNCTION0(GVariant*, gs_local_variant_unref, g_variant_unref) /** * gs_free_variant_iter: * * Call g_variant_iter_free() on a variable location when it goes out of * scope. */ #define gs_free_variant_iter __attribute__ ((cleanup(gs_local_variant_iter_free))) GS_DEFINE_CLEANUP_FUNCTION0(GVariantIter*, gs_local_variant_iter_free, g_variant_iter_free) /** * gs_free_variant_builder: * * Call g_variant_builder_unref() on a variable location when it goes out of * scope. */ #define gs_unref_variant_builder __attribute__ ((cleanup(gs_local_variant_builder_unref))) GS_DEFINE_CLEANUP_FUNCTION0(GVariantBuilder*, gs_local_variant_builder_unref, g_variant_builder_unref) /** * gs_unref_array: * * Call g_array_unref() on a variable location when it goes out of * scope. Note that unlike g_array_unref(), the variable may be * %NULL. */ #define gs_unref_array __attribute__ ((cleanup(gs_local_array_unref))) GS_DEFINE_CLEANUP_FUNCTION0(GArray*, gs_local_array_unref, g_array_unref) /** * gs_unref_ptrarray: * * Call g_ptr_array_unref() on a variable location when it goes out of * scope. Note that unlike g_ptr_array_unref(), the variable may be * %NULL. */ #define gs_unref_ptrarray __attribute__ ((cleanup(gs_local_ptrarray_unref))) GS_DEFINE_CLEANUP_FUNCTION0(GPtrArray*, gs_local_ptrarray_unref, g_ptr_array_unref) /** * gs_unref_hashtable: * * Call g_hash_table_unref() on a variable location when it goes out * of scope. Note that unlike g_hash_table_unref(), the variable may * be %NULL. */ #define gs_unref_hashtable __attribute__ ((cleanup(gs_local_hashtable_unref))) GS_DEFINE_CLEANUP_FUNCTION0(GHashTable*, gs_local_hashtable_unref, g_hash_table_unref) /** * gs_free_list: * * Call g_list_free() on a variable location when it goes out * of scope. */ #define gs_free_list __attribute__ ((cleanup(gs_local_free_list))) GS_DEFINE_CLEANUP_FUNCTION(GList*, gs_local_free_list, g_list_free) /** * gs_free_slist: * * Call g_slist_free() on a variable location when it goes out * of scope. */ #define gs_free_slist __attribute__ ((cleanup(gs_local_free_slist))) GS_DEFINE_CLEANUP_FUNCTION(GSList*, gs_local_free_slist, g_slist_free) /** * gs_free_checksum: * * Call g_checksum_free() on a variable location when it goes out * of scope. Note that unlike g_checksum_free(), the variable may * be %NULL. */ #define gs_free_checksum __attribute__ ((cleanup(gs_local_checksum_free))) GS_DEFINE_CLEANUP_FUNCTION0(GChecksum*, gs_local_checksum_free, g_checksum_free) /** * gs_unref_bytes: * * Call g_bytes_unref() on a variable location when it goes out * of scope. Note that unlike g_bytes_unref(), the variable may * be %NULL. */ #define gs_unref_bytes __attribute__ ((cleanup(gs_local_bytes_unref))) GS_DEFINE_CLEANUP_FUNCTION0(GBytes*, gs_local_bytes_unref, g_bytes_unref) /** * gs_strfreev: * * Call g_strfreev() on a variable location when it goes out of scope. */ #define gs_strfreev __attribute__ ((cleanup(gs_local_strfreev))) GS_DEFINE_CLEANUP_FUNCTION(char**, gs_local_strfreev, g_strfreev) /** * gs_free_error: * * Call g_error_free() on a variable location when it goes out of scope. */ #define gs_free_error __attribute__ ((cleanup(gs_local_free_error))) GS_DEFINE_CLEANUP_FUNCTION0(GError*, gs_local_free_error, g_error_free) /** * gs_unref_keyfile: * * Call g_key_file_unref() on a variable location when it goes out of scope. */ #define gs_unref_keyfile __attribute__ ((cleanup(gs_local_keyfile_unref))) GS_DEFINE_CLEANUP_FUNCTION0(GKeyFile*, gs_local_keyfile_unref, g_key_file_unref) static inline void gs_cleanup_close_fdp (int *fdp) { int fd; g_assert (fdp); fd = *fdp; if (fd != -1) (void) close (fd); } /** * gs_fd_close: * * Call close() on a variable location when it goes out of scope. */ #define gs_fd_close __attribute__((cleanup(gs_cleanup_close_fdp))) G_END_DECLS #endif kylin-nm/src/backend/dbus-interface/kywirelessnetresource.cpp0000664000175000017500000010552415167651420023511 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kywirelessnetresource.h" #include "kylinutil.h" #define LOG_FLAG "[KyWirelessNetResource]" const QString ENTERPRICE_TYPE = "802.1X"; const QString WPA1_AND_WPA2 = "WPA"; const QString WPA3 = "WPA3"; static bool subWifiListSort(const KyWirelessNetItem info1, const KyWirelessNetItem info2) { if (info1.m_isConfigured == info2.m_isConfigured) { if (info1.m_signalStrength != info2.m_signalStrength) { return info1.m_signalStrength > info2.m_signalStrength; } else { if (QString::compare(info1.m_NetSsid, info2.m_NetSsid, Qt::CaseInsensitive) > 0) { return false; } else { return true; } } } return info1.m_isConfigured; } static void wifiListSort(QList &list) { std::sort(list.begin(), list.end(), subWifiListSort); } KyWirelessNetResource::KyWirelessNetResource(QObject *parent) : QObject(parent) { qDebug()<< LOG_FLAG <<"KyWirelessNetResource"; qRegisterMetaType("KyWirelessNetItem&"); m_networkResourceInstance = KyNetworkResourceManager::getInstance(); m_operation = new KyWirelessConnectOperation(this); m_networkDevice = new KyNetworkDeviceResourse(this); kyWirelessNetItemListInit(); //TODO:connect device signal connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkAdded, this, &KyWirelessNetResource::onWifiNetworkAdded/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkRemoved, this, &KyWirelessNetResource::onWifiNetworkRemoved/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkPropertyChange, this, &KyWirelessNetResource::onWifiNetworkPropertyChange/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkSecuChange, this, &KyWirelessNetResource::onWifiNetworkSecuChange/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkDeviceDisappear, this, &KyWirelessNetResource::onWifiNetworkDeviceDisappear/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::connectionAdd, this, &KyWirelessNetResource::onConnectionAdd); connect(m_networkResourceInstance, &KyNetworkResourceManager::connectionRemove, this, &KyWirelessNetResource::onConnectionRemove); connect(m_networkResourceInstance, &KyNetworkResourceManager::connectionUpdate, this, &KyWirelessNetResource::onConnectionUpdate); connect(m_networkDevice, &KyNetworkDeviceResourse::deviceAdd, this, &KyWirelessNetResource::onDeviceAdd); connect(m_networkDevice, &KyNetworkDeviceResourse::deviceRemove, this, &KyWirelessNetResource::onDeviceRemove); connect(m_networkDevice, &KyNetworkDeviceResourse::deviceNameUpdate, this, &KyWirelessNetResource::onDeviceNameUpdate); } KyWirelessNetResource::~KyWirelessNetResource() { m_networkResourceInstance = nullptr; } bool KyWirelessNetResource::getAllDeviceWifiNetwork(QMap> &map) { // onWifiNetworkDeviceDisappear(); if (m_WifiNetworkList.isEmpty()) { return false; } else { QMap >::iterator iter = m_WifiNetworkList.begin(); while (iter != m_WifiNetworkList.end()) { wifiListSort(m_WifiNetworkList[iter.key()]); iter++; } map = m_WifiNetworkList; return true; } } bool KyWirelessNetResource::getDeviceWifiNetwork(QString devIfaceName, QList &wirelessNetResource) { if (!m_WifiNetworkList.contains(devIfaceName)) { return false; } else { wifiListSort(m_WifiNetworkList[devIfaceName]); wirelessNetResource = m_WifiNetworkList[devIfaceName]; return true; } } bool KyWirelessNetResource::getWifiNetwork(const QString &devIfaceName, const QString &ssid, KyWirelessNetItem &wirelessNetResource) { if (!m_WifiNetworkList.contains(devIfaceName)) { qDebug()<< LOG_FLAG << "getWifiNetwork fail, not contain " << devIfaceName; return false; } else { for (int index = 0; index < m_WifiNetworkList[devIfaceName].size(); index++){ if (m_WifiNetworkList[devIfaceName].at(index).m_NetSsid == ssid) { wirelessNetResource = m_WifiNetworkList[devIfaceName].at(index); qDebug()<< LOG_FLAG << "getWifiNetwork success"; return true; } } } qDebug()<< LOG_FLAG << "getWifiNetwork fail, not contain " << ssid; return false; } void KyWirelessNetResource::getWirelessActiveConnection(NetworkManager::ActiveConnection::State state, QMap &map) { int index = 0; map.clear(); NetworkManager::ActiveConnection::List activeConnectionList; activeConnectionList.clear(); activeConnectionList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectionList.isEmpty()) { return; } NetworkManager::ActiveConnection::Ptr activeConnectionPtr = nullptr; for (; index < activeConnectionList.size(); index++) { activeConnectionPtr = activeConnectionList.at(index); if (activeConnectionPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::ConnectionType::Wireless != activeConnectionPtr->type()) { continue; } if (state != activeConnectionPtr->state()) { continue; } qDebug()<< LOG_FLAG << "getWirelessActiveConnection " << activeConnectionPtr->uuid(); QString ssid; QString ifaceName = getDeviceIFace(activeConnectionPtr, ssid); if(ifaceName.isEmpty() || ssid.isNull()) { continue; } if (map.contains(ifaceName)) { map[ifaceName].append(activeConnectionPtr->uuid()); } else { QStringList list; list.append(activeConnectionPtr->uuid()); map.insert(ifaceName,list); } } return; } QString KyWirelessNetResource::getActiveConnectSsidByDevice(QString deviceName) { QString ssid = ""; NetworkManager::ActiveConnection::List activeConnectionList; activeConnectionList.clear(); activeConnectionList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectionList.isEmpty()) { return ssid; } NetworkManager::ActiveConnection::Ptr activeConnectionPtr = nullptr; for (int index = 0; index < activeConnectionList.size(); index++) { activeConnectionPtr = activeConnectionList.at(index); if (activeConnectionPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::ConnectionType::Wireless != activeConnectionPtr->type()) { continue; } if (NetworkManager::ActiveConnection::State::Activated != activeConnectionPtr->state()) { continue; } QStringList interfaces = activeConnectionPtr->devices(); if(interfaces.isEmpty()) { qWarning()<< LOG_FLAG <<"get active device failed."; continue; } QString ifaceUni = interfaces.at(0); NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceUni(ifaceUni); if (deviceName.isNull()) { continue; } if (deviceName != devicePtr->interfaceName()) { continue; } NetworkManager::Connection::Ptr connectPtr = activeConnectionPtr->connection(); NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); NetworkManager::WirelessSetting::Ptr wirelessSettingPtr = settingPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); QByteArray rawSsid = wirelessSettingPtr->ssid(); ssid = getSsidFromByteArray(rawSsid); break; } return ssid; } bool KyWirelessNetResource::getActiveWirelessNetItem(QString deviceName, KyWirelessNetItem &wirelessNetItem) { if (!m_WifiNetworkList.contains(deviceName)) { qDebug() << "getWifiNetwork fail,not contain " << deviceName; return false; } QString ssid = getActiveConnectSsidByDevice(deviceName); if (ssid.isEmpty()) { return false; } for (int index = 0; index < m_WifiNetworkList[deviceName].size(); index ++) { if (m_WifiNetworkList[deviceName].at(index).m_NetSsid == ssid) { wirelessNetItem = m_WifiNetworkList[deviceName].at(index); updatewirelessItemConnectInfo(wirelessNetItem); m_WifiNetworkList[deviceName].replace(index,wirelessNetItem); qDebug()<< LOG_FLAG << "getWifiNetwork success"; return true; } } return false; } QString KyWirelessNetResource::getDeviceIFace(NetworkManager::ActiveConnection::Ptr actConn, QString &wirelessNetResourcessid) { if (actConn.isNull()) { return ""; } NetworkManager::Connection::Ptr conn = actConn->connection(); if (conn.isNull()) { return ""; } NetworkManager::ConnectionSettings::Ptr sett = conn->settings(); if (sett.isNull()) { return ""; } NetworkManager::WirelessSetting::Ptr wireless_sett = sett->setting(NetworkManager::Setting::Wireless).dynamicCast(); if (wireless_sett.isNull()) { return ""; } QByteArray rawSsid = wireless_sett->ssid(); wirelessNetResourcessid = getSsidFromByteArray(rawSsid); QStringList interfaces = actConn->devices(); if (interfaces.isEmpty()) { return ""; } QString ifaceUni = interfaces.at(0); NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceUni(ifaceUni); if (devicePtr.isNull()) { return QString(); } return devicePtr->interfaceName(); } void KyWirelessNetResource::getSsidByUuid(const QString uuid, QString &ssid) { ssid.clear(); NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(uuid); if (connectPtr.isNull()) { return; } NetworkManager::WirelessSetting::Ptr wireless_sett = connectPtr->settings()->setting(NetworkManager::Setting::Wireless).dynamicCast(); if (wireless_sett.isNull()) { qDebug()<< LOG_FLAG << "don't have WirelessSetting connection"; return; } QByteArray rawSsid = wireless_sett->ssid(); ssid = getSsidFromByteArray(rawSsid); qDebug()<< LOG_FLAG << "getSsidByUuid success " << ssid; return; } void KyWirelessNetResource::getDeviceByUuid(const QString uuid, QString &deviceName) { deviceName.clear(); NetworkManager::ActiveConnection::Ptr activeConnectionPtr = m_networkResourceInstance->getActiveConnect(uuid); if (!activeConnectionPtr.isNull()) { QStringList interfaces = activeConnectionPtr->devices(); if (interfaces.size() > 0) { QString ifaceUni = interfaces.at(0); NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceUni(ifaceUni); if (!devicePtr.isNull()) { deviceName = devicePtr->interfaceName(); return; } } else { qDebug() << LOG_FLAG << "get device of active connection failed."; } } NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(uuid); if (connectPtr.isNull()) { return; } deviceName = connectPtr->settings()->interfaceName(); return; } void KyWirelessNetResource::kyWirelessNetItemListInit() { qDebug()<< LOG_FLAG << "wireless net size:" << m_networkResourceInstance->m_wifiNets.size(); for (auto const & net : m_networkResourceInstance->m_wifiNets) { QString devIface = getDeviceIFace(net); if (devIface.isEmpty()) { continue; } KyWirelessNetItem item(net); if (item.m_NetSsid.isEmpty()) { continue; } if (!m_WifiNetworkList.contains(devIface)){ QList list; list.append(item); m_WifiNetworkList.insert(devIface,list); } else { m_WifiNetworkList[devIface].append(item); } } return; } QString KyWirelessNetResource::getDeviceIFace(NetworkManager::WirelessNetwork::Ptr net) { if (net.isNull()) { return ""; } QString devUni = net->device(); NetworkManager::Device::Ptr dev = m_networkResourceInstance->findDeviceUni(devUni); if (dev.isNull()) { qDebug()<< LOG_FLAG << "KyWirelessNetResource: can't find " << net->ssid() << " find in device list"; return ""; } return dev->interfaceName(); } void KyWirelessNetResource::onWifiNetworkAdded(QString devIfaceName, QString ssid) { NetworkManager::Device::Ptr dev = m_networkResourceInstance->findDeviceInterface(devIfaceName); if (dev.isNull()) { return; } NetworkManager::WirelessDevice* w_dev = qobject_cast(dev.data()); NetworkManager::WirelessNetwork::Ptr wifi = w_dev->findNetwork(ssid); if (wifi.isNull()) { return; } KyWirelessNetItem item(wifi); if (m_WifiNetworkList.contains(devIfaceName)) { for (int index = 0; index < m_WifiNetworkList[devIfaceName].size(); ++index) { if (m_WifiNetworkList[devIfaceName].at(index).m_NetSsid == item.m_NetSsid) { m_WifiNetworkList[devIfaceName].removeAt(index); index--; } } m_WifiNetworkList[devIfaceName].append(item); } else { QList list; list.append(item); m_WifiNetworkList.insert(devIfaceName,list); } Q_EMIT wifiNetworkAdd(devIfaceName, item); } void KyWirelessNetResource::onWifiNetworkRemoved(QString devIfaceName, QString ssid) { if (!m_WifiNetworkList.contains(devIfaceName)) { return; } for (int index = 0; index < m_WifiNetworkList.value(devIfaceName).size(); ++index) { if (m_WifiNetworkList[devIfaceName].at(index).m_NetSsid == ssid) { m_WifiNetworkList[devIfaceName].removeAt(index); //remove后为空则删除 if (m_WifiNetworkList.value(devIfaceName).isEmpty()) { m_WifiNetworkList.remove(devIfaceName); } Q_EMIT wifiNetworkRemove(devIfaceName,ssid); break; } } } void KyWirelessNetResource::onWifiNetworkSecuChange(NetworkManager::AccessPoint *accessPointPtr) { QString secuType = enumToQstring(accessPointPtr->capabilities(), accessPointPtr->wpaFlags(), accessPointPtr->rsnFlags()); QMap >::iterator iter = m_WifiNetworkList.begin(); while (iter != m_WifiNetworkList.end()) { QList::iterator itemIter = iter.value().begin(); while (itemIter != iter.value().end()) { if (itemIter->m_NetSsid == accessPointPtr->ssid()) { QString devName = iter.key(); itemIter->m_secuType = secuType; itemIter->setKySecuType(secuType); //qDebug() << "!!!!" << itemIter->m_NetSsid << itemIter->m_secuType << itemIter->m_kySecuType; Q_EMIT secuTypeChange(devName, accessPointPtr->ssid(), secuType); break; } itemIter++; } iter++; } } void KyWirelessNetResource::onWifiNetworkPropertyChange(QString interface, QString ssid, int signal, QString bssid, QString sec) { if (m_WifiNetworkList.contains(interface)) { QList::iterator iter = m_WifiNetworkList[interface].begin(); while (iter != m_WifiNetworkList[interface].end()) { qDebug() << iter->m_NetSsid; if (iter->m_NetSsid == ssid) { // qDebug()<< LOG_FLAG <<"recive properity changed signal, sender is" << iter->m_NetSsid; if (iter->m_signalStrength != signal) { iter->m_signalStrength = signal; Q_EMIT signalStrengthChange(interface, ssid, iter->m_signalStrength); } if (iter->m_bssid != bssid) { qDebug() << "bssid"; iter->m_bssid = bssid; Q_EMIT bssidChange(interface, ssid, iter->m_bssid); } if (iter->m_secuType != sec) { iter->setKySecuType(sec); Q_EMIT secuTypeChange(interface, ssid, sec); } break; } iter++; } } } void KyWirelessNetResource::onWifiNetworkDeviceDisappear() { m_WifiNetworkList.clear(); kyWirelessNetItemListInit(); } bool KyWirelessNetResource::getEnterPriseInfoTls(QString &uuid, KyEapMethodTlsInfo &info) { NetworkManager::Connection::Ptr conn = m_networkResourceInstance->getConnect(uuid); if (conn.isNull()) { qDebug()<< LOG_FLAG << "modifyEnterPriseInfoTls connection missing"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (security_sett.isNull()) { qDebug()<< LOG_FLAG << "don't have WirelessSecurity connection"; return false; } if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { return false; } NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); if (setting.isNull()) { qDebug()<< LOG_FLAG << "don't have Security8021x connection"; return false; } info.identity = setting->identity(); info.domain = setting->domainSuffixMatch(); info.caCertPath = setting->caCertificate(); if (info.caCertPath.left(7) == "file://") { info.caCertPath = info.caCertPath.mid(7); } info.clientCertPath = setting->clientCertificate(); if (info.clientCertPath.left(7) == "file://") { info.clientCertPath = info.clientCertPath.mid(7); } info.clientPrivateKey = QString(setting->privateKey()); if (info.clientPrivateKey.left(7) == "file://") { info.clientPrivateKey = info.clientPrivateKey.mid(7); } info.m_privateKeyPWDFlag = setting->privateKeyPasswordFlags(); if (!info.m_privateKeyPWDFlag) { info.clientPrivateKeyPWD = m_operation->getPrivateKeyPassword(conn->uuid()); } return true; } bool KyWirelessNetResource::getEnterPriseInfoPeap(QString &uuid, KyEapMethodPeapInfo &info) { NetworkManager::Connection::Ptr conn = m_networkResourceInstance->getConnect(uuid); if (conn.isNull()) { qDebug()<< LOG_FLAG << "getEnterPriseInfoPeap connection missing"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (security_sett.isNull()) { qDebug()<< LOG_FLAG << "don't have WirelessSecurity connection"; return false; } if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { qDebug()<< LOG_FLAG << "keyMgmt not WpaEap " << security_sett->keyMgmt(); return false; } NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); if (setting.isNull() || !setting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodPeap)) { qDebug()<< LOG_FLAG << "don't have Security8021x connection"; return false; } info.phase2AuthMethod = (KyNoEapMethodAuth)setting->phase2AuthMethod(); info.userName = setting->identity(); info.m_passwdFlag = setting->passwordFlags(); if (!info.m_passwdFlag) { info.userPWD = m_operation->get8021xPassword(conn->uuid()); } return true; } bool KyWirelessNetResource::getEnterPriseInfoTtls(QString &uuid, KyEapMethodTtlsInfo &info) { NetworkManager::Connection::Ptr conn = m_networkResourceInstance->getConnect(uuid); if (conn.isNull()) { qDebug()<< LOG_FLAG << "modifyEnterPriseInfoTtls connection missing"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (security_sett.isNull()) { qDebug()<< LOG_FLAG << "don't have WirelessSecurity connection"; return false; } if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { qDebug()<< LOG_FLAG << "not wpaeap"<keyMgmt(); return false; } NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); if (setting.isNull() || !setting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodTtls)) { qDebug()<< LOG_FLAG << "don't have Security8021x connection"; return false; } info.authEapMethod = (KyEapMethodAuth)setting->phase2AuthEapMethod(); info.authNoEapMethod = (KyNoEapMethodAuth)setting->phase2AuthMethod(); info.authType = KyTtlsAuthMethod::AUTH_EAP; if (info.authEapMethod != KyAuthEapMethodUnknown) { info.authType = KyTtlsAuthMethod::AUTH_EAP; } else { info.authType = KyTtlsAuthMethod::AUTH_NO_EAP; } info.userName = setting->identity(); info.m_passwdFlag = setting->passwordFlags(); if (!info.m_passwdFlag) { info.userPWD = m_operation->get8021xPassword(conn->uuid()); } return true; } bool KyWirelessNetResource::getEnterPriseInfoLeap(QString &uuid, KyEapMethodLeapInfo &info) { NetworkManager::Connection::Ptr conn = m_networkResourceInstance->getConnect(uuid); if (conn.isNull()) { qDebug()<< LOG_FLAG << "getEnterPriseInfoLeap connection missing"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (security_sett.isNull()) { qDebug()<< LOG_FLAG << "don't have WirelessSecurity connection"; return false; } if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { qDebug()<< LOG_FLAG << "keyMgmt not WpaEap " << security_sett->keyMgmt(); return false; } NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); if (setting.isNull() || !setting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodLeap)) { qDebug()<< LOG_FLAG << "don't have Security8021x connection"; return false; } info.m_userName = setting->identity(); info.m_passwdFlag = setting->passwordFlags(); if (!info.m_passwdFlag) { info.m_userPwd = m_operation->get8021xPassword(conn->uuid()); } return true; } bool KyWirelessNetResource::getEnterPriseInfoPwd(QString &uuid, KyEapMethodPwdInfo &info) { NetworkManager::Connection::Ptr conn = m_networkResourceInstance->getConnect(uuid); if (conn.isNull()) { qDebug()<< LOG_FLAG << "getEnterPriseInfoPwd connection missing"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (security_sett.isNull()) { qDebug()<< LOG_FLAG << "don't have WirelessSecurity connection"; return false; } if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { qDebug()<< LOG_FLAG << "keyMgmt not WpaEap " << security_sett->keyMgmt(); return false; } NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); if (setting.isNull() || !setting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodPwd)) { qDebug()<< LOG_FLAG << "don't have Security8021x connection"; return false; } info.m_userName = setting->identity(); info.m_passwdFlag = setting->passwordFlags(); if (!info.m_passwdFlag) { info.m_userPwd = m_operation->get8021xPassword(conn->uuid()); } return true; } bool KyWirelessNetResource::getEnterPriseInfoFast(QString &uuid, KyEapMethodFastInfo &info) { NetworkManager::Connection::Ptr conn = m_networkResourceInstance->getConnect(uuid); if (conn.isNull()) { qDebug()<< LOG_FLAG << "getEnterPriseInfoFast connection missing"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (security_sett.isNull()) { qDebug()<< LOG_FLAG << "don't have WirelessSecurity connection"; return false; } if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { qDebug()<< LOG_FLAG << "keyMgmt not WpaEap " << security_sett->keyMgmt(); return false; } NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); if (setting.isNull() || !setting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodFast)) { qDebug()<< LOG_FLAG << "don't have Security8021x connection"; return false; } info.m_anonIdentity = setting->anonymousIdentity(); info.m_pacProvisioning = (KyFastProvisioning)setting->phase1FastProvisioning(); info.m_pacFilePath = setting->pacFile(); if (info.m_pacFilePath.left(7) == "file://") { info.m_pacFilePath = info.m_pacFilePath.mid(7); } info.m_authMethod = (KyNoEapMethodAuth)setting->phase2AuthMethod(); info.m_userName = setting->identity(); info.m_passwdFlag = setting->passwordFlags(); if (!info.m_passwdFlag) { info.m_userPwd = m_operation->get8021xPassword(conn->uuid()); } return true; } void KyWirelessNetResource::onConnectionAdd(QString uuid) { qDebug() << LOG_FLAG << "onConnectionAdd " << uuid; NetworkManager::Connection::Ptr conn = m_networkResourceInstance->getConnect(uuid); if (conn.isNull()) { qDebug()<< LOG_FLAG << "onConnectionAdd can not find connection" << uuid; return; } NetworkManager::ConnectionSettings::Ptr sett = conn->settings(); if (sett->connectionType() != NetworkManager::ConnectionSettings::ConnectionType::Wireless) { qDebug()<< LOG_FLAG << uuid << " is not wireless connection"; return; } NetworkManager::WirelessSetting::Ptr wireless_sett = sett->setting(NetworkManager::Setting::Wireless).dynamicCast(); QByteArray rawSsid = wireless_sett->ssid(); QString wifiSsid = getSsidFromByteArray(rawSsid); QMap map; map.clear(); QMap >::iterator iter = m_WifiNetworkList.begin(); while (iter != m_WifiNetworkList.end()) { for(int i = 0; i < iter.value().size(); i++) { if (iter.value().at(i).m_NetSsid == wifiSsid && (sett->interfaceName() == iter.key() || sett->interfaceName().isEmpty())) { QString devIfaceName; QString ssid; m_WifiNetworkList[iter.key()][i].m_isConfigured = true; m_WifiNetworkList[iter.key()][i].m_connName = conn->name(); m_WifiNetworkList[iter.key()][i].m_connectUuid = conn->uuid(); m_WifiNetworkList[iter.key()][i].m_connDbusPath = conn->path(); m_WifiNetworkList[iter.key()][i].m_channel = wireless_sett->channel(); devIfaceName = iter.key(); ssid = iter.value().at(i).m_NetSsid; map.insert(devIfaceName, ssid); break; } } iter++; } if (!map.isEmpty()) { for(auto var = map.cbegin(); var != map.cend(); var++) { QString devIfaceName = var.key(); QString ssid = var.value(); Q_EMIT connectionAdd(devIfaceName, ssid); } } } void KyWirelessNetResource::onConnectionRemove(QString path) { qDebug()<< LOG_FLAG << "onConnectionRemove remove " << path; QMap map; map.clear(); QMap >::iterator iter = m_WifiNetworkList.begin(); while (iter != m_WifiNetworkList.end()) { qDebug()<< LOG_FLAG <<"wifi network list key:" << iter.key(); for(int i = 0; i < iter.value().size(); i++) { qDebug() << LOG_FLAG << "connection path" << iter.value().at(i).m_connDbusPath; if (iter.value().at(i).m_connDbusPath == path) { QString devIfaceName; QString ssid; m_WifiNetworkList[iter.key()][i].m_isConfigured = false; m_WifiNetworkList[iter.key()][i].m_connName = ""; m_WifiNetworkList[iter.key()][i].m_connectUuid = ""; m_WifiNetworkList[iter.key()][i].m_connDbusPath = ""; m_WifiNetworkList[iter.key()][i].m_channel = 0; devIfaceName = iter.key(); ssid = iter.value().at(i).m_NetSsid; map.insert(devIfaceName, ssid); break; } } iter++; } if (!map.isEmpty()) { for(auto var = map.cbegin(); var != map.cend(); var++) { QString devIfaceName = var.key(); QString ssid = var.value(); Q_EMIT connectionRemove(devIfaceName, ssid, path); } } } void KyWirelessNetResource::onConnectionUpdate(QString uuid) { qDebug()<< LOG_FLAG << "onConnectionUpdate " << uuid; KyWirelessNetItem temp; NetworkManager::Connection::Ptr conn = m_networkResourceInstance->getConnect(uuid); if (conn.isNull()) { qDebug()<< LOG_FLAG << "onConnectionAdd can not find connection" << uuid; return; } NetworkManager::ConnectionSettings::Ptr sett= conn->settings(); if (sett->connectionType() != NetworkManager::ConnectionSettings::ConnectionType::Wireless) { return; } QString ssid, dev; getSsidByUuid(uuid, ssid); getDeviceByUuid(uuid, dev); if (!dev.isEmpty()) { NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceInterface(dev); if (devicePtr.isNull() || !m_WifiNetworkList.contains(dev)) { return; } } QMap >::iterator iter; for (iter = m_WifiNetworkList.begin(); iter != m_WifiNetworkList.end(); ++iter) { QList::iterator itemIter; for (itemIter = iter.value().begin(); itemIter != iter.value().end(); ++itemIter) { //判断是否有其他wifi配置 更新WIFI-bd 的connect相关变量 emit update if (uuid == itemIter->m_connectUuid) { if (itemIter->m_NetSsid != ssid || (iter.key() != dev && !dev.isEmpty())) { temp=*itemIter; updatewirelessItemConnectInfoEx(&temp); *itemIter=temp; Q_EMIT connectionUpdate(iter.key(), itemIter->m_NetSsid); //判断netptr是否为空 空返回 //否则 更新ssid 的connect相关变量 emit update ssid NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceInterface(dev); NetworkManager::WirelessNetwork::Ptr netPtr = m_networkResourceInstance->findWifiNetwork(ssid, devicePtr->uni()); if (netPtr.isNull()) { qDebug() << LOG_FLAG << ssid << "netPtr is Null"; return; } } } //更新WIFI 的connect相关变量 emit update to ui if (ssid == itemIter->m_NetSsid) { if (iter.key() == dev || dev.isEmpty()) { temp=*itemIter; updatewirelessItemConnectInfoEx(&temp); *itemIter=temp; Q_EMIT connectionUpdate(dev, itemIter->m_NetSsid); } } break; } } Q_EMIT wifiNetworkUpdate(); } void KyWirelessNetResource::onDeviceAdd(QString deviceName, NetworkManager::Device::Type deviceType) { if(deviceType == NetworkManager::Device::Type::Wifi) { if (!m_WifiNetworkList.contains(deviceName)) { m_WifiNetworkList.insert(deviceName,QList()); } } } void KyWirelessNetResource::onDeviceRemove(QString deviceName) { if (m_WifiNetworkList.contains(deviceName)) { m_WifiNetworkList.remove(deviceName); } } void KyWirelessNetResource::onDeviceNameUpdate(QString oldName, QString newName) { if (!m_WifiNetworkList.contains(oldName)) { return; } QMap> newWifiNetworkList(m_WifiNetworkList); QList list = m_WifiNetworkList[oldName]; newWifiNetworkList.remove(oldName); newWifiNetworkList.insert(newName,list); m_WifiNetworkList = newWifiNetworkList; } kylin-nm/src/backend/dbus-interface/kywirelessconnectoperation.cpp0000664000175000017500000017117315167646234024537 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kywirelessconnectoperation.h" #include "kylinutil.h" #include #define PSK_SETTING_NAME "802-11-wireless-security" #define PRIVATE_PSK_SETTING_NAME "802-1x" NetworkManager::ConnectionSettings::Ptr assembleWpaXPskSettings(NetworkManager::AccessPoint::Ptr accessPoint, QString &psk, bool isAutoConnect) { QByteArray rawSsid = accessPoint->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); NetworkManager::ConnectionSettings::Ptr settings{new NetworkManager::ConnectionSettings{NetworkManager::ConnectionSettings::Wireless}}; settings->setId(wifiSsid); settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); settings->setAutoconnect(isAutoConnect); //Note: workaround for wrongly (randomly) initialized gateway-ping-timeout settings->setGatewayPingTimeout(0); NetworkManager::WirelessSetting::Ptr wifi_sett = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); wifi_sett->setInitialized(true); wifi_sett->setSsid(rawSsid); wifi_sett->setSecurity("802-11-wireless-security"); NetworkManager::WirelessSecuritySetting::Ptr security_sett = settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); if (NetworkManager::AccessPoint::Adhoc == accessPoint->mode()) { wifi_sett->setMode(NetworkManager::WirelessSetting::Adhoc); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaNone); } else { security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk); } if (!psk.isEmpty()) { security_sett->setPsk(psk); } return settings; } NetworkManager::ConnectionSettings::Ptr assembleSaeSettings(NetworkManager::AccessPoint::Ptr accessPoint, QString &psk, bool isAutoConnect) { QByteArray rawSsid = accessPoint->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); NetworkManager::ConnectionSettings::Ptr settings{new NetworkManager::ConnectionSettings{NetworkManager::ConnectionSettings::Wireless}}; settings->setId(wifiSsid); settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); settings->setAutoconnect(isAutoConnect); //Note: workaround for wrongly (randomly) initialized gateway-ping-timeout settings->setGatewayPingTimeout(0); NetworkManager::WirelessSetting::Ptr wifi_sett = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); wifi_sett->setInitialized(true); wifi_sett->setSsid(rawSsid); wifi_sett->setSecurity("802-11-wireless-security"); NetworkManager::WirelessSecuritySetting::Ptr security_sett = settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); if (NetworkManager::AccessPoint::Adhoc == accessPoint->mode()) { wifi_sett->setMode(NetworkManager::WirelessSetting::Adhoc); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaNone); } else { security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::SAE); } if (!psk.isEmpty()) { security_sett->setPsk(psk); } return settings; } NetworkManager::ConnectionSettings::Ptr assembleWirelessSettings( const NetworkManager::AccessPoint::Ptr accessPointPtr, const KyWirelessConnectSetting &connSettingInfo, bool isHidden) { QByteArray rawSsid; if (nullptr == accessPointPtr || accessPointPtr.isNull()) { rawSsid = connSettingInfo.m_ssid.toUtf8(); } else { rawSsid = accessPointPtr->rawSsid(); } NetworkManager::ConnectionSettings::Ptr settings{new NetworkManager::ConnectionSettings{NetworkManager::ConnectionSettings::Wireless}}; settings->setId(connSettingInfo.m_connectName); settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); settings->setAutoconnect(connSettingInfo.isAutoConnect); //Note: workaround for wrongly (randomly) initialized gateway-ping-timeout settings->setGatewayPingTimeout(0); settings->setInterfaceName(connSettingInfo.m_ifaceName); NetworkManager::WirelessSetting::Ptr wifi_sett = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); wifi_sett->setInitialized(true); wifi_sett->setSsid(rawSsid); wifi_sett->setSecurity("802-11-wireless-security"); wifi_sett->setHidden(isHidden); if (connSettingInfo.m_type != KyKeyMgmt::WpaNone && connSettingInfo.m_type != KyKeyMgmt::Unknown) { NetworkManager::WirelessSecuritySetting::Ptr security_sett = settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt((NetworkManager::WirelessSecuritySetting::KeyMgmt)connSettingInfo.m_type); if (KyKeyMgmt::SAE == connSettingInfo.m_type || KyKeyMgmt::WpaPsk == connSettingInfo.m_type) { security_sett->setPsk(connSettingInfo.m_psk); } } return settings; } KyWirelessConnectOperation::KyWirelessConnectOperation(QObject *parent) : KyConnectOperation(parent) { connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiEnabledChanged, this, &KyWirelessConnectOperation::wifiEnabledChanged); connect(this, &KyWirelessConnectOperation::enabledWirelessNetwork, m_networkResourceInstance, &KyNetworkResourceManager::setWirelessNetworkEnabled, Qt::ConnectionType::QueuedConnection); } KyWirelessConnectOperation::~KyWirelessConnectOperation() { m_networkResourceInstance = nullptr; } void KyWirelessConnectOperation::activeWirelessConnect(QString devIfaceName, QString connUuid) { activateConnection(connUuid, devIfaceName); return; } void KyWirelessConnectOperation::deActivateWirelessConnection(const QString activeConnectName, const QString &activeConnectUuid) { deactivateConnection(activeConnectName, activeConnectUuid); return; } //普通wifi void KyWirelessConnectOperation::addConnect(const KyWirelessConnectSetting &connSettingInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning()<referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } else { qDebug()<<"create wireless connect complete"; } watcher->deleteLater(); }); return; } //tls void KyWirelessConnectOperation::addTlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTlsInfo &tlsInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning()<referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); assembleEapMethodTlsSettings(connSetting, tlsInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless tls connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } else { qDebug()<<"create wireless connect complete"; } watcher->deleteLater(); }); return; } //peap void KyWirelessConnectOperation::addPeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPeapInfo &peapInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning()<referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); assembleEapMethodPeapSettings(connSetting, peapInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless peap connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } else { qDebug()<<"create wireless connect complete"; } watcher->deleteLater(); }); return; } void KyWirelessConnectOperation::addTtlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTtlsInfo &ttlsInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning()<referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); assembleEapMethodTtlsSettings(connSetting, ttlsInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless ttls connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } else { qDebug()<<"create wireless connect complete"; } watcher->deleteLater(); }); return; } //leap void KyWirelessConnectOperation::addLeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodLeapInfo &leapInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning() << errorMessage; Q_EMIT createConnectionError(errorMessage); return; } NetworkManager::AccessPoint::Ptr accessPointPtr = wifiNet->referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); assembleEapMethodLeapSettings(connSetting, leapInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless leap connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } else { qDebug()<<"create wireless connect complete"; } watcher->deleteLater(); }); return; } //pwd void KyWirelessConnectOperation::addPwdConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPwdInfo &pwdInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning() << errorMessage; Q_EMIT createConnectionError(errorMessage); return; } NetworkManager::AccessPoint::Ptr accessPointPtr = wifiNet->referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); assembleEapMethodPwdSettings(connSetting, pwdInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless pwd connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } else { qDebug()<<"create wireless connect complete"; } watcher->deleteLater(); }); return; } //fast void KyWirelessConnectOperation::addFastConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodFastInfo &fastInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning() << errorMessage; Q_EMIT createConnectionError(errorMessage); return; } NetworkManager::AccessPoint::Ptr accessPointPtr = wifiNet->referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); assembleEapMethodFastSettings(connSetting, fastInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless fast connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } else { qDebug()<<"create wireless connect complete"; } watcher->deleteLater(); }); } void KyWirelessConnectOperation::setWirelessAutoConnect(const QString &uuid, bool bAutoConnect) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setAutoConnect(connectionSettings, bAutoConnect); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::deleteWirelessConnect(const QString &connectUuid) { qDebug()<<"delete wireless connect uuid " << connectUuid; deleteConnect(connectUuid); return ; } QString KyWirelessConnectOperation::getPsk(const QString &connectUuid) { qDebug() << "getPsk" << connectUuid; NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(connectUuid); if (connectPtr.isNull()) { QString errorMessage = tr("it can not find connection") + connectUuid; qWarning()< reply = connectPtr->secrets(PSK_SETTING_NAME); QMap map(reply.value()); if (map.contains("802-11-wireless-security") && map.value("802-11-wireless-security").contains("psk")) { QString psk = map.value("802-11-wireless-security").value("psk").toString(); return psk; } return ""; } QString KyWirelessConnectOperation::getPrivateKeyPassword(const QString &connectUuid) { qDebug() << "getPsk" << connectUuid; NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(connectUuid); if (connectPtr.isNull()) { QString errorMessage = tr("it can not find connection") + connectUuid; qWarning()<path(), "org.freedesktop.NetworkManager.Settings.Connection", QDBusConnection::systemBus()); dbusInterface.setTimeout(500); QDBusMessage result = dbusInterface.call("GetSecrets", PRIVATE_PSK_SETTING_NAME); const QDBusArgument &dbusArg1st = result.arguments().at( 0 ).value(); QMap map; dbusArg1st >> map; if (map.contains("802-1x") && map.value("802-1x").contains("private-key-password")) { QString psk = map.value("802-1x").value("private-key-password").toString(); return psk; } return ""; } QString KyWirelessConnectOperation::get8021xPassword(const QString &connectUuid) { qDebug() << "getPsk" << connectUuid; NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(connectUuid); if (connectPtr.isNull()) { QString errorMessage = tr("it can not find connection") + connectUuid; qWarning()<path(), "org.freedesktop.NetworkManager.Settings.Connection", QDBusConnection::systemBus()); dbusInterface.setTimeout(500); QDBusMessage result = dbusInterface.call("GetSecrets", PRIVATE_PSK_SETTING_NAME); const QDBusArgument &dbusArg1st = result.arguments().at( 0 ).value(); QMap map; dbusArg1st >> map; // QDBusPendingReply reply = connectPtr->secrets(PRIVATE_PSK_SETTING_NAME); // QMap map(reply.value()); if (map.contains("802-1x") && map.value("802-1x").contains("password")) { QString psk = map.value("802-1x").value("password").toString(); return psk; } return ""; } void KyWirelessConnectOperation::updateIpv4AndIpv6SettingInfo(const QString &uuid, const KyConnectSetting &connectSettingsInfo) { qDebug()<<"updateIpv4AndIpv6SettingInfo wireless connect uuid " << uuid; NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setIpv4AndIpv6Setting(connectionSettings,connectSettingsInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessPersonalConnect(const QString &uuid, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); if (connSettingInfo.m_type != Unknown &&connSettingInfo.m_type != WpaNone && connSettingInfo.m_type != WpaPsk && connSettingInfo.m_type != SAE) { qDebug() << "updateWirelessPersonalConnect " << connSettingInfo.m_type << " not support"; return; } NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connectionSettings->setting(NetworkManager::Setting::Security8021x).dynamicCast(); wifi_8021x_sett->setInitialized(false); updateWirelessSecu(connectionSettings, connSettingInfo, bPwdChange); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessEnterPriseTlsConnect(const QString &uuid, const KyEapMethodTlsInfo &tlsInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (connectPtr.isNull()) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setWirelessSecuWpaXEap(connectionSettings); modifyEapMethodTlsSettings(connectionSettings, tlsInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessEnterPrisePeapConnect(const QString &uuid, const KyEapMethodPeapInfo &peapInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setWirelessSecuWpaXEap(connectionSettings); modifyEapMethodPeapSettings(connectionSettings, peapInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessEnterPriseTtlsConnect(const QString &uuid, const KyEapMethodTtlsInfo &ttlsInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setWirelessSecuWpaXEap(connectionSettings); modifyEapMethodTtlsSettings(connectionSettings, ttlsInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessEnterPriseLeapConnect(const QString &uuid, const KyEapMethodLeapInfo &leapInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setWirelessSecuWpaXEap(connectionSettings); modifyEapMethodLeapSettings(connectionSettings, leapInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessEnterPrisePwdConnect(const QString &uuid, const KyEapMethodPwdInfo &pwdInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setWirelessSecuWpaXEap(connectionSettings); modifyEapMethodPwdSettings(connectionSettings, pwdInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessEnterPriseFastConnect(const QString &uuid, const KyEapMethodFastInfo &fastInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setWirelessSecuWpaXEap(connectionSettings); modifyEapMethodFastSettings(connectionSettings, fastInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::addAndActiveWirelessConnect(QString & devIface,KyWirelessConnectSetting &connSettingInfo,bool isHidden) { qDebug() << "addAndActiveWirelessConnect" << connSettingInfo.m_ssid << devIface <findDeviceInterface(devIface); if (dev.isNull()) { Q_EMIT addAndActivateConnectionError("can not find device"); return; } qDebug() << "addAndActiveWirelessConnect device " << devIface << " exist"; dev_uni = dev->uni(); auto spec_dev = dev->as(); if (!isHidden) { qDebug() << "start assemble"; auto access_point = wifiNet->referenceAccessPoint(); conn_uni = access_point->uni(); conn_name = access_point->ssid(); spec_object = conn_uni; NetworkManager::WirelessSecurityType sec_type = NetworkManager::findBestWirelessSecurity(spec_dev->wirelessCapabilities() , true, (spec_dev->mode() == NetworkManager::WirelessDevice::Adhoc) , access_point->capabilities(), access_point->wpaFlags(), access_point->rsnFlags()); qDebug() << "findBestWirelessSecurity type "<< sec_type; NetworkManager::ConnectionSettings::Ptr settings = nullptr; switch (sec_type) { case NetworkManager::UnknownSecurity: qWarning() << QStringLiteral("unknown security to use for '%1'").arg(conn_name); case NetworkManager::NoneSecurity: //nothing to do break; case NetworkManager::WpaPsk: case NetworkManager::Wpa2Psk: settings = assembleWpaXPskSettings(access_point, connSettingInfo.m_psk, connSettingInfo.isAutoConnect); if (nullptr != settings) { map_settings = settings->toMap(); } else { qWarning() << QStringLiteral("connection settings assembly for '%1' failed, abandoning activation...").arg(conn_name); return; } break; //TODO: other types... case NetworkManager::SAE: settings = assembleSaeSettings(access_point, connSettingInfo.m_psk, connSettingInfo.isAutoConnect); if (nullptr != settings) { map_settings = settings->toMap(); } else { qWarning() << QStringLiteral("connection settings assembly for '%1' failed, abandoning activation...").arg(conn_name); return; } break; default: qDebug() << "addAndActiveWirelessConnect not support"; break; } qDebug() << "finish assemble"; } else { qDebug() << "start assembleWirelessSettings"; map_settings = assembleWirelessSettings(nullptr, connSettingInfo, isHidden)->toMap(); qDebug() << "finish assembleWirelessSettings"; } QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "activation of connection failed " << errorMessage; Q_EMIT addAndActivateConnectionError(errorMessage); } watcher->deleteLater(); }); } void KyWirelessConnectOperation::requestWirelessScan() { for (auto const & dev : m_networkResourceInstance->m_devices) { auto spec_dev = dev->as(); if (nullptr != spec_dev) { m_networkResourceInstance->requestScan(spec_dev); } } } void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseTlsConnect(KyEapMethodTlsInfo &info, KyWirelessConnectSetting &connSettingInfo, QString & devIface, bool isHidden) { QString conn_uni; QString dev_uni; QString spec_object; NMVariantMapMap map_settings; NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; if (!isHidden) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning()<referenceAccessPoint(); conn_uni = accessPointPtr->uni(); spec_object = conn_uni; } auto dev = m_networkResourceInstance->findDeviceInterface(devIface); if (dev.isNull()) { Q_EMIT addAndActivateConnectionError("can not find device"); return; } dev_uni = dev->uni(); NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, isHidden); assembleEapMethodTlsSettings(settings, info); if(settings.isNull()) { qDebug() << "assembleEapMethodTlsSettings failed"; return; } map_settings = settings->toMap(); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "addAndActiveWirelessEnterPriseTlsConnect failed " << errorMessage; Q_EMIT addAndActivateConnectionError(errorMessage); } watcher->deleteLater(); }); } void KyWirelessConnectOperation::addAndActiveWirelessEnterPrisePeapConnect(KyEapMethodPeapInfo &info, KyWirelessConnectSetting &connSettingInfo, QString & devIface, bool isHidden) { qDebug() <<"addAndActiveWirelessEnterPrisePeapConnect"; QString conn_uni; QString dev_uni; QString spec_object; NMVariantMapMap map_settings; NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; if (!isHidden) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning()<referenceAccessPoint(); conn_uni = accessPointPtr->uni(); spec_object = conn_uni; } auto dev = m_networkResourceInstance->findDeviceInterface(devIface); if (dev.isNull()) { Q_EMIT addAndActivateConnectionError("can not find device"); return; } dev_uni = dev->uni(); NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, isHidden); assembleEapMethodPeapSettings(settings, info); if(settings.isNull()) { qDebug() << "assembleEapMethodPeapSettings failed"; return; } map_settings = settings->toMap(); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "addAndActiveWirelessEnterPrisePeapConnect failed " << errorMessage; Q_EMIT addAndActivateConnectionError(errorMessage); } watcher->deleteLater(); }); } void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseTtlsConnect(KyEapMethodTtlsInfo &info, KyWirelessConnectSetting &connSettingInfo, QString & devIface, bool isHidden) { QString conn_uni; QString dev_uni; QString spec_object; NMVariantMapMap map_settings; NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; if (!isHidden) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning()<referenceAccessPoint(); conn_uni = accessPointPtr->uni(); spec_object = conn_uni; } auto dev = m_networkResourceInstance->findDeviceInterface(devIface); if (dev.isNull()) { Q_EMIT addAndActivateConnectionError("can not find device"); return; } dev_uni = dev->uni(); NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, isHidden); assembleEapMethodTtlsSettings(settings, info); if(settings.isNull()) { qDebug() << "assembleEapMethodTtlsSettings failed"; return; } map_settings = settings->toMap(); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "addAndActiveWirelessEnterPriseTtlsConnect failed " << errorMessage; Q_EMIT addAndActivateConnectionError(errorMessage); } watcher->deleteLater(); }); } void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseLeapConnect(KyEapMethodLeapInfo &info, KyWirelessConnectSetting &connSettingInfo, QString &devIface, bool isHidden) { QString conn_uni; QString dev_uni; QString spec_object; NMVariantMapMap map_settings; NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; if (!isHidden) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning()<referenceAccessPoint(); conn_uni = accessPointPtr->uni(); spec_object = conn_uni; } auto dev = m_networkResourceInstance->findDeviceInterface(devIface); if (dev.isNull()) { Q_EMIT addAndActivateConnectionError("can not find device"); return; } dev_uni = dev->uni(); NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, isHidden); assembleEapMethodLeapSettings(settings, info); if(settings.isNull()) { qDebug() << "assembleEapMethodLeapSettings failed"; return; } map_settings = settings->toMap(); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "addAndActiveWirelessEnterPriseLeapConnect failed " << errorMessage; Q_EMIT addAndActivateConnectionError(errorMessage); } watcher->deleteLater(); }); } void KyWirelessConnectOperation::addAndActiveWirelessEnterPrisePwdConnect(KyEapMethodPwdInfo &info, KyWirelessConnectSetting &connSettingInfo, QString &devIface, bool isHidden) { QString conn_uni; QString dev_uni; QString spec_object; NMVariantMapMap map_settings; NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; if (!isHidden) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning()<referenceAccessPoint(); conn_uni = accessPointPtr->uni(); spec_object = conn_uni; } auto dev = m_networkResourceInstance->findDeviceInterface(devIface); if (dev.isNull()) { Q_EMIT addAndActivateConnectionError("can not find device"); return; } dev_uni = dev->uni(); NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, isHidden); assembleEapMethodPwdSettings(settings, info); if(settings.isNull()) { qDebug() << "assembleEapMethodPwdSettings failed"; return; } map_settings = settings->toMap(); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "addAndActiveWirelessEnterPrisePwdConnect failed " << errorMessage; Q_EMIT addAndActivateConnectionError(errorMessage); } watcher->deleteLater(); }); } void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseFastConnect(KyEapMethodFastInfo &info, KyWirelessConnectSetting &connSettingInfo, QString &devIface, bool isHidden) { QString conn_uni; QString dev_uni; QString spec_object; NMVariantMapMap map_settings; NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; if (!isHidden) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning()<referenceAccessPoint(); conn_uni = accessPointPtr->uni(); spec_object = conn_uni; } auto dev = m_networkResourceInstance->findDeviceInterface(devIface); if (dev.isNull()) { Q_EMIT addAndActivateConnectionError("can not find device"); return; } dev_uni = dev->uni(); NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, isHidden); assembleEapMethodFastSettings(settings, info); if(settings.isNull()) { qDebug() << "assembleEapMethodFastSettings failed"; return; } map_settings = settings->toMap(); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "addAndActiveWirelessEnterPriseFastConnect failed " << errorMessage; Q_EMIT addAndActivateConnectionError(errorMessage); } watcher->deleteLater(); }); } //无线网络开关设置 void KyWirelessConnectOperation::setWirelessEnabled(bool enabled) { Q_EMIT enabledWirelessNetwork(enabled); return; } bool KyWirelessConnectOperation::getWirelessEnabled() { return NetworkManager::isWirelessEnabled(); } bool KyWirelessConnectOperation::getConnSecretFlags(QString &connUuid, NetworkManager::Setting::SecretFlags &flag) { NetworkManager::Connection::Ptr conn; conn = m_networkResourceInstance->getConnect(connUuid); if (conn.isNull()) { qDebug() <<"get failed"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); flag = security_sett->pskFlags(); return true; } NetworkManager::ConnectionSettings::Ptr KyWirelessConnectOperation::createWirelessApSetting(const QString apSsid, const QString apPassword, const QString apDevice, const QString wirelessBand) { NetworkManager::ConnectionSettings::Ptr connectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(NetworkManager::ConnectionSettings::Wireless)); connectionSettings->setId(apSsid); connectionSettings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); connectionSettings->setAutoconnect(false); connectionSettings->setAutoconnectPriority(0); connectionSettings->setInterfaceName(apDevice); //Note: workaround for wrongly (randomly) initialized gateway-ping-timeout connectionSettings->setGatewayPingTimeout(0); NetworkManager::Ipv4Setting::Ptr ipv4Setting = connectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); ipv4Setting->setInitialized(true); ipv4Setting->setMethod(NetworkManager::Ipv4Setting::Shared); NetworkManager::Ipv6Setting::Ptr ipv6Setting = connectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); ipv6Setting->setInitialized(true); ipv6Setting->setMethod(NetworkManager::Ipv6Setting::Ignored); NetworkManager::WirelessSetting::Ptr wirelessSetting = connectionSettings->setting(NetworkManager::Setting::Wireless).dynamicCast(); wirelessSetting->setInitialized(true); wirelessSetting->setSsid(apSsid.toUtf8()); wirelessSetting->setMode(NetworkManager::WirelessSetting::NetworkMode::Ap); wirelessSetting->setSecurity("802-11-wireless-security"); if (wirelessBand == WIFI_BAND_2_4GHZ) { wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::Bg); } else if (wirelessBand == WIFI_BAND_5GHZ) { wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::A); } else { qWarning()<<"[KyWirelessConnectOperation] the band type undefined"<setBand(NetworkManager::WirelessSetting::FrequencyBand::Automatic); } NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting = connectionSettings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (apPassword.isEmpty()) { wirelessSecuritySetting->setInitialized(false); } else { wirelessSecuritySetting->setInitialized(true); wirelessSecuritySetting->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk); wirelessSecuritySetting->setPsk(apPassword); } return connectionSettings; } QStringList KyWirelessConnectOperation::getBlackListHostName(QString apConnectPath) { QStringList blackList; blackList.clear(); QDBusInterface dbusInterface("org.freedesktop.NetworkManager", apConnectPath, "org.freedesktop.NetworkManager.Settings.Connection", QDBusConnection::systemBus()); if (!dbusInterface.isValid()) { qWarning()<(); QMap> map; dbusArg1st >> map; if (map.isEmpty()) { qWarning() << Q_FUNC_INFO << __LINE__ <<"map is empty!"; return blackList; } QMap wirelessMap = map.value(KEY_802_11_WIRELESS); if (wirelessMap.isEmpty()) { qWarning() << Q_FUNC_INFO << __LINE__ <<"wirelessMap is empty!"; return blackList; } if (wirelessMap.contains(KEY_BLACKLIST_HOSTNAME)) { blackList = wirelessMap.value(KEY_BLACKLIST_HOSTNAME).toStringList(); } return blackList; } void KyWirelessConnectOperation::updateWirelessApSetting( NetworkManager::Connection::Ptr apConnectPtr, const QString apName, const QString apPassword, const QString apDevice, const QString wirelessBand) { NetworkManager::ConnectionSettings::Ptr apConnectSettingPtr = apConnectPtr->settings(); apConnectSettingPtr->setId(apName); apConnectSettingPtr->setInterfaceName(apDevice); apConnectSettingPtr->setAutoconnect(false); NetworkManager::WirelessSetting::Ptr wirelessSetting = apConnectSettingPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); wirelessSetting->setInitialized(true); wirelessSetting->setSsid(apName.toUtf8()); if (wirelessBand == WIFI_BAND_2_4GHZ) { wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::Bg); } else if (wirelessBand == WIFI_BAND_5GHZ) { wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::A); } else { qWarning()<<"[KyWirelessConnectOperation] the band type undefined"<setBand(NetworkManager::WirelessSetting::FrequencyBand::Automatic); } NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting = apConnectSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (apPassword.isEmpty()) { wirelessSecuritySetting->setInitialized(false); } else { wirelessSecuritySetting->setInitialized(true); wirelessSecuritySetting->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk); wirelessSecuritySetting->setPsk(apPassword); } apConnectPtr->update(apConnectSettingPtr->toMap()); QStringList blackList = getBlackListHostName(apConnectPtr->path()); NMVariantMapMap newMap = apConnectSettingPtr->toMap(); if (newMap.contains(KEY_802_11_WIRELESS)) { newMap[KEY_802_11_WIRELESS].insert(KEY_BLACKLIST_HOSTNAME, blackList); if (wirelessBand == WIFI_BAND_2_4GHZ) { newMap[KEY_802_11_WIRELESS].remove("channel"); } } apConnectPtr->update(newMap); usleep(100*1000); } void KyWirelessConnectOperation::activeWirelessAp(const QString apUuid, const QString apName, const QString apPassword, const QString apDevice, const QString wirelessBand) { qDebug() << "[activeWirelessAp]" << apUuid << apName << apPassword << apDevice << wirelessBand; //1、检查连接是否存在 NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(apUuid); if (nullptr == connectPtr) { NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceInterface(apDevice); if (devicePtr.isNull()) { QString errorMsg ="Create hotspot faild. " + apDevice + " is not existed"; qWarning()<< errorMsg; Q_EMIT addAndActivateConnectionError(errorMsg); return; } QString deviceIdentifier = devicePtr->uni(); NetworkManager::ConnectionSettings::Ptr apConnectSettingPtr = createWirelessApSetting(apName, apPassword, apDevice, wirelessBand); QString specificObject = ""; QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(apConnectSettingPtr->toMap(), deviceIdentifier, specificObject), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMsg = "Create hotspot faild. " + watcher->error().message(); qWarning() << errorMsg; Q_EMIT addAndActivateConnectionError(errorMsg); } watcher->deleteLater(); }); } else { updateWirelessApSetting(connectPtr, apName, apPassword, apDevice, wirelessBand); QTimer::singleShot(500, this, [=](){ activateApConnectionByUuid(apUuid, apDevice); }); } return; } void KyWirelessConnectOperation::deactiveWirelessAp(const QString apName, const QString apUuid) { deactivateConnection(apName, apUuid); return; } //private NetworkManager::WirelessNetwork::Ptr KyWirelessConnectOperation::checkWifiNetExist(QString ssid, QString devName) { for (auto const & net : m_networkResourceInstance->m_wifiNets) { auto dev = m_networkResourceInstance->findDeviceUni(net->device()); if (dev == nullptr) { continue; } if (dev->type() != NetworkManager::Device::Wifi || dev->interfaceName() != devName) { continue; } NetworkManager::AccessPoint::Ptr accessPointPtr = net->referenceAccessPoint(); QByteArray rawSsid = accessPointPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); if (ssid == wifiSsid) { return net; } } return nullptr; } KyKeyMgmt KyWirelessConnectOperation::getConnectKeyMgmt(const QString &uuid) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (connectPtr.isNull()) { return KyKeyMgmt::Unknown; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = connectPtr->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if(security_sett.isNull()) { return KyKeyMgmt::Unknown; } return (KyKeyMgmt)security_sett->keyMgmt(); } void KyWirelessConnectOperation::updateWirelessSecu(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange) { qDebug() << "updateWirelessSecu " << connSettingInfo.m_type; NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); KyKeyMgmt type = connSettingInfo.m_type; qDebug() << "set keyMgmt " << type; if (type == WpaNone) { security_sett->setInitialized(false); return; } else { security_sett->setInitialized(true); } security_sett->setKeyMgmt((NetworkManager::WirelessSecuritySetting::KeyMgmt)type); if (bPwdChange) { security_sett->setPsk(connSettingInfo.m_psk); NetworkManager::Setting::SecretFlags flag = NetworkManager::Setting::None; security_sett->setPskFlags(flag); } return; } void KyWirelessConnectOperation::setWirelessSecuWpaXEap(NetworkManager::ConnectionSettings::Ptr connSettingPtr) { NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::KeyMgmt::WpaEap); return; } void KyWirelessConnectOperation::setIpv4AndIpv6Setting(NetworkManager::ConnectionSettings::Ptr connSetting, const KyConnectSetting &connSettingInfo) { NetworkManager::Ipv4Setting::Ptr ipv4Setting = connSetting->setting(NetworkManager::Setting::Ipv4).dynamicCast(); ipv4SettingSet(ipv4Setting, connSettingInfo); NetworkManager::Ipv6Setting::Ptr ipv6Setting = connSetting->setting(NetworkManager::Setting::Ipv6).dynamicCast(); ipv6SettingSet(ipv6Setting, connSettingInfo); } void KyWirelessConnectOperation::activateApConnectionByUuid(const QString apUuid, const QString apDevice) { QString connectPath = ""; QString deviceIdentifier = ""; QString connectName = ""; QString specificObject = "/"; qDebug()<<"it will activate hotspot connect"<getConnect(apUuid); if (connectPtr.isNull()) { QString errorMessage = tr("Create hotspot faild.UUID is empty, its name") + apUuid; qWarning() << errorMessage; Q_EMIT activateConnectionError(errorMessage); return; } connectPath = connectPtr->path(); connectName = connectPtr->name(); auto dev = m_networkResourceInstance->findDeviceInterface(apDevice); if (!dev.isNull()) { deviceIdentifier = dev->uni(); } if (deviceIdentifier.isEmpty()) { QString errorMessage = tr("Create hotspot faild.Device Identifier is empty, its name") + apDevice; qWarning() << errorMessage; Q_EMIT activateConnectionError(errorMessage); return ; } QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::activateConnection(connectPath, deviceIdentifier, specificObject), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this, connectName, apDevice] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("Create hotspot faild. ") + watcher->error().message(); qWarning()<activateConnectionError(errorMessage); } else { qWarning()<<"active wired connect complete."; } watcher->deleteLater(); }); return ; } bool KyWirelessConnectOperation::getEnterpiseEapMethod(const QString &uuid, KyEapMethodType &type) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (connectPtr.isNull()) { qWarning() << "getEnterpiseEapMethod faild.Can't find uuid = " << uuid; return false; } KyKeyMgmt keyMgmt = getConnectKeyMgmt(uuid); if (keyMgmt != WpaEap) { qWarning() << "getEnterpiseEapMethod but not WpaEap.it's " << keyMgmt; return false; } NetworkManager::ConnectionSettings::Ptr connectionSettings = connectPtr->settings(); NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connectionSettings->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list = wifi_8021x_sett->eapMethods(); if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodTls)) { type = TLS; } else if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodPeap)) { type = PEAP; } else if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodTtls)) { type = TTLS; } else if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodLeap)) { type = LEAP; } else if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodPwd)) { type = PWD; } else if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodFast)) { type = FAST; } return true; } kylin-nm/src/backend/dbus-interface/kywirelessnetitem.h0000664000175000017500000000463415167651420022265 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYWIRELESSNETITEM_H #define KYWIRELESSNETITEM_H #include #include "kylinnetworkresourcemanager.h" #include "kywirelessconnectoperation.h" class KyWirelessNetItem { public: KyWirelessNetItem(NetworkManager::WirelessNetwork::Ptr net); KyWirelessNetItem() {;} ~KyWirelessNetItem(); QString getDevice() { return m_device; } private: void init(NetworkManager::WirelessNetwork::Ptr net); public: QString m_NetSsid; QString m_connectUuid; QString m_bssid; int m_signalStrength; uint m_frequency; QString m_secuType; KySecuType m_kySecuType; QString m_uni; bool m_isMix; //only for m_isConfiged = true bool m_isConfigured; QString m_connName; QString m_connDbusPath; uint m_channel; int getCategory(QString uni); void setKySecuType(QString strSecuType); private: KyNetworkResourceManager *m_networkResourceInstance = nullptr; QString m_device; }; bool updatewirelessItemConnectInfo(KyWirelessNetItem& item); void updatewirelessItemConnectInfoEx(KyWirelessNetItem* item); #endif // KYWIRELESSNETITEM_H kylin-nm/src/backend/dbus-interface/kylinconnectoperation.h0000664000175000017500000000525215167651420023114 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINCONNECTOPERATION_H #define KYLINCONNECTOPERATION_H #include "kylinnetworkresourcemanager.h" #include "kylinconnectsetting.h" #include class KyConnectOperation : public QObject { Q_OBJECT public: explicit KyConnectOperation(QObject *parent = nullptr); ~KyConnectOperation(); public: void createConnect(KyConnectSetting &connectSettingsInfo); void updateConnect(NetworkManager::ConnectionSettings::Ptr connectionSettings, const KyConnectSetting &connectSettingsInfo); void deleteConnect(const QString &connectUuid); void activateConnection(const QString connectUuid, const QString deviceName); void deactivateConnection(const QString activeConnectName, const QString &activeConnectUuid, bool concise = false, QString devName = ""); public: void connectSettingSet( NetworkManager::ConnectionSettings::Ptr connectionSettings, const KyConnectSetting &connectSettingsInfo); void ipv4SettingSet(NetworkManager::Ipv4Setting::Ptr &ipv4Setting, const KyConnectSetting &connectSettingsInfo); void ipv6SettingSet(NetworkManager::Ipv6Setting::Ptr &ipv6Setting, const KyConnectSetting &connectSettingsInfo); void setAutoConnect(NetworkManager::ConnectionSettings::Ptr &connectSetting, bool bAutoConnect); inline void errorProcess(QString errorMessage); Q_SIGNALS: void createConnectionError(QString errorMessage); void updateConnectionError(QString errorMessage); void deleteConnectionError(QString errorMessage); void activateConnectionError(QString errorMessage); void deactivateConnectionError(QString errorMessage); protected: KyNetworkResourceManager *m_networkResourceInstance = nullptr; }; #endif // KYLINCONNECTOPERATION_H kylin-nm/src/backend/dbus-interface/kyvpnconnectoperation.h0000664000175000017500000003436215167646234023150 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYVPNCONNECTOPERATION_H #define KYVPNCONNECTOPERATION_H #include #include #include "kylinnetworkresourcemanager.h" #include "kylinconnectsetting.h" #include "kylinconnectoperation.h" #include "kylinconnectresource.h" #include "kyenterpricesettinginfo.h" #include #define VPN_SERVERTYPE_L2TP "org.freedesktop.NetworkManager.l2tp" #define VPN_SERVERTYPE_PPTP "org.freedesktop.NetworkManager.pptp" #define VPN_SERVERTYPE_OPENVPN "org.freedesktop.NetworkManager.openvpn" #define VPN_SERVERTYPE_STRONGSWAN "org.freedesktop.NetworkManager.strongswan" #define KYVPN_VPN_KEY "vpn" #define KYVPN_GATEWAY_KEY "gateway" #define KYVPN_REMOTE_KEY "remote" #define KYVPN_ADDRESS_KEY "address" #define KYVPN_USER_KEY "user" #define KYVPN_PASSWD_KEY "password" #define KYVPN_SECRETS_KEY "secrets" #define KYVPN_PASSWDFLAGS_KEY "password-flags" #define KYVPN_REFUSEPAP_KEY "refuse-pap" #define KYVPN_REFUSECHAP_KEY "refuse-chap" #define KYVPN_REFUSEEAP_KEY "refuse-eap" #define KYVPN_REFUSEMSCHAP_KEY "refuse-mschap" #define KYVPN_REFUSEMSCHAPV2_KEY "refuse-mschapv2" #define KYVPN_NOVJCOMP_KEY "no-vj-comp" #define KYVPN_NOACCOMP_KEY "noaccomp" #define KYVPN_NOBSDCOMP_KEY "nobsdcomp" #define KYVPN_NODEFLATE_KEY "nodeflate" #define KYVPN_NOPCOMP_KEY "nopcomp" #define KYVPN_DOMAIN_KEY "domain" #define KYVPN_REQUIREMPPE_KEY "require-mppe" #define KYVPN_MPPESTATEFUL_KEY "mppe-stateful" #define KYVPN_LCPECHOFAILURE_KEY "lcp-echo-failure" #define KYVPN_LCPECHOINTERVAL_KEY "lcp-echo-interval" #define KYVPN_MRU_KEY "mru" #define KYVPN_MTU_KEY "mtu" #define KYVPN_REQUIREMPPE128_KEY "require-mppe-128" #define KYVPN_REQUIREMPPE40_KEY "require-mppe-40" #define KYVPN_USERCERT_KEY "usercert" #define KYVPN_USERKEY_KEY "userkey" #define KYVPN_CERTPASSWD_KEY "cert-pass" #define KYVPN_CERTPASSWDFLAGS_KEY "cert-pass-flags" #define KYVPN_PIN_KEY "pin" #define KYVPN_VIRTUAL_KEY "virtual" #define KYVPN_ENCAP_KEY "encap" #define KYVPN_IPCOMP_KEY "ipcomp" #define KYVPN_PROPOSAL_KEY "proposal" #define KYVPN_IKE_KEY "ike" #define KYVPN_ESP_KEY "esp" //openvpn #define KYVPN_CONNECTIONTYPE_KEY "connection-type" #define KYVPN_CA_KEY "ca" #define KYVPN_CERT_KEY "cert" #define KYVPN_KEY_KEY "key" #define KYVPN_USERNAME_KEY "username" #define KYVPN_STATICKEY_KEY "static-key" #define KYVPN_STATICKEYDIR_KEY "static-key-direction" #define KYVPN_LOCALIP_KEY "local-ip" #define KYVPN_REMOTEIP_KEY "remote-ip" #define KYVPN_PORT_KEY "port" #define KYVPN_RENEGSEC_KEY "reneg-seconds" #define KYVPN_COMPLZO_KEY "comp-lzo" #define KYVPN_COMPRESS_KEY "compress" #define COMPLZO_LZODISABLE "no-by-default" #define COMPLZO_ADAPTIVE "adaptive" #define COMPRESS_LZO "lzo" #define COMPRESS_LZ4 "lz4" #define COMPRESS_LZ4V2 "lz4-v2" #define KYVPN_PROTOTCP_KEY "proto-tcp" #define KYVPN_DEVTYPE_KEY "dev-type" #define DEVTYPE_TUN "tun" #define DEVTYPE_TAP "tap" #define KYVPN_DEV_KEY "dev" #define KYVPN_TUNNELMTU_KEY "tunnel-mtu" #define KYVPN_FRAGMENTSIZE_KEY "fragment-size" #define KYVPN_MSSFIX_KEY "mssfix" #define KYVPN_REMOTERANDOM_KEY "remote-random" #define KYVPN_TUNIPV6_KEY "tun-ipv6" #define KYVPN_PING_KEY "ping" #define KYVPN_PINGEXIT_KEY "ping-exit" #define KYVPN_PINGRESTART_KEY "ping-restart" #define KYVPN_FLOAT_KEY "float" #define KYVPN_MAXROUTES_KEY "max-routes" #define KYVPN_VERIFYX509NAME_KEY "verify-x509-name" #define X509NAME_SUBJECT "subject" #define X509NAME_NAME "name" #define X509NAME_NAMEPREFIX "name-prefix" #define KYVPN_REMOTECERTTLS_KEY "remote-cert-tls" #define KYVPN_NSCERTTYPE_KEY "ns-cert-type" #define KYVPN_SERVER "server" #define KYVPN_CLIENT "client" #define KYVPN_TA_KEY "ta" #define KYVPN_TLSCRYPT_KEY "tls-crypt" #define KYVPN_TADIR_KEY "ta-dir" #define KYVPN_PROXYTYPE_KEY "proxy-type" #define PROXYTYPE_HTTP "http" #define PROXYTYPE_SOCKS "socks" #define KYVPN_PROXYSERVER_KEY "proxy-server" #define KYVPN_PROXYPORT_KEY "proxy-port" #define KYVPN_PROXYRETRY_KEY "proxy-retry" #define KYVPN_HTTPPROXYUSERNAME_KEY "http-proxy-username" #define KYVPN_HTTPPROXYPASSWD_KEY "http-proxy-password" #define KYVPN_HTTPPROXYPASSWDFLAGS_KEY "http-proxy-password-flags" #define KYVPN_KEYSIZE_KEY "keysize" #define KYVPN_AUTH_KEY "auth" #define KYVPN_METHOD_KEY "method" #define KYVPN_YES "yes" #define KYVPN_NO "no" //VPN类型 enum KyVpnType{ KYVPNTYPE_UNKNOWN = -1, KYVPNTYPE_L2TP = 0, KYVPNTYPE_OPENVPN, KYVPNTYPE_PPTP, KYVPNTYPE_STRONGSWAN }; //密码策略 enum KyPasswdPolicy{ KYPASSWD_FORTHISUSER = 0, KYPASSWD_FORALLUSER, KYPASSWD_ASKEVERYTIME, KYPASSWD_ISNOTREQUIRED = 4 }; //认证方式 enum KyAuthMethod2 { KYAUTH2_PAP = 1u << 0, //PAP认证 KYAUTH2_CHAP = 1u << 1, //CHAP认证 KYAUTH2_MSCHAP = 1u << 2, //MSCHAP认证 KYAUTH2_MSCHAPV2 = 1u << 3, //MSCHAPV2认证 KYAUTH2_EAP = 1u << 4, //EAP认证 KYAUTH2_ALL = KYAUTH2_PAP | KYAUTH2_CHAP | KYAUTH2_MSCHAP | KYAUTH2_MSCHAPV2 | KYAUTH2_EAP }; Q_DECLARE_FLAGS(KyAuthMethods, KyAuthMethod2) //压缩方式 enum KyCompressMethod { KYCOMP_BSD = 1u << 0, //允许BSD压缩 KYCOMP_DEFLATE = 1u << 1, //允许Deflate压缩 KYCOMP_TCP = 1u << 2, //允许TCP头压缩 KYCOMP_PROTO = 1u << 3, //使用协议域压缩协商 KYCOMP_ADDR = 1u << 4, //使用地址/控制压缩 KYCOMP_ALL = KYCOMP_BSD | KYCOMP_DEFLATE | KYCOMP_TCP | KYCOMP_PROTO | KYCOMP_ADDR }; Q_DECLARE_FLAGS(KyCompressMethods, KyCompressMethod) //高级设置 enum KyMPPEMethod { KYMPPE_DEFAULT = 0, //默认MPPE加密 KYMPPE_REQUIRE128, //128位加密 KYMPPE_REQUIRE40 //40位加密 }; enum KyAuthMethod{ KYAUTH_ERROR = -1, KYAUTH_PASSWD = 0, KYAUTH_KEY, KYAUTH_AGENT, KYAUTH_SMARTCARD, KYAUTH_EAP, KYAUTH_CERTIFICATE, KYAUTH_CERTIFICATEANDPASSWD, KYAUTH_STATICPASSWD }; enum KyCompressMethod2{ KYCOMP2_LZODISABLE = 0, KYCOMP2_LZO, KYCOMP2_LZ4, KYCOMP2_LZ4V2, KYCOMP2_LZOADAPTIVE, KYCOMP2_AUTO }; enum KyVirtualDeviceType{ KYVIRDEVTYPE_TUN = 0, KYVIRDEVTYPE_TAP }; enum KyVpnPingMethod{ KYVPNPING_EXIT = 0, KYVPNPING_RESTART }; enum KyVpnCheckServerMethod{ KYCHECKSERVER_NONE = 0, KYCHECKSERVER_ENTIRETHEME, KYCHECKSERVER_ENTIRENAME, KYCHECKSERVER_PRENAME }; enum KyVpnCertType{ KYVPNCERT_SERVER = 0, KYVPNCERT_CLIENT }; enum KyVpnTlsMode{ KYVPNTLS_NONE = 0, KYVPNTLS_AUTHENTICATION, KYVPNTLS_CRYPT }; enum KyVpnProxyType{ KYVPNPROXY_NONE = 0, KYVPNPROXY_HTTP, KYVPNPROXY_SOCKS }; enum KyHMACAuthMethod{ KYHMACAUTH_DEFAULT = 0, KYHMACAUTH_NONE, KYHMACAUTH_MD4, KYHMACAUTH_MD5, KYHMACAUTH_SHA1, KYHMACAUTH_SHA224, KYHMACAUTH_SHA256, KYHMACAUTH_SHA384, KYHMACAUTH_SHA512, KYHMACAUTH_RIPEMD160 }; class KyVpnConfig : public KyConnectSetting { public: KyVpnType m_vpnType; QString m_vpnName; QString m_gateway; //认证方式 KyAuthMethod m_authMethod; //VPN用户密码信息 QString m_userName; //用户密码 QString m_userPasswd; //密码策略 KyPasswdPolicy m_passwdPolicy = KYPASSWD_ASKEVERYTIME; //NT域 QString m_ntDomain; //CA证书 QString m_caCertificate; //用户证书 QString m_userCertificate; //用户私钥 QString m_userKey; //静态密钥 QString m_staticKey; //用户私有密钥密码 QString m_privatePasswd; //用户私有密码策略 KyPasswdPolicy m_privatePasswdPolicy = KYPASSWD_ASKEVERYTIME; //密钥方向 QString m_vpnKeyDir; //本地IP地址 QString m_localAddress; //远程IP地址 QString m_remoteAddress; //PIN码 QString m_pinId; //MPPE加密开关 bool m_mppeEnable = false; //MPPE加密算法 KyMPPEMethod m_mppeEncryptMethod = KYMPPE_DEFAULT; //使用有状态加密 bool m_isAllowStatefulEncryption = false; //发送PPP回显包 bool m_sendPppPackage = false; //认证方式 KyAuthMethods m_authMethods = KYAUTH2_ALL; //压缩方式 KyCompressMethods m_compressMethods = KYCOMP_ALL; //MRU 最大接收单元 QString m_mru; //MTU 最大传输单元 QString m_mtu; //请求使用内部IP bool m_virtual; //强制UDP封装 bool m_encap; //使用IP压缩 bool m_ipcomp; //启用自定义密码建议 bool m_proposal; //IKE QString m_ike; //ESP QString m_esp; //使用自定义网关端口 bool m_useAssignPort; QString m_assignPort; //使用自定义重协商间隔 bool m_useRenegSeconds; QString m_renegSeconds; //使用压缩 bool m_useCompress; KyCompressMethod2 m_openvpnCompress; //使用TCP连接 bool m_useTcpLink; //设置虚拟设备类型 bool m_setDevType; KyVirtualDeviceType m_devType; //设置虚拟设备名称 bool m_setDevName; QString m_devName; //使用自定义隧道最大单元传输 bool m_useTunnelMtu; QString m_tunnelMtu; //使用自定义UDP分片大小 bool m_useFragmentSize; QString m_fragmentSize; //限制TCP最大段尺寸 bool m_mssfix; //随机化远程主机 bool m_remoteRandom; //IPv6 tun link bool m_ipv6TunLink; //指定Ping周期 bool m_setPingCycle; QString m_pingCycle; //指定退出或重启Ping bool m_usePingMethod; KyVpnPingMethod m_pingMethod; QString m_pingMethodTime; //接受来自任何地址(Float)已通过身份验证的数据包 bool m_float; //指定路由上限 bool m_setMaxRoute; QString m_maxRoute; //服务器证书检验 KyVpnCheckServerMethod m_checkServerCa; //主题匹配 QString m_verifyName; //验证对等(服务器)证书用法签名 bool m_useRemoteCertTls; KyVpnCertType m_remoteCertType; //验证对等(服务器)证书nsCertType签名 bool m_useNsCertTls; KyVpnCertType m_nsCertType; //其他TLS身份验证 //模式 KyVpnTlsMode m_vpnTlsMode; //密钥文件 QString m_vpnKeyFile; //密钥方向 QString m_vpnTlsTaDir; //代理 //代理类型 KyVpnProxyType m_vpnProxyType; //服务器地址 QString m_vpnProxyServer; //端口 QString m_vpnProxyPort; //出错时无限重试 bool m_vpnProxyRetry; //代理用户名 QString m_vpnProxyName; //代理用户名 QString m_vpnProxyPasswd; //代理密码策略 KyPasswdPolicy m_vpnProxyPasswdPolicy = KYPASSWD_ASKEVERYTIME; //安全 //使用自定义密钥大小 bool m_useKeysize; QString m_keySize; //HMAC认证 KyHMACAuthMethod m_hmacAuthMethod; //IPv4Setting QStringList m_ipv4DnsSearch; QString m_ipv4DhcpClientId; //IPv6Setting QStringList m_ipv6DnsSearch; }; class KyVpnConnectOperation : public KyConnectOperation { Q_OBJECT public: explicit KyVpnConnectOperation(QObject *parent = nullptr); public: void createVpnConnect(KyVpnConfig &vpnSettings); void setVpnConfig(QString connectUuid, KyVpnConfig &vpnConfig); KyVpnConfig getVpnConfig(QString connectUuid); void activateVpnConnection(const QString connectUuid); void deactivateVpnConnection(const QString activeConnectName, const QString &activeConnectUuid); void deleteVpnConnect(const QString &connectUuid); private: KyHMACAuthMethod getHmacAuthMethod(const QString method); KyAuthMethod getAuthMethod(const QString method); void getConnectionSetting(QString connectUuid, KyVpnConfig &vpnConfig); void setConnectionSetting(NetworkManager::ConnectionSettings::Ptr connectionSettings, KyVpnConfig &vpnConfig); void getL2tpConfig(KyVpnConfig &vpnConfig); void setL2tpConfig(KyVpnConfig &vpnConfig); void getPptpConfig(KyVpnConfig &vpnConfig); void setPptpConfig(KyVpnConfig &vpnConfig); void getStrongswanConfig(KyVpnConfig &vpnConfig); void setStrongswanConfig(KyVpnConfig &vpnConfig); void getOpenvpnConfig(KyVpnConfig &vpnConfig); void setOpenvpnConfig(KyVpnConfig &vpnConfig); void getUsrPasswdAndPolicy(KyVpnConfig &vpnConfig); void setUsrPasswdAndPolicy(KyVpnConfig &vpnConfig); void getCertPasswdAndPolicy(KyVpnConfig &vpnConfig); void setCertPasswdAndPolicy(KyVpnConfig &vpnConfig); NMVariantMapMap setIpConfig(NetworkManager::ConnectionSettings::Ptr connectionSettings, KyVpnConfig &vpnConfig); private: QMap m_authMethodMap = { {"password" , KYAUTH_PASSWD }, {"key" , KYAUTH_KEY }, {"agent" , KYAUTH_AGENT }, {"smartcard" , KYAUTH_SMARTCARD }, {"eap" , KYAUTH_EAP }, {"tls" , KYAUTH_CERTIFICATE }, {"password-tls" , KYAUTH_CERTIFICATEANDPASSWD }, {"static-password" , KYAUTH_STATICPASSWD } }; QMap m_hmacMap = { {"none" , KYHMACAUTH_NONE }, {"RSA-MD4" , KYHMACAUTH_MD4 }, {"MD5" , KYHMACAUTH_MD5 }, {"SHA1" , KYHMACAUTH_SHA1 }, {"SHA224" , KYHMACAUTH_SHA224 }, {"SHA256" , KYHMACAUTH_SHA256 }, {"SHA384" , KYHMACAUTH_SHA384 }, {"SHA512" , KYHMACAUTH_SHA512 }, {"RIPEMD160" , KYHMACAUTH_RIPEMD160 } }; NMStringMap m_vpnData; NMStringMap m_vpnSecrets; }; #endif // KYVPNCONNECTOPERATION_H kylin-nm/src/backend/dbus-interface/kylinwiredconnectoperation.h0000664000175000017500000000450315167651420024145 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINWIREDCONNECTOPERATION_H #define KYLINWIREDCONNECTOPERATION_H #include #include #include "kylinnetworkresourcemanager.h" #include "kylinconnectsetting.h" #include "kylinconnectoperation.h" const QString WIRED_NETWORK_STATE_CONF_FILE = QDir::homePath() + "/.config/ukui/kylin-nm-wired.ini"; class KyWiredConnectOperation : public KyConnectOperation { Q_OBJECT public: explicit KyWiredConnectOperation(QObject *parent = nullptr); ~KyWiredConnectOperation(); public: //无线开关 void setWiredEnabled(bool enabled); bool getWiredEnabled(); void createWiredConnect(KyConnectSetting &connectSettingsInfo); void updateWiredConnect(const QString &connectUuid, const KyConnectSetting &connectSettingsInfo); void deleteWiredConnect(const QString &connectUuid); void activateWiredConnection(const QString connectUuid, const QString devName); void deactivateWiredConnection(const QString activeConnectName, const QString &activeConnectUuid, bool concise = false, QString devName = ""); int closeWiredNetworkWithDevice(QString deviceName); int openWiredNetworkWithDevice(QString deviceName); int setWiredDeviceAutoconnect(QString deviceName,bool autoconnectstate); Q_SIGNALS: void wiredEnabledChanged(bool); private: void getActiveConnection(QString &deviceName, QString &connectUuid); void saveActiveConnection(QString &deviceName, QString &connectUuid); }; #endif // KYLINWIREDCONNECTOPERATION_H kylin-nm/src/backend/dbus-interface/kylinconnectsetting.cpp0000664000175000017500000001004415167646234023126 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see KyConnectSetting::KyConnectSetting(/*QObject *parent) : QObject(parent*/) { m_connectName = ""; m_ifaceName = ""; m_ipv4ConfigIpType = CONFIG_IP_DHCP; m_ipv4Address.clear(); m_ipv4Dns.clear(); m_ipv6ConfigIpType = CONFIG_IP_DHCP; m_ipv6Address.clear(); m_ipv6Dns.clear(); m_isAutoConnect = true; } KyConnectSetting::~KyConnectSetting() { } void KyConnectSetting::setIfaceName(QString &ifaceName) { m_ifaceName = ifaceName; } void KyConnectSetting::setConnectName(QString &connectName) { m_connectName = connectName; } int KyConnectSetting::setIpConfigType(KyIpAddressType ipType, KyIpConfigType ipConfigType) { if (ipType != IPADDRESS_V4 && ipType != IPADDRESS_V6) { qWarning()<<"set config ip type failed, the ip address type undefined"< &ipv4Dns) { m_ipv4Dns = ipv4Dns; } void KyConnectSetting::ipv6AddressConstruct(QString &ipv6Address, QString &ipv6NetMask, QString &ipv6GateWay) { NetworkManager::IpAddress nmIpv6Address; nmIpv6Address.setIp(QHostAddress(ipv6Address)); nmIpv6Address.setGateway(QHostAddress(ipv6GateWay)); nmIpv6Address.setPrefixLength(ipv6NetMask.toInt()); m_ipv6Address.clear(); m_ipv6Address << nmIpv6Address; } void KyConnectSetting::ipv6DnsConstruct(QList &ipv6Dns) { m_ipv6Dns = ipv6Dns; } void KyConnectSetting::dumpInfo() { qDebug()<<"connect setting info:"; qDebug()<<"connect name"<< m_connectName; qDebug()<<"iface name" << m_ifaceName; qDebug()<<"ipv4 method" <toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create vpn connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } else { qDebug()<<"create vpn connect complete"; } watcher->deleteLater(); }); return; } void KyVpnConnectOperation::getConnectionSetting(QString connectUuid, KyVpnConfig &connectSetting) { qDebug() <<"[KyConnectResourse]" << connectUuid <<"get connect setting info, connect uuid"; KyNetworkResourceManager *networkResourceInstance = KyNetworkResourceManager::getInstance(); NetworkManager::Connection::Ptr connectPtr = networkResourceInstance->getConnect(connectUuid); if (nullptr == connectPtr || !connectPtr->isValid()) { qWarning() <<"[KyConnectResourse]" << "it can not find valid connection" << connectUuid; return; } connectSetting.m_connectName = connectPtr->name(); NetworkManager::ConnectionSettings::Ptr connectionSettings = connectPtr->settings(); connectSetting.m_ifaceName = connectionSettings->interfaceName(); connectSetting.m_isAutoConnect = connectionSettings->autoconnect(); if (NetworkManager::ConnectionSettings::ConnectionType::Vpn != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Bond != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Bridge != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Vlan != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Team != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::IpTunnel != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Wired != connectPtr->settings()->connectionType()) { return; } QDBusPendingReply reply = connectPtr->secrets(KYVPN_VPN_KEY); QMap secretMap(reply.value()); QVariantMap vpnSecretMap; vpnSecretMap.clear(); if (secretMap.contains(KYVPN_VPN_KEY)) { vpnSecretMap = secretMap.value(KYVPN_VPN_KEY); } connectSetting.m_vpnName = connectionSettings->id(); NetworkManager::VpnSetting::Ptr vpnSettings = connectionSettings->setting(NetworkManager::Setting::Vpn).dynamicCast(); m_vpnData.clear(); m_vpnData = vpnSettings->data(); m_vpnSecrets.clear(); if (!vpnSecretMap.isEmpty()) { vpnSettings->secretsFromMap(vpnSecretMap); } m_vpnSecrets = vpnSettings->secrets(); connectSetting.m_gateway.clear(); if (vpnSettings->serviceType() == VPN_SERVERTYPE_L2TP) { connectSetting.m_vpnType = KYVPNTYPE_L2TP; if (m_vpnData.contains(KYVPN_GATEWAY_KEY)) { connectSetting.m_gateway = m_vpnData.value(KYVPN_GATEWAY_KEY); } } else if (vpnSettings->serviceType() == VPN_SERVERTYPE_PPTP) { connectSetting.m_vpnType = KYVPNTYPE_PPTP; if (m_vpnData.contains(KYVPN_GATEWAY_KEY)) { connectSetting.m_gateway = m_vpnData.value(KYVPN_GATEWAY_KEY); } } else if (vpnSettings->serviceType() == VPN_SERVERTYPE_OPENVPN) { connectSetting.m_vpnType = KYVPNTYPE_OPENVPN; if (m_vpnData.contains(KYVPN_REMOTE_KEY)) { connectSetting.m_gateway = m_vpnData.value(KYVPN_REMOTE_KEY); } } else if (vpnSettings->serviceType() == VPN_SERVERTYPE_STRONGSWAN) { connectSetting.m_vpnType = KYVPNTYPE_STRONGSWAN; if (m_vpnData.contains(KYVPN_ADDRESS_KEY)) { connectSetting.m_gateway = m_vpnData.value(KYVPN_ADDRESS_KEY); } } else { connectSetting.m_vpnType = KYVPNTYPE_UNKNOWN; } NetworkManager::Ipv4Setting::Ptr ipv4Settings = connectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); connectSetting.m_ipv4DnsSearch = ipv4Settings->dnsSearch(); connectSetting.m_ipv4DhcpClientId = ipv4Settings->dhcpClientId(); if (NetworkManager::Ipv4Setting::Automatic == ipv4Settings->method()) { connectSetting.m_ipv4ConfigIpType = CONFIG_IP_DHCP; connectSetting.m_ipv4Dns = ipv4Settings->dns(); } else { connectSetting.m_ipv4ConfigIpType = CONFIG_IP_MANUAL; connectSetting.m_ipv4Address = ipv4Settings->addresses(); connectSetting.m_ipv4Dns = ipv4Settings->dns(); } NetworkManager::Ipv6Setting::Ptr ipv6Settings = connectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); connectSetting.m_ipv6DnsSearch = ipv6Settings->dnsSearch(); if (NetworkManager::Ipv6Setting::Automatic == ipv6Settings->method()) { connectSetting.m_ipv6ConfigIpType = CONFIG_IP_DHCP; connectSetting.m_ipv6Dns = ipv6Settings->dns(); } else { connectSetting.m_ipv6ConfigIpType = CONFIG_IP_MANUAL; connectSetting.m_ipv6Address = ipv6Settings->addresses(); connectSetting.m_ipv6Dns = ipv6Settings->dns(); } return; } KyVpnConfig KyVpnConnectOperation::getVpnConfig(QString connectUuid) { KyVpnConfig vpnConfig; getConnectionSetting(connectUuid, vpnConfig); switch (vpnConfig.m_vpnType) { case KYVPNTYPE_L2TP: getL2tpConfig(vpnConfig); break; case KYVPNTYPE_PPTP: getPptpConfig(vpnConfig); break; case KYVPNTYPE_STRONGSWAN: getStrongswanConfig(vpnConfig); break; case KYVPNTYPE_OPENVPN: getOpenvpnConfig(vpnConfig); break; default : break; } return vpnConfig; } NMVariantMapMap KyVpnConnectOperation::setIpConfig(NetworkManager::ConnectionSettings::Ptr connectionSettings, KyVpnConfig &vpnConfig) { NetworkManager::Ipv4Setting::Ptr ipv4Settings = connectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); ipv4SettingSet(ipv4Settings, vpnConfig); if (!vpnConfig.m_ipv4DnsSearch.isEmpty()) { ipv4Settings->setDnsSearch(vpnConfig.m_ipv4DnsSearch); } else { QStringList emptyList; emptyList.clear(); ipv4Settings->setDnsSearch({""}); } if (!vpnConfig.m_ipv4DhcpClientId.isEmpty()) { ipv4Settings->setDhcpClientId(vpnConfig.m_ipv4DhcpClientId); } else { ipv4Settings->setDhcpClientId(""); } NetworkManager::Ipv6Setting::Ptr ipv6Settings = connectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); ipv6SettingSet(ipv6Settings, vpnConfig); if (!vpnConfig.m_ipv6DnsSearch.isEmpty()) { ipv6Settings->setDnsSearch(vpnConfig.m_ipv6DnsSearch); } NMVariantMapMap connectionSettingMap = connectionSettings->toMap(); if (connectionSettingMap.contains("ipv4")) { QVariantMap ipv4Map = connectionSettingMap.value(QLatin1String("ipv4")); bool isAuto = false; if (ipv4Map.contains("method") && ipv4Map["method"] == "auto") { qDebug() << "[KyVpnConnectOperation] set ipv4 method auto, clear address-data && addresses && gateway"; isAuto = true; } if (isAuto) { if (ipv4Map.contains("address-data")) { ipv4Map.remove("address-data"); } if (ipv4Map.contains("addresses")) { ipv4Map.remove("addresses"); } if (ipv4Map.contains("gateway")) { ipv4Map.remove("gateway"); } connectionSettingMap["ipv4"] = ipv4Map; } } if (connectionSettingMap.contains("ipv6")) { QVariantMap ipv6Map = connectionSettingMap.value(QLatin1String("ipv6")); bool isAuto = false; if (ipv6Map.contains("method") && ipv6Map["method"] == "auto") { qDebug() << "[KyVpnConnectOperation] set ipv6 method auto, clear address-data && addresses && gateway"; isAuto = true; } if (isAuto) { if (ipv6Map.contains("address-data")) { ipv6Map.remove("address-data"); } if (ipv6Map.contains("addresses")) { ipv6Map.remove("addresses"); } if (ipv6Map.contains("gateway")) { ipv6Map.remove("gateway"); } connectionSettingMap["ipv6"] = ipv6Map; } } return connectionSettingMap; } void KyVpnConnectOperation::setVpnConfig(QString connectUuid, KyVpnConfig &vpnConfig) { qDebug() <<"[KyVpnConnectOperation]" << connectUuid <<"get connect setting info, connect uuid"; KyNetworkResourceManager *networkResourceInstance = KyNetworkResourceManager::getInstance(); NetworkManager::Connection::Ptr connectPtr = networkResourceInstance->getConnect(connectUuid); if (nullptr == connectPtr || !connectPtr->isValid()) { qWarning() <<"[KyVpnConnectOperation]" << "it can not find valid connection" << connectUuid; return; } NetworkManager::ConnectionSettings::Ptr connectionSettings = connectPtr->settings(); setConnectionSetting(connectionSettings, vpnConfig); NMVariantMapMap connectionSettingMap = setIpConfig(connectionSettings, vpnConfig); connectPtr->update(connectionSettingMap); return ; } void KyVpnConnectOperation::setConnectionSetting(NetworkManager::ConnectionSettings::Ptr connectionSettings, KyVpnConfig &vpnConfig) { connectionSettings->setId(vpnConfig.m_connectName); connectionSettings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); if (!vpnConfig.m_ifaceName.isEmpty()) { connectionSettings->setInterfaceName(vpnConfig.m_ifaceName); } connectionSettings->setAutoconnect(vpnConfig.m_isAutoConnect); NetworkManager::VpnSetting::Ptr vpnSettings = connectionSettings->setting(NetworkManager::Setting::Vpn).dynamicCast(); vpnSettings->setInitialized(true); m_vpnData.clear(); m_vpnSecrets.clear(); switch (vpnConfig.m_vpnType) { case KYVPNTYPE_L2TP: vpnSettings->setServiceType(VPN_SERVERTYPE_L2TP); setL2tpConfig(vpnConfig); break; case KYVPNTYPE_PPTP: vpnSettings->setServiceType(VPN_SERVERTYPE_PPTP); setPptpConfig(vpnConfig); break; case KYVPNTYPE_STRONGSWAN: vpnSettings->setServiceType(VPN_SERVERTYPE_STRONGSWAN); setStrongswanConfig(vpnConfig); break; case KYVPNTYPE_OPENVPN: vpnSettings->setServiceType(VPN_SERVERTYPE_OPENVPN); setOpenvpnConfig(vpnConfig); break; default : break; } vpnSettings->setData(m_vpnData); vpnSettings->setSecrets(m_vpnSecrets); return; } void KyVpnConnectOperation::getL2tpConfig(KyVpnConfig &vpnConfig) { vpnConfig.m_authMethod = KYAUTH_PASSWD; //获取用户名 vpnConfig.m_userName.clear(); if (m_vpnData.contains(KYVPN_USER_KEY)) { vpnConfig.m_userName = m_vpnData.value(KYVPN_USER_KEY); } //获取密码和加密策略 getUsrPasswdAndPolicy(vpnConfig); //获取NT域 vpnConfig.m_ntDomain.clear(); if (m_vpnData.contains(KYVPN_DOMAIN_KEY) && !m_vpnData.value(KYVPN_DOMAIN_KEY).isEmpty()) { vpnConfig.m_ntDomain = m_vpnData.value(KYVPN_DOMAIN_KEY); } if (m_vpnData.contains(KYVPN_MRU_KEY) && !m_vpnData.value(KYVPN_MRU_KEY).isEmpty()) { vpnConfig.m_mru = m_vpnData.value(KYVPN_MRU_KEY); } if (m_vpnData.contains(KYVPN_MTU_KEY) && !m_vpnData.value(KYVPN_MTU_KEY).isEmpty()) { vpnConfig.m_mtu = m_vpnData.value(KYVPN_MTU_KEY); } vpnConfig.m_authMethods.setFlag(KYAUTH2_ALL); if (m_vpnData.contains(KYVPN_REFUSEPAP_KEY) && m_vpnData.value(KYVPN_REFUSEPAP_KEY) == KYVPN_YES) { vpnConfig.m_authMethods.setFlag(KYAUTH2_PAP, false); } if (m_vpnData.contains(KYVPN_REFUSECHAP_KEY) && m_vpnData.value(KYVPN_REFUSECHAP_KEY) == KYVPN_YES) { vpnConfig.m_authMethods.setFlag(KYAUTH2_CHAP, false); } if (m_vpnData.contains(KYVPN_REFUSEMSCHAP_KEY) && m_vpnData.value(KYVPN_REFUSEMSCHAP_KEY) == KYVPN_YES) { vpnConfig.m_authMethods.setFlag(KYAUTH2_MSCHAP, false); } if (m_vpnData.contains(KYVPN_REFUSEMSCHAPV2_KEY) && m_vpnData.value(KYVPN_REFUSEMSCHAPV2_KEY) == KYVPN_YES) { vpnConfig.m_authMethods.setFlag(KYAUTH2_MSCHAPV2, false); } if (m_vpnData.contains(KYVPN_REFUSEEAP_KEY) && m_vpnData.value(KYVPN_REFUSEEAP_KEY) == KYVPN_YES) { vpnConfig.m_authMethods.setFlag(KYAUTH2_EAP, false); } vpnConfig.m_compressMethods.setFlag(KYCOMP_ALL); if (m_vpnData.contains(KYVPN_NOBSDCOMP_KEY) && m_vpnData.value(KYVPN_NOBSDCOMP_KEY) == KYVPN_YES) { vpnConfig.m_compressMethods.setFlag(KYCOMP_BSD, false); } if (m_vpnData.contains(KYVPN_NODEFLATE_KEY) && m_vpnData.value(KYVPN_NODEFLATE_KEY) == KYVPN_YES) { vpnConfig.m_compressMethods.setFlag(KYCOMP_DEFLATE, false); } if (m_vpnData.contains(KYVPN_NOVJCOMP_KEY) && m_vpnData.value(KYVPN_NOVJCOMP_KEY) == KYVPN_YES) { vpnConfig.m_compressMethods.setFlag(KYCOMP_TCP, false); } if (m_vpnData.contains(KYVPN_NOPCOMP_KEY) && m_vpnData.value(KYVPN_NOPCOMP_KEY) == KYVPN_YES) { vpnConfig.m_compressMethods.setFlag(KYCOMP_PROTO, false); } if (m_vpnData.contains(KYVPN_NOACCOMP_KEY) && m_vpnData.value(KYVPN_NOACCOMP_KEY) == KYVPN_YES) { vpnConfig.m_compressMethods.setFlag(KYCOMP_ADDR, false); } vpnConfig.m_mppeEnable = false; if (m_vpnData.contains(KYVPN_REQUIREMPPE_KEY)) { vpnConfig.m_mppeEnable = true; if (m_vpnData.contains(KYVPN_REQUIREMPPE128_KEY)) { vpnConfig.m_mppeEncryptMethod = KYMPPE_REQUIRE128; } else if (m_vpnData.contains(KYVPN_REQUIREMPPE40_KEY)) { vpnConfig.m_mppeEncryptMethod = KYMPPE_REQUIRE40; } else { vpnConfig.m_mppeEncryptMethod = KYMPPE_DEFAULT; } vpnConfig.m_authMethods.setFlag(KYAUTH2_EAP, false); vpnConfig.m_authMethods.setFlag(KYAUTH2_PAP, false); vpnConfig.m_authMethods.setFlag(KYAUTH2_CHAP, false); } vpnConfig.m_isAllowStatefulEncryption = false; if (m_vpnData.contains(KYVPN_MPPESTATEFUL_KEY)) { vpnConfig.m_isAllowStatefulEncryption = true; } vpnConfig.m_sendPppPackage = false; if (m_vpnData.contains(KYVPN_LCPECHOFAILURE_KEY) && m_vpnData.contains(KYVPN_LCPECHOINTERVAL_KEY)) { vpnConfig.m_sendPppPackage = true; } } void KyVpnConnectOperation::setL2tpConfig(KyVpnConfig &vpnConfig) { //设置用户名 if (!vpnConfig.m_userName.isEmpty()) { m_vpnData.insert(KYVPN_USER_KEY, vpnConfig.m_userName); } //设置密码和密码策略 setUsrPasswdAndPolicy(vpnConfig); //设置地址 if (!vpnConfig.m_gateway.isEmpty()) { m_vpnData.insert(KYVPN_GATEWAY_KEY, vpnConfig.m_gateway); } //设置NT域 if (!vpnConfig.m_ntDomain.isEmpty()) { m_vpnData.insert(KYVPN_DOMAIN_KEY, vpnConfig.m_ntDomain); } //设置MRU 最大接收单元 if (!vpnConfig.m_mru.isEmpty()) { m_vpnData.insert(KYVPN_MRU_KEY, vpnConfig.m_mru); } //设置MTU 最大传输单元 if (!vpnConfig.m_mtu.isEmpty()) { m_vpnData.insert(KYVPN_MTU_KEY, vpnConfig.m_mtu); } //设置认证方式 //不设置PAP认证,若未勾选,则对应字段设置YES if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_PAP)) { m_vpnData.insert(KYVPN_REFUSEPAP_KEY, KYVPN_YES); } //不设置CHAP认证,若未勾选,则对应字段设置YES if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_CHAP)) { m_vpnData.insert(KYVPN_REFUSECHAP_KEY, KYVPN_YES); } //不设置MSCHAP认证,若未勾选,则对应字段设置YES if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_MSCHAP)) { m_vpnData.insert(KYVPN_REFUSEMSCHAP_KEY, KYVPN_YES); } //不设置MSCHAPV2认证,若未勾选,则对应字段设置YES if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_MSCHAPV2)) { m_vpnData.insert(KYVPN_REFUSEMSCHAPV2_KEY, KYVPN_YES); } //不设置EAP认证,若未勾选,则对应字段设置YES if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_EAP)) { m_vpnData.insert(KYVPN_REFUSEEAP_KEY, KYVPN_YES); } //设置压缩方式 //不允许BSD压缩,若未勾选,则对应字段设置YES if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_BSD)) { m_vpnData.insert(KYVPN_NOBSDCOMP_KEY, KYVPN_YES); } //不允许Deflate压缩,若未勾选,则对应字段设置YES if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_DEFLATE)) { m_vpnData.insert(KYVPN_NODEFLATE_KEY, KYVPN_YES); } //不允许TCP头压缩,若未勾选,则对应字段设置YES if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_TCP)) { m_vpnData.insert(KYVPN_NOVJCOMP_KEY, KYVPN_YES); } //不使用协议域压缩协商,若未勾选,则对应字段设置YES if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_PROTO)) { m_vpnData.insert(KYVPN_NOPCOMP_KEY, KYVPN_YES); } //不使用地址/控制压缩,若未勾选,则对应字段设置YES if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_ADDR)) { m_vpnData.insert(KYVPN_NOACCOMP_KEY, KYVPN_YES); } //设置MPPE加密算法 if (vpnConfig.m_mppeEnable) { //设置MPPE加密算法方法为默认加密 m_vpnData.insert(KYVPN_REQUIREMPPE_KEY, KYVPN_YES); switch (vpnConfig.m_mppeEncryptMethod) { case KYMPPE_REQUIRE128: //设置MPPE加密算法方法为128位加密 m_vpnData.insert(KYVPN_REQUIREMPPE128_KEY, KYVPN_YES); break; case KYMPPE_REQUIRE40: //设置MPPE加密算法方法为40位加密 m_vpnData.insert(KYVPN_REQUIREMPPE40_KEY, KYVPN_YES); break; case KYMPPE_DEFAULT: default: break; } //若使用MPPE加密算法,则不设置PAP认证、不设置CHAP认证、不设置EAP认证 m_vpnData.insert(KYVPN_REFUSEPAP_KEY, KYVPN_YES); m_vpnData.insert(KYVPN_REFUSECHAP_KEY, KYVPN_YES); m_vpnData.insert(KYVPN_REFUSEEAP_KEY, KYVPN_YES); } //允许有状态的加密 if (vpnConfig.m_isAllowStatefulEncryption) { m_vpnData.insert(KYVPN_MPPESTATEFUL_KEY, KYVPN_YES); } //发送PPP回显包 if (vpnConfig.m_sendPppPackage) { m_vpnData.insert(KYVPN_LCPECHOFAILURE_KEY, "5"); m_vpnData.insert(KYVPN_LCPECHOINTERVAL_KEY, "30"); } } void KyVpnConnectOperation::getPptpConfig(KyVpnConfig &vpnConfig) { vpnConfig.m_authMethod = KYAUTH_PASSWD; vpnConfig.m_userName.clear(); if (m_vpnData.contains(KYVPN_USER_KEY)) { vpnConfig.m_userName = m_vpnData.value(KYVPN_USER_KEY); } getUsrPasswdAndPolicy(vpnConfig); vpnConfig.m_ntDomain.clear(); if (m_vpnData.contains(KYVPN_DOMAIN_KEY)) { vpnConfig.m_ntDomain = m_vpnData.value(KYVPN_DOMAIN_KEY); } vpnConfig.m_authMethods.setFlag(KYAUTH2_ALL); if (m_vpnData.contains(KYVPN_REFUSEPAP_KEY) && m_vpnData.value(KYVPN_REFUSEPAP_KEY) == KYVPN_YES) { vpnConfig.m_authMethods.setFlag(KYAUTH2_PAP, false); } if (m_vpnData.contains(KYVPN_REFUSECHAP_KEY) && m_vpnData.value(KYVPN_REFUSECHAP_KEY) == KYVPN_YES) { vpnConfig.m_authMethods.setFlag(KYAUTH2_CHAP, false); } if (m_vpnData.contains(KYVPN_REFUSEMSCHAP_KEY) && m_vpnData.value(KYVPN_REFUSEMSCHAP_KEY) == KYVPN_YES) { vpnConfig.m_authMethods.setFlag(KYAUTH2_MSCHAP, false); } if (m_vpnData.contains(KYVPN_REFUSEMSCHAPV2_KEY) && m_vpnData.value(KYVPN_REFUSEMSCHAPV2_KEY) == KYVPN_YES) { vpnConfig.m_authMethods.setFlag(KYAUTH2_MSCHAPV2, false); } if (m_vpnData.contains(KYVPN_REFUSEEAP_KEY) && m_vpnData.value(KYVPN_REFUSEEAP_KEY) == KYVPN_YES) { vpnConfig.m_authMethods.setFlag(KYAUTH2_EAP, false); } vpnConfig.m_compressMethods.setFlag(KYCOMP_ALL); vpnConfig.m_compressMethods.setFlag(KYCOMP_PROTO, false); vpnConfig.m_compressMethods.setFlag(KYCOMP_ADDR, false); if (m_vpnData.contains(KYVPN_NOBSDCOMP_KEY) && m_vpnData.value(KYVPN_NOBSDCOMP_KEY) == KYVPN_YES) { vpnConfig.m_compressMethods.setFlag(KYCOMP_BSD, false); } if (m_vpnData.contains(KYVPN_NODEFLATE_KEY) && m_vpnData.value(KYVPN_NODEFLATE_KEY) == KYVPN_YES) { vpnConfig.m_compressMethods.setFlag(KYCOMP_DEFLATE, false); } if (m_vpnData.contains(KYVPN_NOVJCOMP_KEY) && m_vpnData.value(KYVPN_NOVJCOMP_KEY) == KYVPN_YES) { vpnConfig.m_compressMethods.setFlag(KYCOMP_TCP, false); } vpnConfig.m_mppeEnable = false; if (m_vpnData.contains(KYVPN_REQUIREMPPE_KEY)) { vpnConfig.m_mppeEnable = true; if (m_vpnData.contains(KYVPN_REQUIREMPPE128_KEY)) { vpnConfig.m_mppeEncryptMethod = KYMPPE_REQUIRE128; } else if (m_vpnData.contains(KYVPN_REQUIREMPPE40_KEY)) { vpnConfig.m_mppeEncryptMethod = KYMPPE_REQUIRE40; } else { vpnConfig.m_mppeEncryptMethod = KYMPPE_DEFAULT; } vpnConfig.m_authMethods.setFlag(KYAUTH2_EAP, false); vpnConfig.m_authMethods.setFlag(KYAUTH2_PAP, false); vpnConfig.m_authMethods.setFlag(KYAUTH2_CHAP, false); } vpnConfig.m_isAllowStatefulEncryption = false; if (m_vpnData.contains(KYVPN_MPPESTATEFUL_KEY)) { vpnConfig.m_isAllowStatefulEncryption = true; } vpnConfig.m_sendPppPackage = false; if (m_vpnData.contains(KYVPN_LCPECHOFAILURE_KEY) && m_vpnData.contains(KYVPN_LCPECHOINTERVAL_KEY)) { vpnConfig.m_sendPppPackage = true; } } void KyVpnConnectOperation::setPptpConfig(KyVpnConfig &vpnConfig) { //设置用户名 if (!vpnConfig.m_userName.isEmpty()) { m_vpnData.insert(KYVPN_USER_KEY, vpnConfig.m_userName); } //设置密码和密码策略 setUsrPasswdAndPolicy(vpnConfig); //设置地址 if (!vpnConfig.m_gateway.isEmpty()) { m_vpnData.insert(KYVPN_GATEWAY_KEY, vpnConfig.m_gateway); } //设置NT域 if (!vpnConfig.m_ntDomain.isEmpty()) { m_vpnData.insert(KYVPN_DOMAIN_KEY, vpnConfig.m_ntDomain); } //设置认证方式 //不设置PAP认证,若未勾选,则对应字段设置YES if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_PAP)) { m_vpnData.insert(KYVPN_REFUSEPAP_KEY, KYVPN_YES); } //不设置CHAP认证,若未勾选,则对应字段设置YES if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_CHAP)) { m_vpnData.insert(KYVPN_REFUSECHAP_KEY, KYVPN_YES); } //不设置MSCHAP认证,若未勾选,则对应字段设置YES if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_MSCHAP)) { m_vpnData.insert(KYVPN_REFUSEMSCHAP_KEY, KYVPN_YES); } //不设置MSCHAPV2认证,若未勾选,则对应字段设置YES if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_MSCHAPV2)) { m_vpnData.insert(KYVPN_REFUSEMSCHAPV2_KEY, KYVPN_YES); } //不设置EAP认证,若未勾选,则对应字段设置YES if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_EAP)) { m_vpnData.insert(KYVPN_REFUSEEAP_KEY, KYVPN_YES); } //设置压缩方式 //不允许BSD压缩,若未勾选,则对应字段设置YES if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_BSD)) { m_vpnData.insert(KYVPN_NOBSDCOMP_KEY, KYVPN_YES); } //不允许Deflate压缩,若未勾选,则对应字段设置YES if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_DEFLATE)) { m_vpnData.insert(KYVPN_NODEFLATE_KEY, KYVPN_YES); } //不允许TCP头压缩,若未勾选,则对应字段设置YES if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_TCP)) { m_vpnData.insert(KYVPN_NOVJCOMP_KEY, KYVPN_YES); } //设置MPPE加密算法 if (vpnConfig.m_mppeEnable) { //设置MPPE加密算法方法为默认加密 m_vpnData.insert(KYVPN_REQUIREMPPE_KEY, KYVPN_YES); switch (vpnConfig.m_mppeEncryptMethod) { case KYMPPE_REQUIRE128: //设置MPPE加密算法方法为128位加密 m_vpnData.insert(KYVPN_REQUIREMPPE128_KEY, KYVPN_YES); break; case KYMPPE_REQUIRE40: //设置MPPE加密算法方法为40位加密 m_vpnData.insert(KYVPN_REQUIREMPPE40_KEY, KYVPN_YES); break; case KYMPPE_DEFAULT: default: break; } //若使用MPPE加密算法,则不设置PAP认证、不设置CHAP认证、不设置EAP认证 m_vpnData.insert(KYVPN_REFUSEPAP_KEY, KYVPN_YES); m_vpnData.insert(KYVPN_REFUSECHAP_KEY, KYVPN_YES); m_vpnData.insert(KYVPN_REFUSEEAP_KEY, KYVPN_YES); } //允许有状态的加密 if (vpnConfig.m_isAllowStatefulEncryption) { m_vpnData.insert(KYVPN_MPPESTATEFUL_KEY, KYVPN_YES); } //发送PPP回显包 if (vpnConfig.m_sendPppPackage) { m_vpnData.insert(KYVPN_LCPECHOFAILURE_KEY, "5"); m_vpnData.insert(KYVPN_LCPECHOINTERVAL_KEY, "30"); } } void KyVpnConnectOperation::getStrongswanConfig(KyVpnConfig &vpnConfig) { vpnConfig.m_authMethod = KYAUTH_ERROR; if (m_vpnData.contains(KYVPN_METHOD_KEY)) { vpnConfig.m_authMethod = getAuthMethod(m_vpnData.value(KYVPN_METHOD_KEY)); } vpnConfig.m_userCertificate.clear(); vpnConfig.m_userKey.clear(); vpnConfig.m_userName.clear(); vpnConfig.m_pinId.clear(); switch (vpnConfig.m_authMethod) { case KYAUTH_KEY: if (m_vpnData.contains(KYVPN_USERCERT_KEY)) { vpnConfig.m_userCertificate = m_vpnData.value(KYVPN_USERCERT_KEY); } if (m_vpnData.contains(KYVPN_USERKEY_KEY)) { vpnConfig.m_userKey = m_vpnData.value(KYVPN_USERKEY_KEY); } getCertPasswdAndPolicy(vpnConfig); break; case KYAUTH_AGENT: if (m_vpnData.contains(KYVPN_USERCERT_KEY)) { vpnConfig.m_userCertificate = m_vpnData.value(KYVPN_USERCERT_KEY); } break; case KYAUTH_SMARTCARD: if (m_vpnData.contains(KYVPN_PIN_KEY)) { vpnConfig.m_pinId = m_vpnData.value(KYVPN_PIN_KEY); } break; case KYAUTH_EAP: if (m_vpnData.contains(KYVPN_USER_KEY)) { vpnConfig.m_userName = m_vpnData.value(KYVPN_USER_KEY); } getUsrPasswdAndPolicy(vpnConfig); break; default : break; } vpnConfig.m_virtual = false; if (m_vpnData.contains(KYVPN_VIRTUAL_KEY) && m_vpnData.value(KYVPN_VIRTUAL_KEY) == KYVPN_YES) { vpnConfig.m_virtual = true; } vpnConfig.m_encap = false; if (m_vpnData.contains(KYVPN_ENCAP_KEY) && m_vpnData.value(KYVPN_ENCAP_KEY) == KYVPN_YES) { vpnConfig.m_encap = true; } vpnConfig.m_ipcomp = false; if (m_vpnData.contains(KYVPN_IPCOMP_KEY) && m_vpnData.value(KYVPN_IPCOMP_KEY) == KYVPN_YES) { vpnConfig.m_ipcomp = true; } vpnConfig.m_proposal = false; if (m_vpnData.contains(KYVPN_PROPOSAL_KEY) && m_vpnData.value(KYVPN_PROPOSAL_KEY) == KYVPN_YES) { vpnConfig.m_proposal = true; } vpnConfig.m_ike.clear(); if (m_vpnData.contains(KYVPN_IKE_KEY)) { vpnConfig.m_ike = m_vpnData.value(KYVPN_IKE_KEY); } vpnConfig.m_esp.clear(); if (m_vpnData.contains(KYVPN_ESP_KEY)) { vpnConfig.m_esp = m_vpnData.value(KYVPN_ESP_KEY); } } void KyVpnConnectOperation::setStrongswanConfig(KyVpnConfig &vpnConfig) { m_vpnData.insert(KYVPN_METHOD_KEY, m_authMethodMap.key(vpnConfig.m_authMethod)); if (!vpnConfig.m_gateway.isEmpty()) { m_vpnData.insert(KYVPN_ADDRESS_KEY, vpnConfig.m_gateway); } switch (vpnConfig.m_authMethod) { case KYAUTH_KEY: if (!vpnConfig.m_userCertificate.isEmpty()) { m_vpnData.insert(KYVPN_USERCERT_KEY, vpnConfig.m_userCertificate); } else { m_vpnData.remove(KYVPN_USERCERT_KEY); } if (!vpnConfig.m_userKey.isEmpty()) { m_vpnData.insert(KYVPN_USERKEY_KEY, vpnConfig.m_userKey); } else { m_vpnData.remove(KYVPN_USERKEY_KEY); } setCertPasswdAndPolicy(vpnConfig); break; case KYAUTH_AGENT: if (!vpnConfig.m_userCertificate.isEmpty()) { m_vpnData.insert(KYVPN_USERCERT_KEY, vpnConfig.m_userCertificate); } break; case KYAUTH_SMARTCARD: if (!vpnConfig.m_pinId.isEmpty()) { m_vpnData.insert(KYVPN_PIN_KEY, vpnConfig.m_pinId); } break; case KYAUTH_EAP: if (!vpnConfig.m_userName.isEmpty()) { m_vpnData.insert(KYVPN_USER_KEY, vpnConfig.m_userName); } vpnConfig.m_passwdPolicy = KYPASSWD_FORALLUSER; setUsrPasswdAndPolicy(vpnConfig); break; default : break; } if (vpnConfig.m_virtual) { m_vpnData.insert(KYVPN_VIRTUAL_KEY, KYVPN_YES); } else { m_vpnData.insert(KYVPN_VIRTUAL_KEY, KYVPN_NO); } if (vpnConfig.m_encap) { m_vpnData.insert(KYVPN_ENCAP_KEY, KYVPN_YES); } else { m_vpnData.insert(KYVPN_ENCAP_KEY, KYVPN_NO); } if (vpnConfig.m_ipcomp) { m_vpnData.insert(KYVPN_IPCOMP_KEY, KYVPN_YES); } else { m_vpnData.insert(KYVPN_IPCOMP_KEY, KYVPN_NO); } if (vpnConfig.m_proposal) { m_vpnData.insert(KYVPN_PROPOSAL_KEY, KYVPN_YES); if (!vpnConfig.m_ike.isEmpty()) { m_vpnData.insert(KYVPN_IKE_KEY, vpnConfig.m_ike); } if (!vpnConfig.m_esp.isEmpty()) { m_vpnData.insert(KYVPN_ESP_KEY, vpnConfig.m_esp); } } else { m_vpnData.insert(KYVPN_PROPOSAL_KEY, KYVPN_NO); m_vpnData.remove(KYVPN_IKE_KEY); m_vpnData.remove(KYVPN_ESP_KEY); } } void KyVpnConnectOperation::getOpenvpnConfig(KyVpnConfig &vpnConfig) { vpnConfig.m_authMethod = KYAUTH_ERROR; if (m_vpnData.contains(KYVPN_CONNECTIONTYPE_KEY)) { vpnConfig.m_authMethod = getAuthMethod(m_vpnData.value(KYVPN_CONNECTIONTYPE_KEY)); } vpnConfig.m_caCertificate.clear(); vpnConfig.m_userCertificate.clear(); vpnConfig.m_userKey.clear(); vpnConfig.m_userName.clear(); vpnConfig.m_staticKey.clear(); vpnConfig.m_vpnKeyDir.clear(); vpnConfig.m_localAddress.clear(); vpnConfig.m_remoteAddress.clear(); switch (vpnConfig.m_authMethod) { case KYAUTH_CERTIFICATE: if (m_vpnData.contains(KYVPN_CA_KEY)) { vpnConfig.m_caCertificate = m_vpnData.value(KYVPN_CA_KEY); } if (m_vpnData.contains(KYVPN_CERT_KEY)) { vpnConfig.m_userCertificate = m_vpnData.value(KYVPN_CERT_KEY); } if (m_vpnData.contains(KYVPN_USERKEY_KEY)) { vpnConfig.m_userKey = m_vpnData.value(KYVPN_USERKEY_KEY); } getCertPasswdAndPolicy(vpnConfig); break; case KYAUTH_PASSWD: if (m_vpnData.contains(KYVPN_CA_KEY)) { vpnConfig.m_caCertificate = m_vpnData.value(KYVPN_CA_KEY); } if (m_vpnData.contains(KYVPN_USERNAME_KEY)) { vpnConfig.m_userName = m_vpnData.value(KYVPN_USERNAME_KEY); } getUsrPasswdAndPolicy(vpnConfig); break; case KYAUTH_CERTIFICATEANDPASSWD: if (m_vpnData.contains(KYVPN_CA_KEY)) { vpnConfig.m_caCertificate = m_vpnData.value(KYVPN_CA_KEY); } if (m_vpnData.contains(KYVPN_CERT_KEY)) { vpnConfig.m_userCertificate = m_vpnData.value(KYVPN_CERT_KEY); } if (m_vpnData.contains(KYVPN_USERKEY_KEY)) { vpnConfig.m_userKey = m_vpnData.value(KYVPN_USERKEY_KEY); } if (m_vpnData.contains(KYVPN_USERNAME_KEY)) { vpnConfig.m_userName = m_vpnData.value(KYVPN_USERNAME_KEY); } getUsrPasswdAndPolicy(vpnConfig); getCertPasswdAndPolicy(vpnConfig); break; case KYAUTH_STATICPASSWD: if (m_vpnData.contains(KYVPN_STATICKEY_KEY)) { vpnConfig.m_staticKey = m_vpnData.value(KYVPN_STATICKEY_KEY); } if (m_vpnData.contains(KYVPN_STATICKEYDIR_KEY)) { vpnConfig.m_vpnKeyDir = m_vpnData.value(KYVPN_STATICKEYDIR_KEY); } if (m_vpnData.contains(KYVPN_LOCALIP_KEY)) { vpnConfig.m_localAddress = m_vpnData.value(KYVPN_LOCALIP_KEY); } if (m_vpnData.contains(KYVPN_REMOTEIP_KEY)) { vpnConfig.m_remoteAddress = m_vpnData.value(KYVPN_REMOTEIP_KEY); } break; default : break; } vpnConfig.m_useAssignPort = false; vpnConfig.m_assignPort.clear(); if (m_vpnData.contains(KYVPN_PORT_KEY)) { vpnConfig.m_useAssignPort = true; vpnConfig.m_assignPort = m_vpnData.value(KYVPN_PORT_KEY); } vpnConfig.m_useRenegSeconds = false; vpnConfig.m_renegSeconds.clear(); if (m_vpnData.contains(KYVPN_RENEGSEC_KEY)) { vpnConfig.m_useRenegSeconds = true; vpnConfig.m_renegSeconds = m_vpnData.value(KYVPN_RENEGSEC_KEY); } vpnConfig.m_useCompress = false; vpnConfig.m_openvpnCompress = KYCOMP2_LZODISABLE; if (m_vpnData.contains(KYVPN_COMPLZO_KEY)) { vpnConfig.m_useCompress = true; if (m_vpnData.value(KYVPN_COMPLZO_KEY) == COMPLZO_LZODISABLE) { vpnConfig.m_openvpnCompress = KYCOMP2_LZODISABLE; } else if (m_vpnData.value(KYVPN_COMPLZO_KEY) == COMPLZO_ADAPTIVE) { vpnConfig.m_openvpnCompress = KYCOMP2_LZOADAPTIVE; } } else if (m_vpnData.contains(KYVPN_COMPRESS_KEY)) { vpnConfig.m_useCompress = true; if (m_vpnData.value(KYVPN_COMPRESS_KEY) == COMPRESS_LZO) { vpnConfig.m_openvpnCompress = KYCOMP2_LZO; } else if (m_vpnData.value(KYVPN_COMPRESS_KEY) == COMPRESS_LZ4) { vpnConfig.m_openvpnCompress = KYCOMP2_LZ4; } else if (m_vpnData.value(KYVPN_COMPRESS_KEY) == COMPRESS_LZ4V2) { vpnConfig.m_openvpnCompress = KYCOMP2_LZ4V2; } else if (m_vpnData.value(KYVPN_COMPRESS_KEY) == KYVPN_YES) { vpnConfig.m_openvpnCompress = KYCOMP2_AUTO; } } vpnConfig.m_useTcpLink = false; if (m_vpnData.contains(KYVPN_PROTOTCP_KEY) && m_vpnData.value(KYVPN_PROTOTCP_KEY) == KYVPN_YES) { vpnConfig.m_useTcpLink = true; } vpnConfig.m_setDevType = false; if (m_vpnData.contains(KYVPN_DEVTYPE_KEY)) { vpnConfig.m_setDevType = true; if (m_vpnData.value(KYVPN_DEVTYPE_KEY) == DEVTYPE_TUN) { vpnConfig.m_devType = KYVIRDEVTYPE_TUN; } else if (m_vpnData.value(KYVPN_DEVTYPE_KEY) == DEVTYPE_TAP) { vpnConfig.m_devType = KYVIRDEVTYPE_TAP; } } vpnConfig.m_setDevName = false; vpnConfig.m_devName.clear(); if (m_vpnData.contains(KYVPN_DEV_KEY)) { vpnConfig.m_setDevName = true; vpnConfig.m_devName = m_vpnData.value(KYVPN_DEV_KEY); } vpnConfig.m_useTunnelMtu = false; vpnConfig.m_tunnelMtu.clear(); if (m_vpnData.contains(KYVPN_TUNNELMTU_KEY)) { vpnConfig.m_useTunnelMtu = true; vpnConfig.m_tunnelMtu = m_vpnData.value(KYVPN_TUNNELMTU_KEY); } vpnConfig.m_useFragmentSize = false; vpnConfig.m_fragmentSize.clear(); if (m_vpnData.contains(KYVPN_FRAGMENTSIZE_KEY)) { vpnConfig.m_useFragmentSize = true; vpnConfig.m_fragmentSize = m_vpnData.value(KYVPN_FRAGMENTSIZE_KEY); } vpnConfig.m_mssfix = false; if (m_vpnData.contains(KYVPN_MSSFIX_KEY) && m_vpnData.value(KYVPN_MSSFIX_KEY) == KYVPN_YES) { vpnConfig.m_mssfix = true; } vpnConfig.m_remoteRandom = false; if (m_vpnData.contains(KYVPN_REMOTERANDOM_KEY) && m_vpnData.value(KYVPN_REMOTERANDOM_KEY) == KYVPN_YES) { vpnConfig.m_remoteRandom = true; } vpnConfig.m_ipv6TunLink = false; if (m_vpnData.contains(KYVPN_TUNIPV6_KEY) && m_vpnData.value(KYVPN_TUNIPV6_KEY) == KYVPN_YES) { vpnConfig.m_ipv6TunLink = true; } vpnConfig.m_setPingCycle = false; vpnConfig.m_pingCycle.clear(); if (m_vpnData.contains(KYVPN_PING_KEY)) { vpnConfig.m_setPingCycle = true; vpnConfig.m_pingCycle = m_vpnData.value(KYVPN_PING_KEY); } vpnConfig.m_usePingMethod = false; vpnConfig.m_pingMethod = KYVPNPING_EXIT; vpnConfig.m_pingMethodTime.clear(); if (m_vpnData.contains(KYVPN_PINGEXIT_KEY)) { vpnConfig.m_usePingMethod = true; vpnConfig.m_pingMethod = KYVPNPING_EXIT; vpnConfig.m_pingMethodTime = m_vpnData.value(KYVPN_PINGEXIT_KEY); } else if (m_vpnData.contains(KYVPN_PINGRESTART_KEY)) { vpnConfig.m_usePingMethod = true; vpnConfig.m_pingMethod = KYVPNPING_RESTART; vpnConfig.m_pingMethodTime = m_vpnData.value(KYVPN_PINGRESTART_KEY); } vpnConfig.m_float = false; if (m_vpnData.contains(KYVPN_FLOAT_KEY) && m_vpnData.value(KYVPN_FLOAT_KEY) == KYVPN_YES) { vpnConfig.m_float = true; } vpnConfig.m_setMaxRoute = false; vpnConfig.m_maxRoute.clear(); if (m_vpnData.contains(KYVPN_MAXROUTES_KEY)) { vpnConfig.m_setMaxRoute = true; vpnConfig.m_maxRoute = m_vpnData.value(KYVPN_MAXROUTES_KEY); } vpnConfig.m_checkServerCa = KYCHECKSERVER_NONE; vpnConfig.m_verifyName.clear(); if (m_vpnData.contains(KYVPN_VERIFYX509NAME_KEY)) { QString nameValue = m_vpnData.value(KYVPN_VERIFYX509NAME_KEY); QString nameType = nameValue.section(":", 0, 0); if (nameType == X509NAME_SUBJECT) { vpnConfig.m_checkServerCa = KYCHECKSERVER_ENTIRETHEME; } else if (nameType == X509NAME_NAME) { vpnConfig.m_checkServerCa = KYCHECKSERVER_ENTIRENAME; } else if (nameType == X509NAME_NAMEPREFIX) { vpnConfig.m_checkServerCa = KYCHECKSERVER_PRENAME; } vpnConfig.m_verifyName = nameValue.section(":", 1, 1); } vpnConfig.m_useRemoteCertTls = false; vpnConfig.m_remoteCertType = KYVPNCERT_SERVER; if (m_vpnData.contains(KYVPN_REMOTECERTTLS_KEY)) { vpnConfig.m_useRemoteCertTls = true; if (m_vpnData.value(KYVPN_REMOTECERTTLS_KEY) == KYVPN_SERVER) { vpnConfig.m_remoteCertType = KYVPNCERT_SERVER; } else if (m_vpnData.value(KYVPN_REMOTECERTTLS_KEY) == KYVPN_CLIENT) { vpnConfig.m_remoteCertType = KYVPNCERT_CLIENT; } } vpnConfig.m_useNsCertTls = false; vpnConfig.m_nsCertType = KYVPNCERT_SERVER; if (m_vpnData.contains(KYVPN_NSCERTTYPE_KEY)) { vpnConfig.m_useNsCertTls = true; if (m_vpnData.value(KYVPN_NSCERTTYPE_KEY) == KYVPN_SERVER) { vpnConfig.m_nsCertType = KYVPNCERT_SERVER; } else if (m_vpnData.value(KYVPN_NSCERTTYPE_KEY) == KYVPN_CLIENT) { vpnConfig.m_nsCertType = KYVPNCERT_CLIENT; } } vpnConfig.m_vpnTlsMode = KYVPNTLS_NONE; if (m_vpnData.contains(KYVPN_TA_KEY)) { vpnConfig.m_vpnTlsMode = KYVPNTLS_AUTHENTICATION; vpnConfig.m_vpnKeyFile = m_vpnData.value(KYVPN_TA_KEY); } else if (m_vpnData.contains(KYVPN_TLSCRYPT_KEY)) { vpnConfig.m_vpnTlsMode = KYVPNTLS_CRYPT; vpnConfig.m_vpnKeyFile = m_vpnData.value(KYVPN_TLSCRYPT_KEY); } vpnConfig.m_vpnTlsTaDir.clear(); if (m_vpnData.contains(KYVPN_TADIR_KEY)) { vpnConfig.m_vpnTlsTaDir = m_vpnData.value(KYVPN_TADIR_KEY); } vpnConfig.m_vpnProxyType = KYVPNPROXY_NONE; vpnConfig.m_vpnProxyServer.clear(); vpnConfig.m_vpnProxyPort.clear(); vpnConfig.m_vpnProxyRetry = false; vpnConfig.m_vpnProxyName.clear(); if (m_vpnData.contains(KYVPN_PROXYTYPE_KEY)) { if (m_vpnData.value(KYVPN_PROXYTYPE_KEY) == PROXYTYPE_HTTP) { vpnConfig.m_vpnProxyType = KYVPNPROXY_HTTP; } else if (m_vpnData.value(KYVPN_PROXYTYPE_KEY) == PROXYTYPE_SOCKS) { vpnConfig.m_vpnProxyType = KYVPNPROXY_SOCKS; } if (m_vpnData.contains(KYVPN_PROXYSERVER_KEY)) { vpnConfig.m_vpnProxyServer = m_vpnData.value(KYVPN_PROXYSERVER_KEY); } if (m_vpnData.contains(KYVPN_PROXYPORT_KEY)) { vpnConfig.m_vpnProxyPort = m_vpnData.value(KYVPN_PROXYPORT_KEY); } if (m_vpnData.contains(KYVPN_PROXYRETRY_KEY) && m_vpnData.value(KYVPN_PROXYRETRY_KEY) == KYVPN_YES) { vpnConfig.m_vpnProxyRetry = true; } if (m_vpnData.contains(KYVPN_HTTPPROXYUSERNAME_KEY)) { vpnConfig.m_vpnProxyName = m_vpnData.value(KYVPN_HTTPPROXYUSERNAME_KEY); } if (m_vpnData.contains(KYVPN_HTTPPROXYPASSWDFLAGS_KEY)) { switch (m_vpnData.value(KYVPN_HTTPPROXYPASSWDFLAGS_KEY).toInt()) { case 1: vpnConfig.m_vpnProxyPasswdPolicy = KYPASSWD_FORTHISUSER; break; case 2: vpnConfig.m_vpnProxyPasswdPolicy = KYPASSWD_ASKEVERYTIME; break; case 4: vpnConfig.m_vpnProxyPasswdPolicy = KYPASSWD_ISNOTREQUIRED; break; default : break; } } if (m_vpnSecrets.contains(KYVPN_HTTPPROXYPASSWD_KEY)) { vpnConfig.m_vpnProxyPasswd = m_vpnSecrets.value(KYVPN_HTTPPROXYPASSWD_KEY); } } vpnConfig.m_useKeysize = false; vpnConfig.m_keySize.clear(); vpnConfig.m_hmacAuthMethod = KYHMACAUTH_DEFAULT; if (m_vpnData.contains(KYVPN_KEYSIZE_KEY)) { vpnConfig.m_useKeysize = true; vpnConfig.m_keySize = m_vpnData.value(KYVPN_KEYSIZE_KEY); if (m_vpnData.contains(KYVPN_AUTH_KEY)) { vpnConfig.m_hmacAuthMethod = getHmacAuthMethod(m_vpnData.value(KYVPN_AUTH_KEY)); } } } void KyVpnConnectOperation::setOpenvpnConfig(KyVpnConfig &vpnConfig) { m_vpnData.insert(KYVPN_CONNECTIONTYPE_KEY, m_authMethodMap.key(vpnConfig.m_authMethod)); if (!vpnConfig.m_gateway.isEmpty()) { m_vpnData.insert(KYVPN_REMOTE_KEY, vpnConfig.m_gateway); } switch (vpnConfig.m_authMethod) { case KYAUTH_CERTIFICATE: if (!vpnConfig.m_caCertificate.isEmpty()) { m_vpnData.insert(KYVPN_CA_KEY, vpnConfig.m_caCertificate); } if (!vpnConfig.m_userCertificate.isEmpty()) { m_vpnData.insert(KYVPN_CERT_KEY, vpnConfig.m_userCertificate); } if (!vpnConfig.m_userKey.isEmpty()) { m_vpnData.insert(KYVPN_USERKEY_KEY, vpnConfig.m_userKey); } setCertPasswdAndPolicy(vpnConfig); break; case KYAUTH_PASSWD: if (!vpnConfig.m_caCertificate.isEmpty()) { m_vpnData.insert(KYVPN_CA_KEY, vpnConfig.m_caCertificate); } if (!vpnConfig.m_userName.isEmpty()) { m_vpnData.insert(KYVPN_USERNAME_KEY, vpnConfig.m_userName); } setUsrPasswdAndPolicy(vpnConfig); break; case KYAUTH_CERTIFICATEANDPASSWD: if (!vpnConfig.m_caCertificate.isEmpty()) { m_vpnData.insert(KYVPN_CA_KEY, vpnConfig.m_caCertificate); } if (!vpnConfig.m_userCertificate.isEmpty()) { m_vpnData.insert(KYVPN_CERT_KEY, vpnConfig.m_userCertificate); } if (!vpnConfig.m_userKey.isEmpty()) { m_vpnData.insert(KYVPN_USERKEY_KEY, vpnConfig.m_userKey); } if (!vpnConfig.m_userName.isEmpty()) { m_vpnData.insert(KYVPN_USERNAME_KEY, vpnConfig.m_userName); } setUsrPasswdAndPolicy(vpnConfig); setCertPasswdAndPolicy(vpnConfig); break; case KYAUTH_STATICPASSWD: if (!vpnConfig.m_staticKey.isEmpty()) { m_vpnData.insert(KYVPN_STATICKEY_KEY, vpnConfig.m_staticKey); } if (!vpnConfig.m_vpnKeyDir.isEmpty()) { m_vpnData.insert(KYVPN_STATICKEYDIR_KEY, vpnConfig.m_vpnKeyDir); } if (!vpnConfig.m_localAddress.isEmpty()) { m_vpnData.insert(KYVPN_LOCALIP_KEY, vpnConfig.m_localAddress); } if (!vpnConfig.m_remoteAddress.isEmpty()) { m_vpnData.insert(KYVPN_REMOTEIP_KEY, vpnConfig.m_remoteAddress); } break; default : break; } if (vpnConfig.m_useAssignPort && !vpnConfig.m_assignPort.isEmpty()) { m_vpnData.insert(KYVPN_PORT_KEY, vpnConfig.m_assignPort); } if (vpnConfig.m_useRenegSeconds && !vpnConfig.m_renegSeconds.isEmpty()) { m_vpnData.insert(KYVPN_RENEGSEC_KEY, vpnConfig.m_renegSeconds); } if (vpnConfig.m_useCompress) { switch (vpnConfig.m_openvpnCompress) { case KYCOMP2_LZODISABLE: m_vpnData.insert(KYVPN_COMPLZO_KEY, COMPLZO_LZODISABLE); break; case KYCOMP2_LZOADAPTIVE: m_vpnData.insert(KYVPN_COMPLZO_KEY, COMPLZO_ADAPTIVE); break; case KYCOMP2_LZO: m_vpnData.insert(KYVPN_COMPRESS_KEY, COMPRESS_LZO); break; case KYCOMP2_LZ4: m_vpnData.insert(KYVPN_COMPRESS_KEY, COMPRESS_LZ4); break; case KYCOMP2_LZ4V2: m_vpnData.insert(KYVPN_COMPRESS_KEY, COMPRESS_LZ4V2); break; case KYCOMP2_AUTO: m_vpnData.insert(KYVPN_COMPRESS_KEY, KYVPN_YES); break; } } if (vpnConfig.m_useTcpLink) { m_vpnData.insert(KYVPN_PROTOTCP_KEY, KYVPN_YES); } if (vpnConfig.m_setDevType) { switch (vpnConfig.m_devType) { case KYVIRDEVTYPE_TUN: m_vpnData.insert(KYVPN_DEVTYPE_KEY, DEVTYPE_TUN); break; case KYVIRDEVTYPE_TAP: m_vpnData.insert(KYVPN_DEVTYPE_KEY, DEVTYPE_TAP); break; default : break; } } if (vpnConfig.m_setDevName && !vpnConfig.m_devName.isEmpty()) { m_vpnData.insert(KYVPN_DEV_KEY, vpnConfig.m_devName); } if (vpnConfig.m_useTunnelMtu && !vpnConfig.m_tunnelMtu.isEmpty()) { m_vpnData.insert(KYVPN_TUNNELMTU_KEY, vpnConfig.m_tunnelMtu); } if (vpnConfig.m_useFragmentSize && !vpnConfig.m_fragmentSize.isEmpty()) { m_vpnData.insert(KYVPN_FRAGMENTSIZE_KEY, vpnConfig.m_fragmentSize); } if (vpnConfig.m_mssfix) { m_vpnData.insert(KYVPN_MSSFIX_KEY, KYVPN_YES); } if (vpnConfig.m_remoteRandom) { m_vpnData.insert(KYVPN_REMOTERANDOM_KEY, KYVPN_YES); } if (vpnConfig.m_ipv6TunLink) { m_vpnData.insert(KYVPN_TUNIPV6_KEY, KYVPN_YES); } if (vpnConfig.m_setPingCycle && !vpnConfig.m_pingCycle.isEmpty()) { m_vpnData.insert(KYVPN_PING_KEY, vpnConfig.m_pingCycle); } if (vpnConfig.m_usePingMethod) { switch (vpnConfig.m_pingMethod) { case KYVPNPING_EXIT: m_vpnData.insert(KYVPN_PINGEXIT_KEY, vpnConfig.m_pingMethodTime); break; case KYVPNPING_RESTART: m_vpnData.insert(KYVPN_PINGRESTART_KEY, vpnConfig.m_pingMethodTime); break; default : break; } } if (vpnConfig.m_float) { m_vpnData.insert(KYVPN_FLOAT_KEY, KYVPN_YES); } if (vpnConfig.m_setMaxRoute && !vpnConfig.m_maxRoute.isEmpty()) { m_vpnData.insert(KYVPN_MAXROUTES_KEY, vpnConfig.m_maxRoute); } if (vpnConfig.m_checkServerCa != KYCHECKSERVER_NONE && !vpnConfig.m_verifyName.isEmpty()) { QString nameStr; nameStr.clear(); switch (vpnConfig.m_checkServerCa) { case KYCHECKSERVER_ENTIRETHEME: nameStr = X509NAME_SUBJECT + QString(":") + vpnConfig.m_verifyName; break; case KYCHECKSERVER_ENTIRENAME: nameStr = X509NAME_NAME + QString(":") + vpnConfig.m_verifyName; break; case KYCHECKSERVER_PRENAME: nameStr = X509NAME_NAMEPREFIX + QString(":") + vpnConfig.m_verifyName; break; default : break; } m_vpnData.insert(KYVPN_VERIFYX509NAME_KEY, nameStr); } if (vpnConfig.m_useRemoteCertTls) { switch (vpnConfig.m_remoteCertType) { case KYVPNCERT_SERVER: m_vpnData.insert(KYVPN_REMOTECERTTLS_KEY, KYVPN_SERVER); break; case KYVPNCERT_CLIENT: m_vpnData.insert(KYVPN_REMOTECERTTLS_KEY, KYVPN_CLIENT); break; default : break; } } if (vpnConfig.m_useNsCertTls) { switch (vpnConfig.m_nsCertType) { case KYVPNCERT_SERVER: m_vpnData.insert(KYVPN_NSCERTTYPE_KEY, KYVPN_SERVER); break; case KYVPNCERT_CLIENT: m_vpnData.insert(KYVPN_NSCERTTYPE_KEY, KYVPN_CLIENT); break; default : break; } } switch (vpnConfig.m_vpnTlsMode) { case KYVPNTLS_AUTHENTICATION: m_vpnData.insert(KYVPN_TA_KEY, vpnConfig.m_vpnKeyFile); break; case KYVPNTLS_CRYPT: m_vpnData.insert(KYVPN_TLSCRYPT_KEY, vpnConfig.m_vpnKeyFile); break; default : break; } if (!vpnConfig.m_vpnTlsTaDir.isEmpty() && vpnConfig.m_vpnTlsTaDir != "None") { m_vpnData.insert(KYVPN_TADIR_KEY, vpnConfig.m_vpnTlsTaDir); } switch (vpnConfig.m_vpnProxyType) { case KYVPNPROXY_HTTP: m_vpnData.insert(KYVPN_PROXYTYPE_KEY, PROXYTYPE_HTTP); break; case KYVPNPROXY_SOCKS: m_vpnData.insert(KYVPN_PROXYTYPE_KEY, PROXYTYPE_SOCKS); break; default : break; } if (!vpnConfig.m_vpnProxyServer.isEmpty()) { m_vpnData.insert(KYVPN_PROXYSERVER_KEY, vpnConfig.m_vpnProxyServer); } if (!vpnConfig.m_vpnProxyPort.isEmpty()) { m_vpnData.insert(KYVPN_PROXYPORT_KEY, vpnConfig.m_vpnProxyPort); } if (vpnConfig.m_vpnProxyRetry) { m_vpnData.insert(KYVPN_PROXYRETRY_KEY, KYVPN_YES); } if (!vpnConfig.m_vpnProxyName.isEmpty()) { m_vpnData.insert(KYVPN_HTTPPROXYUSERNAME_KEY, vpnConfig.m_vpnProxyName); } vpnConfig.m_vpnProxyPasswdPolicy = KYPASSWD_FORALLUSER; if (vpnConfig.m_vpnProxyPasswdPolicy == KYPASSWD_FORALLUSER && !vpnConfig.m_vpnProxyPasswd.isEmpty()) { m_vpnData.insert(KYVPN_HTTPPROXYPASSWDFLAGS_KEY, "0"); m_vpnSecrets.insert(KYVPN_HTTPPROXYPASSWD_KEY, vpnConfig.m_vpnProxyPasswd); } if (vpnConfig.m_useKeysize) { m_vpnData.insert(KYVPN_KEYSIZE_KEY, vpnConfig.m_keySize); m_vpnData.insert(KYVPN_AUTH_KEY, m_hmacMap.key(vpnConfig.m_hmacAuthMethod)); } } KyHMACAuthMethod KyVpnConnectOperation::getHmacAuthMethod(const QString method) { if (m_hmacMap.contains(method)) { return m_hmacMap.value(method); } return KYHMACAUTH_DEFAULT; } KyAuthMethod KyVpnConnectOperation::getAuthMethod(const QString method) { if (m_authMethodMap.contains(method)) { return m_authMethodMap.value(method); } return KYAUTH_ERROR; } void KyVpnConnectOperation::getUsrPasswdAndPolicy(KyVpnConfig &vpnConfig) { vpnConfig.m_userPasswd.clear(); vpnConfig.m_passwdPolicy = KYPASSWD_ASKEVERYTIME; if (m_vpnData.contains(KYVPN_PASSWDFLAGS_KEY)) { switch (m_vpnData.value(KYVPN_PASSWDFLAGS_KEY).toInt()) { case 0: vpnConfig.m_passwdPolicy = KYPASSWD_FORALLUSER; if (m_vpnSecrets.contains(KYVPN_PASSWD_KEY)) { vpnConfig.m_userPasswd = m_vpnSecrets.value(KYVPN_PASSWD_KEY); } break; case 1: vpnConfig.m_passwdPolicy = KYPASSWD_FORTHISUSER; break; case 2: vpnConfig.m_passwdPolicy = KYPASSWD_ASKEVERYTIME; break; case 4: vpnConfig.m_passwdPolicy = KYPASSWD_ISNOTREQUIRED; break; default : break; } } } void KyVpnConnectOperation::setUsrPasswdAndPolicy(KyVpnConfig &vpnConfig) { switch (vpnConfig.m_passwdPolicy) { case KYPASSWD_FORTHISUSER: m_vpnData.insert(KYVPN_PASSWDFLAGS_KEY, "1"); break ; case KYPASSWD_FORALLUSER: m_vpnData.insert(KYVPN_PASSWDFLAGS_KEY, "0"); break ; case KYPASSWD_ASKEVERYTIME: m_vpnData.insert(KYVPN_PASSWDFLAGS_KEY, "2"); break ; case KYPASSWD_ISNOTREQUIRED: m_vpnData.insert(KYVPN_PASSWDFLAGS_KEY, "4"); break ; default : break; } if (vpnConfig.m_passwdPolicy == KYPASSWD_FORALLUSER && !vpnConfig.m_userPasswd.isEmpty()) { m_vpnSecrets.insert(KYVPN_PASSWD_KEY, vpnConfig.m_userPasswd); } } void KyVpnConnectOperation::getCertPasswdAndPolicy(KyVpnConfig &vpnConfig) { vpnConfig.m_privatePasswd.clear(); vpnConfig.m_privatePasswdPolicy = KYPASSWD_ASKEVERYTIME; if (m_vpnData.contains(KYVPN_CERTPASSWDFLAGS_KEY)) { switch (m_vpnData.value(KYVPN_CERTPASSWDFLAGS_KEY).toInt()) { case 0: vpnConfig.m_privatePasswdPolicy = KYPASSWD_FORALLUSER; if (m_vpnSecrets.contains(KYVPN_CERTPASSWD_KEY)) { vpnConfig.m_privatePasswd = m_vpnSecrets.value(KYVPN_CERTPASSWD_KEY); } break; case 1: vpnConfig.m_privatePasswdPolicy = KYPASSWD_FORTHISUSER; break; case 2: vpnConfig.m_privatePasswdPolicy = KYPASSWD_ASKEVERYTIME; break; case 4: vpnConfig.m_privatePasswdPolicy = KYPASSWD_ISNOTREQUIRED; break; default : break; } } } void KyVpnConnectOperation::setCertPasswdAndPolicy(KyVpnConfig &vpnConfig) { switch (vpnConfig.m_privatePasswdPolicy) { case KYPASSWD_FORTHISUSER: m_vpnData.insert(KYVPN_CERTPASSWDFLAGS_KEY, "1"); break ; case KYPASSWD_FORALLUSER: m_vpnData.insert(KYVPN_CERTPASSWDFLAGS_KEY, "0"); break ; case KYPASSWD_ASKEVERYTIME: m_vpnData.insert(KYVPN_CERTPASSWDFLAGS_KEY, "2"); break ; case KYPASSWD_ISNOTREQUIRED: m_vpnData.insert(KYVPN_CERTPASSWDFLAGS_KEY, "4"); break ; default : break; } if (vpnConfig.m_privatePasswdPolicy == KYPASSWD_FORALLUSER && !vpnConfig.m_privatePasswd.isEmpty()) { m_vpnSecrets.insert(KYVPN_CERTPASSWD_KEY, vpnConfig.m_privatePasswd); } } void KyVpnConnectOperation::activateVpnConnection(const QString connectUuid) { QString connectPath = ""; QString deviceIdentifier = ""; QString connectName = ""; QString specificObject = ""; NetworkManager::Connection::Ptr connectPtr = nullptr; qDebug()<<"it will activate vpn connect"<settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Bond != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Bridge != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Vlan != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Team != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::IpTunnel != connectPtr->settings()->connectionType() && NetworkManager::ConnectionSettings::ConnectionType::Wired != connectPtr->settings()->connectionType()) { QString errorMessage = tr("the connect type is") + NetworkManager::ConnectionSettings::typeAsString(connectPtr->settings()->connectionType()) + tr(", but it is not vpn"); qWarning()<path(); connectName = connectPtr->name(); specificObject = deviceIdentifier = QStringLiteral("/"); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::activateConnection(connectPath, deviceIdentifier, specificObject), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this, connectName] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("activate vpn connection failed: ") + watcher->error().message(); qWarning()<activateConnectionError(errorMessage); } else { qWarning()<<"active vpn connect complete."; } watcher->deleteLater(); }); return; } void KyVpnConnectOperation::deactivateVpnConnection(const QString activeConnectName, const QString &activeConnectUuid) { qDebug()<<"deactivetate connect name"< #include #include "kylinutil.h" #define SIGNAL_DELAY 80000 #define EMIT_DELAY 10000 #define LOG_FLAG "[KyNetworkResourceManager]" QString enumToQstring(NetworkManager::AccessPoint::Capabilities cap, NetworkManager::AccessPoint::WpaFlags wpa_flags,NetworkManager::AccessPoint::WpaFlags rsn_flags) { QString out; if ( (cap & NM_802_11_AP_FLAGS_PRIVACY) && (wpa_flags == NM_802_11_AP_SEC_NONE) && (rsn_flags == NM_802_11_AP_SEC_NONE)) { out += "WEP "; } if (wpa_flags != NM_802_11_AP_SEC_NONE) { out += "WPA1 "; } if ((rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK) || (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { out += "WPA2 "; } if (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_SAE) { out += "WPA3 "; } if ( (wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X) || (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { out += "802.1X "; } return out; } KyNetworkResourceManager* KyNetworkResourceManager::m_pInstance = nullptr; KyNetworkResourceManager* KyNetworkResourceManager::getInstance() { if (m_pInstance == NULL) { m_pInstance = new KyNetworkResourceManager(); } return m_pInstance; } void KyNetworkResourceManager::Release() { if (m_pInstance != NULL) { delete m_pInstance; m_pInstance = NULL; } } KyNetworkResourceManager::KyNetworkResourceManager(QObject *parent) : QObject(parent) { qRegisterMetaType("NetworkManager::ActiveConnection::State"); qRegisterMetaType("NetworkManager::Connectivity"); qRegisterMetaType("NetworkManager::ActiveConnection::Reason"); qRegisterMetaType("NetworkManager::Device::Type"); qRegisterMetaType("NetworkManager::Device::State"); qRegisterMetaType("NetworkManager::Device::StateChangeReason"); qRegisterMetaType("NetworkManager::VpnConnection::State"); qRegisterMetaType("NetworkManager::VpnConnection::StateChangeReason"); QDBusConnection::systemBus().connect(QString("org.freedesktop.DBus"), QString("/org/freedesktop/DBus"), QString("org.freedesktop.DBus"), QString("NameOwnerChanged"), this, SLOT(onServiceAppear(QString,QString,QString))); QDBusConnection::systemBus().connect(QString("org.freedesktop.NetworkManager"), QString("/org/freedesktop/NetworkManager"), QString("org.freedesktop.NetworkManager"), QString("PropertiesChanged"), this, SLOT(onPropertiesChanged(QVariantMap))); } void KyNetworkResourceManager::onInitNetwork() { insertActiveConnections(); insertConnections(); insertDevices(); insertWifiNetworks(); //initialize NetworkManager signals connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceAdded, this, &KyNetworkResourceManager::onDeviceAdded); connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceRemoved, this, &KyNetworkResourceManager::onDeviceRemoved); connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionAdded, this, &KyNetworkResourceManager::onActiveConnectionAdded); connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionRemoved, this, &KyNetworkResourceManager::onActiveConnectionRemoved); connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionAdded, this, &KyNetworkResourceManager::onConnectionAdded); connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionRemoved, this, static_cast(&KyNetworkResourceManager::onConnectionRemoved)); connect(NetworkManager::notifier(), &NetworkManager::Notifier::connectivityChanged, this, &KyNetworkResourceManager::connectivityChanged); //todo wifi开关信号 connect(NetworkManager::notifier(), &NetworkManager::Notifier::wirelessEnabledChanged, this, &KyNetworkResourceManager::wifiEnabledChanged); // Note: the connectionRemoved is never emitted in case network-manager service stop, // we need remove the connections manually. connect(NetworkManager::notifier(), &NetworkManager::Notifier::serviceDisappeared, this, &KyNetworkResourceManager::clearConnections); connect(NetworkManager::notifier(), &NetworkManager::Notifier::serviceDisappeared, this, &KyNetworkResourceManager::clearWifiNetworks); qDebug() <<"[KyNetworkResourceManager]" << "active connections:" << m_activeConns.size() << "connections:" << m_connections.size() << "network device:" << m_devices.size(); m_initFinished = true; return; } KyNetworkResourceManager::~KyNetworkResourceManager() { } void KyNetworkResourceManager::removeActiveConnection(int pos) { //active connections signals NetworkManager::ActiveConnection::Ptr conn = m_activeConns.takeAt(pos); conn->disconnect(this); } void KyNetworkResourceManager::clearActiveConnections() { while (0 < m_activeConns.size()) removeActiveConnection(0); } void KyNetworkResourceManager::addActiveConnection(NetworkManager::ActiveConnection::Ptr conn) { m_activeConns.push_back(conn); #if 0 connect(conn.data(), &NetworkManager::ActiveConnection::connectionChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(conn.data(), &NetworkManager::ActiveConnection::default4Changed, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(conn.data(), &NetworkManager::ActiveConnection::default6Changed, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(conn.data(), &NetworkManager::ActiveConnection::dhcp4ConfigChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(conn.data(), &NetworkManager::ActiveConnection::dhcp6ConfigChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(conn.data(), &NetworkManager::ActiveConnection::ipV4ConfigChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(conn.data(), &NetworkManager::ActiveConnection::ipV6ConfigChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(conn.data(), &NetworkManager::ActiveConnection::idChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(conn.data(), &NetworkManager::ActiveConnection::typeChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(conn.data(), &NetworkManager::ActiveConnection::masterChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(conn.data(), &NetworkManager::ActiveConnection::specificObjectChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); #endif //connect(conn.data(), &NetworkManager::ActiveConnection::stateChangedReason, this, &KyNetworkResourceManager::onActiveConnectionChangedReason); connect(conn.data(), &NetworkManager::ActiveConnection::stateChanged, this, &KyNetworkResourceManager::onActiveConnectionChanged); #if 0 connect(conn.data(), &NetworkManager::ActiveConnection::vpnChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(conn.data(), &NetworkManager::ActiveConnection::uuidChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(conn.data(), &NetworkManager::ActiveConnection::devicesChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); #endif if (conn->vpn()) { connect(qobject_cast(conn.data()), &NetworkManager::VpnConnection::bannerChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); connect(qobject_cast(conn.data()), &NetworkManager::VpnConnection::stateChanged, this, &KyNetworkResourceManager::onVpnActiveConnectChanagedReason); } } void KyNetworkResourceManager::insertActiveConnections() { for (auto const & conn : NetworkManager::activeConnections()) { if (conn.isNull()) { continue; } addActiveConnection(conn); } } void KyNetworkResourceManager::removeConnection(int pos) { //connections signals QString path = m_connections.at(pos)->path(); NetworkManager::Connection::Ptr conn = m_connections.takeAt(pos); conn->disconnect(this); Q_EMIT connectionRemove(path); } void KyNetworkResourceManager::clearConnections() { while (0 < m_connections.size()) { removeConnection(0); } } void KyNetworkResourceManager::addConnection(NetworkManager::Connection::Ptr conn) { m_connections.push_back(conn); //connections signals connect(conn.data(), &NetworkManager::Connection::updated, this, &KyNetworkResourceManager::onConnectionUpdated); connect(conn.data(), &NetworkManager::Connection::removed, this, &KyNetworkResourceManager::onConnectionRemoved); } void KyNetworkResourceManager::insertConnections() { for (auto const & connectPtr : NetworkManager::listConnections()) { if (connectPtr.isNull()) { continue; } if (connectPtr->name().isEmpty() || connectPtr->uuid().isEmpty()) { qWarning() <<"[KyNetworkResourceManager]" << " the name of connection is empty."; continue; } addConnection(connectPtr); } return; } void KyNetworkResourceManager::removeDevice(int pos) { //connections signals NetworkManager::Device::Ptr device = m_devices.takeAt(pos); QDBusConnection::systemBus().disconnect(QString("org.freedesktop.NetworkManager"), device.data()->uni(), QString("org.freedesktop.NetworkManager.Device"), QString("AcdIpProbed"), this, SIGNAL(needShowDesktop(QString))); device->disconnect(this); } void KyNetworkResourceManager::clearDevices() { while (0 < m_devices.size()) removeDevice(0); } void KyNetworkResourceManager::addDevice(NetworkManager::Device::Ptr device) { m_devices.push_back(device); //device signals #if 0 //connect(device.data(), &NetworkManager::Device::stateChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::activeConnectionChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::autoconnectChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::availableConnectionChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::availableConnectionAppeared, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::availableConnectionDisappeared, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::capabilitiesChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::dhcp4ConfigChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::dhcp6ConfigChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::driverChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::driverVersionChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::firmwareMissingChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::firmwareVersionChanged, this, &KyNetworkResourceManager::onDeviceUpdated); #endif connect(device.data(), &NetworkManager::Device::activeConnectionChanged, this, &KyNetworkResourceManager::onDeviceActiveChanage); connect(device.data(), &NetworkManager::Device::interfaceNameChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::managedChanged, this, &KyNetworkResourceManager::onDeviceManagedChange); #if 0 connect(device.data(), &NetworkManager::Device::ipV4AddressChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::ipV4ConfigChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::ipV6ConfigChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::ipInterfaceChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::physicalPortIdChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::mtuChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::nmPluginMissingChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::meteredChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::connectionStateChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::stateReasonChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::stateChanged, this, &KyNetworkResourceManager::onDeviceStateChanged); connect(device.data(), &NetworkManager::Device::udiChanged, this, &KyNetworkResourceManager::onDeviceUpdated); #endif switch (device->type()) { case NetworkManager::Device::Ethernet: connect(qobject_cast(device.data()), &NetworkManager::WiredDevice::bitRateChanged, this, &KyNetworkResourceManager::onDeviceBitRateChanage); connect(qobject_cast(device.data()), &NetworkManager::WiredDevice::carrierChanged, this, &KyNetworkResourceManager::onDeviceCarrierChanage); connect(qobject_cast(device.data()), &NetworkManager::WiredDevice::hardwareAddressChanged, this, &KyNetworkResourceManager::onDeviceMacAddressChanage); connect(device.data(), &NetworkManager::Device::stateChanged, this, &KyNetworkResourceManager::stateChanged); // connect(qobject_cast(device.data()), &NetworkManager::WiredDevice::permanentHardwareAddressChanged, this, &KyNetworkResourceManager::onDeviceUpdated); break; case NetworkManager::Device::Wifi: #if 0 connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::bitRateChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::activeAccessPointChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::modeChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::wirelessCapabilitiesChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::hardwareAddressChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::permanentHardwareAddressChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::wirelessPropertiesChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::accessPointAppeared, this, &KyNetworkResourceManager::onDeviceUpdated); connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::accessPointDisappeared, this, &KyNetworkResourceManager::onDeviceUpdated); #endif connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::networkAppeared, this, &KyNetworkResourceManager::onWifiNetworkAppeared); connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::networkDisappeared, this, &KyNetworkResourceManager::onWifiNetworkDisappeared); connect(device.data(), &NetworkManager::Device::stateChanged, this, &KyNetworkResourceManager::stateChanged); break; default: //TODO: other device types! break; } QDBusConnection::systemBus().connect(QString("org.freedesktop.NetworkManager"), device.data()->uni(), QString("org.freedesktop.NetworkManager.Device"), QString("AcdIpProbed"), this, SIGNAL(needShowDesktop(QString))); } void KyNetworkResourceManager::insertDevices() { for (auto const & device : NetworkManager::networkInterfaces()) { if (device.isNull()) { continue; } addDevice(device); } return; } void KyNetworkResourceManager::removeWifiNetwork(int pos) { //network signals NetworkManager::WirelessNetwork::Ptr net = m_wifiNets.takeAt(pos); net->disconnect(this); } void KyNetworkResourceManager::clearWifiNetworks() { while (0 < m_wifiNets.size()) removeWifiNetwork(0); } void KyNetworkResourceManager::addWifiNetwork(NetworkManager::WirelessNetwork::Ptr net) { m_wifiNets.push_back(net); //device signals connect(net.data(), &NetworkManager::WirelessNetwork::signalStrengthChanged, this, &KyNetworkResourceManager::onUpdateWirelessNet); connect(net.data(), &NetworkManager::WirelessNetwork::referenceAccessPointChanged, this, &KyNetworkResourceManager::onUpdateWirelessNet); connect(net.data(), &NetworkManager::WirelessNetwork::referenceAccessPointChanged, this, &KyNetworkResourceManager::onReferenceAccessPointChanged); connect(net.data(), &NetworkManager::WirelessNetwork::disappeared, this, &KyNetworkResourceManager::onUpdateWirelessNet); connect(net->referenceAccessPoint().data(), &NetworkManager::AccessPoint::wpaFlagsChanged, this, &KyNetworkResourceManager::onWifiNetworkSecuChang, Qt::UniqueConnection); connect(net->referenceAccessPoint().data(), &NetworkManager::AccessPoint::rsnFlagsChanged, this, &KyNetworkResourceManager::onWifiNetworkSecuChang, Qt::UniqueConnection); } void KyNetworkResourceManager::insertWifiNetworks() { for (auto const & device : m_devices) { if (device.isNull()) { continue; } if (NetworkManager::Device::Wifi == device->type()) { NetworkManager::WirelessDevice::Ptr w_dev = device.objectCast(); for (auto const & net : w_dev->networks()) { if (!net.isNull()) { addWifiNetwork(net); Q_EMIT wifiNetworkAdded(device->interfaceName(),net->ssid()); } } } } } NetworkManager::ActiveConnection::Ptr KyNetworkResourceManager::findActiveConnection(QString const & path) { auto i = std::find_if(m_activeConns.cbegin(), m_activeConns.cend(), [&path] (NetworkManager::ActiveConnection::Ptr const & conn) -> bool { return conn->path() == path; }); return m_activeConns.cend() == i ? NetworkManager::ActiveConnection::Ptr{} : *i; } template NetworkManager::Device::Ptr KyNetworkResourceManager::findDevice(Predicate const & pred) { auto i = std::find_if(m_devices.cbegin(), m_devices.cend(), pred); return m_devices.cend() == i ? NetworkManager::Device::Ptr{} : *i; } NetworkManager::Device::Ptr KyNetworkResourceManager::findDeviceUni(QString const & uni) { return findDevice([&uni] (NetworkManager::Device::Ptr const & dev) { return dev->uni() == uni; }); } NetworkManager::Device::Ptr KyNetworkResourceManager::findDeviceInterface(QString const & interfaceName) { return findDevice([&interfaceName] (NetworkManager::Device::Ptr const & dev) { return dev->interfaceName() == interfaceName; }); } NetworkManager::WirelessNetwork::Ptr KyNetworkResourceManager::findWifiNetwork(QString const & ssid, QString const & devUni) { auto i = std::find_if(m_wifiNets.cbegin(), m_wifiNets.cend(), [&ssid, &devUni] (NetworkManager::WirelessNetwork::Ptr const & net) -> bool { return net->ssid() == ssid && net->device() == devUni; }); return m_wifiNets.cend() == i ? NetworkManager::WirelessNetwork::Ptr{} : *i; } NetworkManager::Device::Ptr KyNetworkResourceManager::getNetworkDevice(const QString ifaceName) { NetworkManager::Device::Ptr devicePtr = nullptr; if (ifaceName.isEmpty()) { return nullptr; } for (int index = 0; index < m_devices.size(); ++index) { devicePtr = m_devices.at(index); if (devicePtr.isNull()) { continue; } if (ifaceName == devicePtr->interfaceName()) { return devicePtr; } } return nullptr; } NetworkManager::ActiveConnection::Ptr KyNetworkResourceManager::getActiveConnect(const QString activeConnectUuid) { int index = 0; NetworkManager::ActiveConnection::Ptr activateConnectPtr = nullptr; qDebug()<<"[KyNetworkResourceManager]"<<"get activetate connect with uuid"<< activeConnectUuid; if (activeConnectUuid.isEmpty()) { return nullptr; } for (index = 0; index < m_activeConns.size(); ++index) { activateConnectPtr = m_activeConns.at(index); if (activateConnectPtr.isNull()) { continue; } if (activateConnectPtr->uuid() == activeConnectUuid) { return activateConnectPtr; } } qWarning()<<"[KyNetworkResourceManager]"<<"it can not find the activate connect with uuid" <uuid() == connectUuid) { return connectPtr; } } qWarning() << "[KyNetworkResourceManager]" << "it can not find connect with uuid" << connectUuid; return nullptr; } NetworkManager::WirelessNetwork::Ptr KyNetworkResourceManager::getWifiNetwork(const QString apName) { return nullptr; } NetworkManager::ActiveConnection::List KyNetworkResourceManager::getActiveConnectList() { return m_activeConns; } NetworkManager::Connection::List KyNetworkResourceManager::getConnectList() { return m_connections; } NetworkManager::Device::List KyNetworkResourceManager::getNetworkDeviceList() { return m_devices; } bool KyNetworkResourceManager::isActiveConnection(QString uuid) { int index = 0; NetworkManager::ActiveConnection::Ptr activateConnectPtr = nullptr; if (uuid.isEmpty()) { return false; } for (index = 0; index < m_activeConns.size(); ++index) { activateConnectPtr = m_activeConns.at(index); if (activateConnectPtr.isNull()) { continue; } if (activateConnectPtr->uuid() == uuid && NetworkManager::ActiveConnection::State::Activated == activateConnectPtr->state()) { return true; } } return false; } bool KyNetworkResourceManager::isActivatingConnection(QString uuid) { int index = 0; NetworkManager::ActiveConnection::Ptr activateConnectPtr = nullptr; if (uuid.isEmpty()) { return false; } for (index = 0; index < m_activeConns.size(); ++index) { activateConnectPtr = m_activeConns.at(index); if (activateConnectPtr.isNull()) { continue; } if (activateConnectPtr->uuid() == uuid && NetworkManager::ActiveConnection::State::Activating == activateConnectPtr->state()) { return true; } } return false; } NetworkManager::ActiveConnection::State KyNetworkResourceManager::getActiveConnectionState(const QString uuid) { int index = 0; NetworkManager::ActiveConnection::Ptr activateConnectPtr = nullptr; if (uuid.isEmpty()) { return NetworkManager::ActiveConnection::State::Unknown; } for (index = 0; index < m_activeConns.size(); ++index) { activateConnectPtr = m_activeConns.at(index); if (activateConnectPtr.isNull()) { continue; } if (activateConnectPtr->uuid() == uuid) { return activateConnectPtr->state(); } } return NetworkManager::ActiveConnection::State::Unknown; } void KyNetworkResourceManager::getConnectivity(NetworkManager::Connectivity &connectivity) { connectivity = NetworkManager::connectivity(); } bool KyNetworkResourceManager::NetworkManagerIsInited() { return m_initFinished; } void KyNetworkResourceManager::requestScan(NetworkManager::WirelessDevice * dev) { if (nullptr == dev) { qWarning() << LOG_FLAG << "request scan failed, wireless device is invalid."; return; } qDebug() <<"[KyNetworkResourceManager]"<< dev->interfaceName()<<"start scan wifi ap"; QDBusPendingReply<> reply = dev->requestScan(); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, dev); connect(watcher, &QDBusPendingCallWatcher::finished, [dev] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { //TODO: in what form should we output the warning messages qWarning() << QStringLiteral("requestScan on device '%1' failed: %3").arg(dev->interfaceName()) .arg(watcher->error().message()); } watcher->deleteLater(); }); return; } void KyNetworkResourceManager::onServiceAppear(QString interface, QString oldOwner, QString newOwner) { if (interface == "org.freedesktop.NetworkManager" && oldOwner.isEmpty() && !newOwner.isEmpty()) { qDebug() << LOG_FLAG << "org.freedesktop.NetworkManager start"; QTimer::singleShot(500,this,&KyNetworkResourceManager::insertWifiNetworks); } } void KyNetworkResourceManager::onPropertiesChanged(QVariantMap qvm) { for(QString keyStr : qvm.keys()) { //收到wifi开关打开或关闭的信号后,进行处理 if (keyStr == "WiredEnabled") { bool wiredEnable = qvm.value("WiredEnabled").toBool(); Q_EMIT wiredEnabledChanged(wiredEnable); } } for(QString keyStr : qvm.keys()) { //内网检测地址变化 if (keyStr == "ConnectivityCheckSpareUri") { Q_EMIT connectivityCheckSpareUriChanged(); } } } void KyNetworkResourceManager::onConnectionUpdated() { NetworkManager::Connection *connectPtr = qobject_cast(sender()); if (nullptr != connectPtr && connectPtr->isValid()) { qDebug()<< LOG_FLAG <<"connection will Update, connection name"<name() << "connection uuid" << connectPtr->uuid(); Q_EMIT connectionUpdate(connectPtr->uuid()); } else { qWarning()<< LOG_FLAG <<"onConnectionUpdate failed, the connect is invalid"; } return; } void KyNetworkResourceManager::onActiveConnectionUpdated() { //Q_EMIT activeConnectionUpdate(qobject_cast(sender())); } void KyNetworkResourceManager::onActiveConnectionChangedReason( NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason) { NetworkManager::ActiveConnection * activeConnect = qobject_cast(sender()); if (nullptr != activeConnect && activeConnect->isValid()) { qDebug()<< LOG_FLAG <<"connect uuid"<uuid() <<"state change"<uuid(), state, reason); } else { qWarning() << LOG_FLAG << "onActiveConnectionChangedReason failed, the connection is invalid."; } return; } void KyNetworkResourceManager::onActiveConnectionChanged( NetworkManager::ActiveConnection::State state) { NetworkManager::ActiveConnection * activeConnect = qobject_cast(sender()); if (nullptr != activeConnect && activeConnect->isValid()) { qDebug()<< LOG_FLAG << "connection uuid" << activeConnect->uuid() <<"state change "<state() != state) { qDebug() << "[KyNetworkResourceManager]" <<"connect real state"<state() <<"change state"<uuid(), state, NetworkManager::ActiveConnection::Reason::UknownReason); } else { qWarning() << LOG_FLAG << "onActiveConnectionChanged failed, the connection is invalid."; } return; } void KyNetworkResourceManager::onVpnActiveConnectChanagedReason(NetworkManager::VpnConnection::State state, NetworkManager::VpnConnection::StateChangeReason reason) { NetworkManager::ActiveConnection *activeConnect = qobject_cast(sender()); if (nullptr != activeConnect && activeConnect->isValid()) { qDebug()<<"vpn connect uuid" << activeConnect->uuid() <<"state change " <uuid(), state, reason); } else { qWarning() << LOG_FLAG << "onVpnActiveConnectChanagedReason failed, the connection is invalid."; } return; } void KyNetworkResourceManager::onDeviceActiveChanage() { NetworkManager::Device *p_device = qobject_cast(sender()); if (nullptr == p_device) { return; } QString deviceName = p_device->interfaceName(); //此处需要取反,因为激活连接的网卡状态是false,断开连接的网卡状态是true bool isActive = !p_device->isActive(); qDebug()<< LOG_FLAG << "device active change, device name " << deviceName << "active state" << isActive; Q_EMIT deviceActiveChanage(deviceName, isActive); return; } void KyNetworkResourceManager::onDeviceUpdated() { NetworkManager::Device *p_device = qobject_cast(sender()); if (nullptr == p_device) { return; } QString deviceName = p_device->interfaceName(); QString deviceUni = p_device->uni(); Q_EMIT deviceUpdate(deviceName, deviceUni); return; } void KyNetworkResourceManager::onDeviceManagedChange() { NetworkManager::Device *p_device = qobject_cast(sender()); if (nullptr == p_device) { return; } QString deviceName = p_device->interfaceName(); bool managed = p_device->managed(); Q_EMIT deviceManagedChange(deviceName, managed); } void KyNetworkResourceManager::onDeviceCarrierChanage(bool pluged) { NetworkManager::WiredDevice * networkDevice = qobject_cast(sender()); qDebug()<< LOG_FLAG<<"device carrier chanage"<< pluged; if (nullptr !=networkDevice && networkDevice->isValid()) { Q_EMIT deviceCarrierChanage(networkDevice->interfaceName(), pluged); } else { qWarning()<< LOG_FLAG<<"onDeviceCarrierChanage failed."; } return; } void KyNetworkResourceManager::onDeviceBitRateChanage(int bitRate) { NetworkManager::WiredDevice * networkDevice = qobject_cast(sender()); if (nullptr != networkDevice && networkDevice->isValid()) { Q_EMIT deviceBitRateChanage(networkDevice->interfaceName(), bitRate); } else { qWarning()<< LOG_FLAG <<"the device is not invalid with bitrate" << bitRate; } return; } void KyNetworkResourceManager::onDeviceMacAddressChanage(const QString &hwAddress) { NetworkManager::WiredDevice * networkDevice = qobject_cast(sender()); if (nullptr !=networkDevice && networkDevice->isValid()) { Q_EMIT deviceMacAddressChanage(networkDevice->interfaceName(), hwAddress); } else { qWarning()<< LOG_FLAG <<"the device is not invalid with mac" << hwAddress; } return; } void KyNetworkResourceManager::onDeviceStateChanged( NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason) { qWarning() << LOG_FLAG <<"the device state "<interfaceName() << ssid; NetworkManager::WirelessDevice * w_dev = qobject_cast(dev); NetworkManager::WirelessNetwork::Ptr net = w_dev->findNetwork(ssid); if (!net.isNull()) { if (0 > m_wifiNets.indexOf(net)){ addWifiNetwork(net); } else { //TODO: onWifiNetworkUpdate qDebug()<< LOG_FLAG << "add but already exist"; } NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); QByteArray rawSsid = accessPoitPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); Q_EMIT wifiNetworkAdded(dev->interfaceName(), wifiSsid); } return; } void KyNetworkResourceManager::onWifiNetworkUpdate(NetworkManager::WirelessNetwork * net) { if (nullptr == net) { return; } bool bFlag = false; QString devIface; NetworkManager::Device::Ptr dev = findDeviceUni(net->device()); if(dev.isNull()) { qDebug()<< LOG_FLAG << "device invalid"; bFlag = true; } else { devIface = dev->interfaceName(); } if(bFlag) { //device invalid qDebug() << LOG_FLAG << "wifiNetworkDeviceDisappear"; Q_EMIT wifiNetworkDeviceDisappear(); return; } auto index = std::find(m_wifiNets.cbegin(), m_wifiNets.cend(), net); if (m_wifiNets.cend() != index) { if (net->accessPoints().isEmpty()) { //remove auto pos = index - m_wifiNets.cbegin(); removeWifiNetwork(pos); qDebug()<< LOG_FLAG << "wifiNetwork disappear" << net << net->ssid(); NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); QByteArray rawSsid = accessPoitPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); Q_EMIT wifiNetworkRemoved(devIface, wifiSsid); } else { NetworkManager::AccessPoint::Ptr accessPointPtr = net->referenceAccessPoint(); if (accessPointPtr.isNull()) { return; } QByteArray rawSsid = accessPointPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); QString bssid = accessPointPtr->hardwareAddress(); QString secuType = enumToQstring(accessPointPtr->capabilities(), accessPointPtr->wpaFlags(), accessPointPtr->rsnFlags()); Q_EMIT wifiNetworkPropertyChange(devIface, wifiSsid, net->signalStrength(), bssid, secuType); } } return; } void KyNetworkResourceManager::onWifiNetworkRemove(NetworkManager::Device * dev, QString const & ssid) { if (nullptr == dev) { return; } qDebug() << "wifiNetworkRemove" << dev << dev->interfaceName() << ssid; NetworkManager::WirelessNetwork::Ptr net = findWifiNetwork(ssid, dev->uni()); if (!net.isNull()) { auto pos = m_wifiNets.indexOf(net); if (0 <= pos) { removeWifiNetwork(pos); NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); QByteArray rawSsid = accessPoitPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); Q_EMIT wifiNetworkRemoved(dev->interfaceName(), wifiSsid); } } return; } void KyNetworkResourceManager::onWifiNetworkAppeared(QString const & ssid) { NetworkManager::Device * p_device = qobject_cast(sender()); if (nullptr != p_device) { onWifiNetworkAdd(p_device, ssid); QString deviceName = p_device->interfaceName(); QString deviceUni = p_device->uni(); Q_EMIT deviceUpdate(deviceName, deviceUni); } else { qWarning()<< LOG_FLAG << "onWifiNetworkAppeared failed."; } return; } void KyNetworkResourceManager::onWifiNetworkDisappeared(QString const & ssid) { NetworkManager::Device *p_device = qobject_cast(sender()); if (nullptr != p_device) { onWifiNetworkRemove(p_device, ssid); QString deviceName = p_device->interfaceName(); QString deviceUni = p_device->uni(); Q_EMIT deviceUpdate(deviceName, deviceUni); } else { qWarning()<< LOG_FLAG << "onWifiNetworkDisappeared failed."; } return; } void KyNetworkResourceManager::onDevicePropertiesChanged(QString interface, QVariantMap qvm) { if (interface.compare(QString("org.freedesktop.NetworkManager.Device"), Qt::CaseSensitive)) { return; } for(QString keyStr : qvm.keys()) { //连通性变化 if (keyStr == "Ip4Connectivity") { NetworkManager::Connectivity connectivity = NetworkManager::Connectivity::UnknownConnectivity; connectivity = (NetworkManager::Connectivity)qvm.value(keyStr).toUInt(); QString uni = message().path(); NetworkManager::Device::Ptr devicePtr = findDeviceUni(uni); if(devicePtr.isNull()) { qWarning()<< LOG_FLAG << "device invalid" << Q_FUNC_INFO; break; } Q_EMIT deviceConnectivityChanged(devicePtr->interfaceName(), connectivity); } } } void KyNetworkResourceManager::onReferenceAccessPointChanged() { NetworkManager::WirelessNetwork *p_wirelessNet = qobject_cast(sender()); if (nullptr != p_wirelessNet) { onAccessPointUpdate(p_wirelessNet); } } void KyNetworkResourceManager::onAccessPointUpdate(NetworkManager::WirelessNetwork * net) { if (nullptr == net) { return; } auto index = std::find(m_wifiNets.cbegin(), m_wifiNets.cend(), net); if (m_wifiNets.cend() != index) { if (!net->referenceAccessPoint().isNull()) { connect(net->referenceAccessPoint().data(), &NetworkManager::AccessPoint::wpaFlagsChanged, this, &KyNetworkResourceManager::onWifiNetworkSecuChang, Qt::UniqueConnection); connect(net->referenceAccessPoint().data(), &NetworkManager::AccessPoint::rsnFlagsChanged, this, &KyNetworkResourceManager::onWifiNetworkSecuChang, Qt::UniqueConnection); } } } void KyNetworkResourceManager::onUpdateWirelessNet() { NetworkManager::WirelessNetwork *p_wirelessNet = qobject_cast(sender()); if (nullptr != p_wirelessNet) { onWifiNetworkUpdate(p_wirelessNet); } return; } void KyNetworkResourceManager::onWifiNetworkSecuChang() { NetworkManager::AccessPoint *p_wirelessNet = qobject_cast(sender()); Q_EMIT wifiNetworkSecuChange(p_wirelessNet); } void KyNetworkResourceManager::onDeviceAdded(QString const & uni) { qDebug()<< "onDeviceAdded"<isValid()) { qWarning() << uni << " is currently not invalid"; return; } if (0 > m_devices.indexOf(networkDevice)) { addDevice(networkDevice); Q_EMIT deviceAdd(networkDevice->interfaceName(), networkDevice->uni(), networkDevice->type()); } else { qWarning() << networkDevice->interfaceName() <<"the device is exist in network device list."; } return; } void KyNetworkResourceManager::onDeviceRemoved(QString const & uni) { NetworkManager::Device::Ptr networkDevice = findDeviceUni(uni); if (networkDevice.isNull()) { qWarning()<<"the device is not exist in network device list ."<< uni; return; } qDebug()<<"remove network device"<< networkDevice->interfaceName() <<"uni:" << uni; auto index = std::find(m_devices.cbegin(), m_devices.cend(), networkDevice); if (m_devices.cend() != index) { const int pos = index - m_devices.cbegin(); removeDevice(pos); Q_EMIT deviceRemove(networkDevice->interfaceName(), networkDevice->uni()); } return; } void KyNetworkResourceManager::onActiveConnectionAdded(QString const & path) { NetworkManager::ActiveConnection::Ptr activeConnectPtr = NetworkManager::findActiveConnection(path); if (activeConnectPtr.isNull()) { qWarning() << "[KyNetworkResourceManager]" << "the active connect is null, so do not add it."<isValid()) { qWarning() << "[KyNetworkResourceManager]" << path << " connect is currently not valid"; return; } qDebug()<<"add active connect"<connection()->name() << " " << activeConnectPtr->connection()->uuid(); if (0 > m_activeConns.indexOf(activeConnectPtr)) { addActiveConnection(activeConnectPtr); Q_EMIT activeConnectionAdd(activeConnectPtr->uuid()); } else { //TODO: onActiveConnectionUpdate qWarning() << "[KyNetworkResourceManager]" << "update active connection to do"; //Q_EMIT activeConnectionUpdate(conn->uuid()); } return; } void KyNetworkResourceManager::onActiveConnectionRemoved(QString const & path) { NetworkManager::ActiveConnection::Ptr activeConnectPtr = findActiveConnection(path);//XXX: const QString &uni if (activeConnectPtr.isNull()) { qWarning() <<"[KyNetworkResourceManager]" <<"the active connect is null, so do not remove it. "<< path; return; } qDebug() <<"[KyNetworkResourceManager]"<<"remove active connect"<uuid(); auto index = std::find(m_activeConns.cbegin(), m_activeConns.cend(), activeConnectPtr); if (m_activeConns.cend() != index) { const int pos = index - m_activeConns.cbegin(); removeActiveConnection(pos); Q_EMIT activeConnectionRemove(activeConnectPtr->uuid()); } return; } void KyNetworkResourceManager::onConnectionAdded(QString const & path) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnection(path); if (connectPtr.isNull()) { qWarning() <<"[KyNetworkResourceManager]" <<"it can not find in networkmanager."<isValid()) { qWarning() <<"[KyNetworkResourceManager]" << path << " is currently not invalid"; return; } qDebug() <<"[KyNetworkResourceManager]" <<"add connect "<< connectPtr->name() << connectPtr->path(); if (connectPtr->name().isEmpty() || connectPtr->uuid().isEmpty()) { qWarning() <<"[KyNetworkResourceManager]" << "the name or uuid of connection is empty"; return; } if (0 > m_connections.indexOf(connectPtr)) { addConnection(connectPtr); Q_EMIT connectionAdd(connectPtr->uuid()); } else { //TODO::updateconnect qWarning() << "[KyNetworkResourceManager]" << connectPtr->uuid() <<" connect is exist in connect list."; } return; } void KyNetworkResourceManager::onConnectionRemoved(QString const & path) { if (path.isEmpty()) { qDebug() <<"[KyNetworkResourceManager]" <<"the connect path is empty"; return; } qDebug() <<"[KyNetworkResourceManager]" << "remove connection path" << path; NetworkManager::Connection::Ptr connectionPtr = nullptr; for (int index = 0; index < m_connections.size(); ++index) { connectionPtr = m_connections.at(index); if (connectionPtr->path() == path) { removeConnection(index); return; } } qWarning() <<"[KyNetworkResourceManager]" << path <<" connect is no exist in connect list"; return; } void KyNetworkResourceManager::removeConnection(QString const & uuid) { NetworkManager::Connection::Ptr conn = this->getConnect(uuid); if(!conn.isNull()) { conn->disconnect(this); conn->remove(); } } void KyNetworkResourceManager::setWirelessNetworkEnabled(bool enabled) { NetworkManager::setWirelessEnabled(enabled); } void KyNetworkResourceManager::connectionDump() { NetworkManager::Connection::Ptr connectionPtr = nullptr; for (int index = 0; index < m_connections.size(); ++index) { connectionPtr = m_connections.at(index); qDebug()<<"connection info**********************"; qDebug()<<"connection name"<< connectionPtr->name(); qDebug()<<"connection uuid"<< connectionPtr->uuid(); qDebug()<<"connection path"<< connectionPtr->path(); } } kylin-nm/src/backend/dbus-interface/kylinconnectoperation.cpp0000664000175000017500000002442615167651420023453 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include #include #include #include #define SYSTEM_DBUS_SERVICE "com.kylin.network.qt.systemdbus" #define SYSTEM_DBUS_PATH "/" #define SYSTEM_DBUS_INTERFACE "com.kylin.network.interface" KyConnectOperation::KyConnectOperation(QObject *parent) : QObject(parent) { m_networkResourceInstance = KyNetworkResourceManager::getInstance(); } KyConnectOperation::~KyConnectOperation() { m_networkResourceInstance = nullptr; } void KyConnectOperation::ipv4SettingSet( NetworkManager::Ipv4Setting::Ptr &ipv4Setting, const KyConnectSetting &connectSettingsInfo) { ipv4Setting->setInitialized(true); ipv4Setting->setDns(connectSettingsInfo.m_ipv4Dns); if (CONFIG_IP_DHCP == connectSettingsInfo.m_ipv4ConfigIpType) { ipv4Setting->setMethod(NetworkManager::Ipv4Setting::Automatic); return; } else { ipv4Setting->setMethod(NetworkManager::Ipv4Setting::Manual); } ipv4Setting->setAddresses(connectSettingsInfo.m_ipv4Address); return; } void KyConnectOperation::ipv6SettingSet( NetworkManager::Ipv6Setting::Ptr &ipv6Setting, const KyConnectSetting &connectSettingsInfo) { ipv6Setting->setInitialized(true); ipv6Setting->setDns(connectSettingsInfo.m_ipv6Dns); if (CONFIG_IP_DHCP == connectSettingsInfo.m_ipv6ConfigIpType) { ipv6Setting->setMethod(NetworkManager::Ipv6Setting::Automatic); ipv6Setting->setPrivacy(NetworkManager::Ipv6Setting::Disabled); return; } ipv6Setting->setMethod(NetworkManager::Ipv6Setting::Manual); ipv6Setting->setAddresses(connectSettingsInfo.m_ipv6Address); return ; } void KyConnectOperation::connectSettingSet( NetworkManager::ConnectionSettings::Ptr connectionSettings, const KyConnectSetting &connectSettingsInfo) { connectionSettings->setId(connectSettingsInfo.m_connectName); connectionSettings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); connectionSettings->setAutoconnect(true); connectionSettings->setAutoconnectPriority(0); if (!connectSettingsInfo.m_ifaceName.isEmpty()) { connectionSettings->setInterfaceName(connectSettingsInfo.m_ifaceName); } return; } void KyConnectOperation::setAutoConnect(NetworkManager::ConnectionSettings::Ptr &connectSetting, bool bAutoConnect) { if (connectSetting.isNull()) { return; } connectSetting->setAutoconnect(bAutoConnect); return; } void KyConnectOperation::createConnect(KyConnectSetting &connectSettingsInfo) { qDebug()<<"create connect need to do"; return; } void KyConnectOperation::updateConnect(NetworkManager::ConnectionSettings::Ptr connectionSettings, const KyConnectSetting &connectSettingsInfo) { qDebug()<<"update connect"<uuid(); NetworkManager::Ipv4Setting::Ptr ipv4Setting = connectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); ipv4SettingSet(ipv4Setting, connectSettingsInfo); NetworkManager::Ipv6Setting::Ptr ipv6Setting = connectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); ipv6SettingSet(ipv6Setting, connectSettingsInfo); // NetworkManager::WiredSetting::Ptr wiredSetting = connectionSettings->setting(NetworkManager::Setting::Wired).dynamicCast(); // wiredSetting->setInitialized(true); return ; } void KyConnectOperation::deleteConnect(const QString &connectUuid) { qDebug()<<"delete connect uuid " << connectUuid; NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(connectUuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + connectUuid; qWarning()<remove(); return ; } void KyConnectOperation::activateConnection(const QString connectUuid, const QString deviceName) { QString connectPath = ""; QString deviceIdentifier = ""; QString connectName = ""; QString specificObject = ""; NetworkManager::Connection::Ptr connectPtr = nullptr; qDebug()<<"it will activate connect"<settings()->connectionType()) { QString errorMessage = tr("the connect type is") + connectPtr->settings()->connectionType() + tr(", but it is not wired"); qWarning()<path(); connectName = connectPtr->name(); // deviceName = connectPtr->settings()->interfaceName(); // for (auto const & dev : m_networkResourceInstance->m_devices) { // for (auto const & dev_conn : dev->availableConnections()) { // if (dev_conn == connectPtr) { // deviceIdentifier = dev->uni(); // deviceName = dev->interfaceName(); // break; // } // } // } auto dev = m_networkResourceInstance->findDeviceInterface(deviceName); if (!dev.isNull()) { deviceIdentifier = dev->uni(); } if (deviceIdentifier.isEmpty()) { QString errorMessage = tr("device Identifier is empty, its name") + deviceName; qWarning() << errorMessage; Q_EMIT activateConnectionError(errorMessage); return ; } qDebug() <<"active wired connect: path "<< connectPath << "device identify " << deviceIdentifier << "connect name " << connectName << "device name" << deviceName << "specific parameter"<< specificObject; QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::activateConnection(connectPath, deviceIdentifier, specificObject), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this, connectName, deviceName] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("activate connection failed: ") + watcher->error().message(); qWarning()<activateConnectionError(errorMessage); } else { qWarning()<<"active wired connect complete."; } watcher->deleteLater(); }); return ; } void KyConnectOperation::deactivateConnection(const QString activeConnectName, const QString &activeConnectUuid, bool concise, QString devName) { NetworkManager::ActiveConnection::Ptr activateConnectPtr = nullptr; qDebug()<<"deactivetate connect name"<getActiveConnect(activeConnectUuid); if (nullptr == activateConnectPtr) { QString errorMessage = tr("it can not find the activate connect") + activeConnectName + tr("uuid") + activeConnectUuid; qWarning()<path(); QDBusPendingReply<> reply = NetworkManager::deactivateConnection(activateConnectPtr->path()); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); connect(watcher, &QDBusPendingCallWatcher::finished, [this, activateConnectPtr, concise, devName] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("deactivation of connection") + activateConnectPtr->connection()->name() + tr("failed:") + watcher->error().message(); qWarning()<deactivateConnectionError(errorMessage); } else { qWarning() << "deactive connect operation finished" << activateConnectPtr->connection()->name(); //断开连接后删除网卡和连接信息 //只有当concise=false的时候即主动断开网络时需要清除网络信息,否则直接关闭网络或网卡,下次需要自动连接 QDBusInterface iface(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, QDBusConnection::systemBus()); if (iface.isValid() && !concise) { iface.call("writeNmConfig", "/etc/kylin-nm/netSwitch.conf", "Lan_Connect", devName, ""); } } watcher->deleteLater(); }); //set autoconnect NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(activeConnectUuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + activeConnectUuid; qWarning()<settings(); setAutoConnect(connectionSettings,false); // 保存autoconnect设置到配置文件 connectPtr->update(connectionSettings->toMap()); return; } kylin-nm/src/backend/dbus.h0000664000175000017500000001561415167651420014540 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef DBUSADAPTOR_H #define DBUSADAPTOR_H #include #include #include #include #include "dbus_adaptor.h" #include "dbus_interface.h" #include "tabpage.h" #include "../dbus-interface/kylinnetworkdeviceresource.h" QT_BEGIN_NAMESPACE class QByteArray; //template class QList; template class QMap; class QString; class QVariant; QT_END_NAMESPACE /* * Adaptor class for interface com.kylin.weather */ #define SYSTEM_DBUS_SERVICE "com.kylin.network.qt.systemdbus" #define SYSTEM_DBUS_PATH "/" #define SYSTEM_DBUS_INTERFACE "com.kylin.network.interface" #include "mainwindow.h" class DbusAdaptor: public QObject, protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "com.kylin.network") public: explicit DbusAdaptor(QString display, MainWindow *m, QObject *parent = nullptr); ~DbusAdaptor(); public: // PROPERTIES public Q_SLOTS: // METHODS //无线列表 QVariantList getWirelessList(QString devName); //有线列表 QVariantList getWiredList(QString devName); //有线总开关 Q_NOREPLY void setWiredSwitchEnable(bool enable); //无线总开关 Q_NOREPLY void setWirelessSwitchEnable(bool enable); //有线网卡开关 Q_NOREPLY void setDeviceEnable(QString devName, bool enable); //设置默认网卡 // Q_NOREPLY void setDefaultWiredDevice(QString deviceName); // QString getDefaultWiredDevice(); // Q_NOREPLY void setDefaultWirelessDevice(QString deviceName); // QString getDefaultWirelessDevice(); //连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid Q_NOREPLY void activateConnect(int type, QString devName, QString ssid); //断开连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid Q_NOREPLY void deActivateConnect(int type, QString devName, QString ssid); //断开连接 根据网卡类型 参数1 0:lan 1:wlan 参数2 true:只断开 false:断开并清除连接的网络信息 参数3 为ssid/uuid Q_NOREPLY void deActivateConnectConcise(int type, bool concise, const QString &devName, const QString &ssid); //delete network connect Q_NOREPLY void deleteConnect(int type,QString Uuid); //dev autoconnect Q_NOREPLY void setDeviceAutoConnectState(QString devName, bool state); //获取设备列表和启用/禁用状态 QVariantMap getDeviceListAndEnabled(int devType); //获取无线设备能力 QVariantMap getWirelessDeviceCap(); //唤起属性页 根据网卡类型 参数2 为ssid/uuid Q_NOREPLY void showPropertyWidget(QString devName, QString ssid); //唤起新建有线连接界面 Q_NOREPLY void showCreateWiredConnectWidget(QString devName); //唤起加入其他无线网络界面 Q_NOREPLY void showAddOtherWlanWidget(QString devName); //开启热点 void activeWirelessAp(const QString apName, const QString apPassword, const QString band, const QString apDevice); //断开热点 void deactiveWirelessAp(const QString apName, const QString uuid); //连接新wifi void passwordConnect(QString devName, QString ssid, QString type, QString psk, bool autoConnect); //获取热点 QStringList getStoredApInfo(); QStringList getApInfoBySsid(QString devName, QString ssid); QString getApConnectionPath(QString uuid); QString getActiveConnectionPath(QString uuid); //wifi扫描 void reScan(); //keyring void keyRingInit(); void keyRingClear(); //just show void showKylinNM(int type); bool getWirelessSwitchBtnState(); bool getWiredMainSwitchBtnState(); int getDeviceConnectivity(const QString deviceName); //获取网卡是否插入了网线 bool getCableStateByDevice(const QString deviceName); Q_SIGNALS: // SIGNALS // void wirelessActivating(QString devName, QString ssid); // void wiredActivating(QString devName, QString ssid); void lanAdd(QString devName, QStringList info); void lanRemove(QString dbusPath); void lanUpdate(QString devName, QStringList info); void wlanAdd(QString devName, QStringList info); void wlanRemove(QString devName,QString ssid); void wlanactiveConnectionStateChanged(QString devName, QString ssid, QString uuid, int status); void lanActiveConnectionStateChanged(QString devName, QString uuid, int status); //仅失败,若成功直接发listUpdate void activateFailed(QString errorMessage); void deactivateFailed(QString errorMessage); //设备插拔 void deviceStatusChanged(); void wirelessDeviceStatusChanged(); void deviceNameChanged(QString oldName, QString newName, int type); void wirelessSwitchBtnChanged(bool state); void wiredMainSwitchBtnChanged(bool state); //热点断开 void hotspotDeactivated(QString devName, QString ssid); //热点连接 void hotspotActivated(QString devName, QString ssid, QString uuid, QString activePath, QString settingPath); //信号强度变化 void signalStrengthChange(QString devName, QString ssid, int strength); //安全性变化 void secuTypeChange(QString devName, QString ssid, QString secuType); //列表排序 void timeToUpdate(); void showKylinNMSignal(QString display, int type); //唤起属性页 根据网卡类型 参数2 为ssid/uuid void showPropertyWidgetSignal(QString display, QString devName, QString ssid); //唤起新建有线连接界面 void showCreateWiredConnectWidgetSignal(QString display, QString devName); //唤起加入其他无线网络界面 void showAddOtherWlanWidgetSignal(QString display, QString devName); private: MainWindow *m_mainWindow; QString m_display; QDBusServiceWatcher *m_watcher = nullptr; NetworkAdaptor* mNetworkAdaptor=nullptr; QDBusInterface *m_pSysBusInterfaces; QString checkDisplay(); QString displayFromPid(uint pid); void connectToMainwindow(); bool registerService(); private Q_SLOT: void onServiceOwnerChanged(const QString &service, const QString &oldOwner, const QString &newOwner); void onWiredMainSwitchBtnChanged(bool); }; #endif kylin-nm/src/backend/wifi-auth-thread.h0000664000175000017500000000263615167646234016754 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef WIFI_AUTH_THREAD_H #define WIFI_AUTH_THREAD_H #include #include #include #include #include #include #include class WifiAuthThread:public QThread { protected: virtual void run(); QNetworkRequest request; QNetworkAccessManager* naManager=nullptr; bool _isConnect=true;//是否已联网 bool _isReply=false;//联网状态检查是否收到回复 public: WifiAuthThread(); ~WifiAuthThread(); }; #endif //WIFI_AUTH_THREAD_H kylin-nm/src/backend/kylinipv4arping.cpp0000664000175000017500000002752215167651420017271 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinipv4arping.h" #include #include #include #define FINAL_PACKS 2 __attribute__((const)) static inline size_t sll_len(const size_t halen) { struct sockaddr_ll unused; const size_t len = offsetof(struct sockaddr_ll, sll_addr) + halen; if (len < sizeof(unused)) return sizeof(unused); return len; } KyIpv4Arping::KyIpv4Arping(QString ifaceName, QString ipAddress, int retryCount, int timeout, QObject *parent) : QObject(parent) { m_ifaceName = ifaceName; m_ipv4Address = ipAddress; m_retryCount = retryCount; m_timeout = timeout; memset(&m_srcAddress, 0, sizeof(m_srcAddress)); } KyIpv4Arping::~KyIpv4Arping() { } void KyIpv4Arping::monoGetTime (struct timespec *ts) { #ifdef CLOCK_MONOTONIC if (clock_gettime (CLOCK_MONOTONIC, ts)) #endif { static long freq = 0; if (freq == 0) freq = sysconf (_SC_CLK_TCK); struct tms dummy; clock_t t = times (&dummy); ts->tv_sec = t / freq; ts->tv_nsec = (t % freq) * (1000000000 / freq); } } void KyIpv4Arping::saveMacAddress(const uint8_t *ptr, size_t len) { int index; char macAddress[64] = {0}; for (index = 0; index < len; index++) { snprintf(&macAddress[qstrlen(macAddress)], sizeof(macAddress) - qstrlen(macAddress), "%02X", ptr[index]); if (index != len - 1) { snprintf(&macAddress[qstrlen(macAddress)], sizeof(macAddress) - qstrlen(macAddress), "%s", ":"); } } m_conflictMac = QString(macAddress); return ; } void KyIpv4Arping::setConflictFlag(bool isConflict) { m_ipConflict = isConflict; } int KyIpv4Arping::sendIpv4Packet() { int err; unsigned char buf[256]; struct arphdr *ah = (struct arphdr *)buf; unsigned char *p = (unsigned char *)(ah + 1); struct sockaddr_ll *p_me = (struct sockaddr_ll *)&(m_me); struct sockaddr_ll *p_he = (struct sockaddr_ll *)&(m_he); ah->ar_hrd = htons(p_me->sll_hatype); if (ah->ar_hrd == htons(ARPHRD_FDDI)) ah->ar_hrd = htons(ARPHRD_ETHER); ah->ar_pro = htons(ETH_P_IP); ah->ar_hln = p_me->sll_halen; ah->ar_pln = 4; ah->ar_op = htons(ARPOP_REQUEST); memcpy(p, &p_me->sll_addr, ah->ar_hln); p += p_me->sll_halen; qWarning()<<"[KyIpv4Arping]" <<"m_src address:" << inet_ntoa(m_srcAddress); memcpy(p, &m_srcAddress, 4); p += 4; memcpy(p, &p_he->sll_addr, ah->ar_hln); p += ah->ar_hln; memcpy(p, &m_destAddress, 4); p += 4; err = sendto(m_ipv4Socket, buf, p - buf, 0, (struct sockaddr *)p_he, sll_len(ah->ar_hln)); return err; } int KyIpv4Arping::ipv4PacketProcess(unsigned char *buf, ssize_t len, struct sockaddr_ll *from) { struct arphdr *ah = (struct arphdr *)buf; unsigned char *p = (unsigned char *)(ah + 1); struct in_addr src_ip, dst_ip; /* Filter out wild packets */ if (from->sll_pkttype != PACKET_HOST && from->sll_pkttype != PACKET_BROADCAST && from->sll_pkttype != PACKET_MULTICAST) return 0; /* Only these types are recognised */ if (ah->ar_op != htons(ARPOP_REQUEST) && ah->ar_op != htons(ARPOP_REPLY)) return 0; /* ARPHRD check and this darned FDDI hack here :-( */ if (ah->ar_hrd != htons(from->sll_hatype) && (from->sll_hatype != ARPHRD_FDDI || ah->ar_hrd != htons(ARPHRD_ETHER))) return 0; /* Protocol must be IP. */ if (ah->ar_pro != htons(ETH_P_IP)) return 0; if (ah->ar_pln != 4) return 0; if (ah->ar_hln != ((struct sockaddr_ll *)&m_me)->sll_halen) return 0; if (len < (ssize_t) sizeof(*ah) + 2 * (4 + ah->ar_hln)) return 0; memcpy(&src_ip, p + ah->ar_hln, 4); memcpy(&dst_ip, p + ah->ar_hln + 4 + ah->ar_hln, 4); /* * DAD packet was: * src_ip = 0 (or some src) * src_hw = ME * dst_ip = tested address * dst_hw = * * We fail, if receive request/reply with: * src_ip = tested_address * src_hw != ME * if src_ip in request was not zero, check * also that it matches to dst_ip, otherwise * dst_ip/dst_hw do not matter. */ if (src_ip.s_addr != m_destAddress.s_addr) return 0; if (memcmp(p, ((struct sockaddr_ll *)&m_me)->sll_addr, ((struct sockaddr_ll *)&m_me)->sll_halen) == 0) return 0; saveMacAddress(p, ah->ar_hln); setConflictFlag(true); return FINAL_PACKS; } int KyIpv4Arping::ipv4EventLoop() { int rc = -1; int ret; int index; int exit_loop = 0; ssize_t bytes; int tfd; struct pollfd pfds[POLLFD_COUNT]; struct itimerspec timerfd_vals; timerfd_vals.it_interval.tv_sec = m_timeout, timerfd_vals.it_interval.tv_nsec = 0, timerfd_vals.it_value.tv_sec = m_timeout, timerfd_vals.it_value.tv_nsec = 0; uint64_t exp; uint64_t total_expires = 1; unsigned char packet[4096]; struct sockaddr_storage from = { 0 }; socklen_t addr_len = sizeof(from); /* timerfd */ tfd = timerfd_create(CLOCK_MONOTONIC, 0); if (tfd == -1) { qWarning()<<"[KyIpv4Arping]" << "timerfd_create failed, errno" << errno; return -1; } if (timerfd_settime(tfd, 0, &timerfd_vals, NULL)) { close(tfd); qWarning()<<"[KyIpv4Arping]" << "timerfd_settime failed, errno" << errno; return -1; } pfds[POLLFD_TIMER].fd = tfd; pfds[POLLFD_TIMER].events = POLLIN | POLLERR | POLLHUP; /* socket */ pfds[POLLFD_SOCKET].fd = m_ipv4Socket; pfds[POLLFD_SOCKET].events = POLLIN | POLLERR | POLLHUP; sendIpv4Packet(); while (!exit_loop) { ret = poll(pfds, POLLFD_COUNT, -1); if (ret <= 0) { if (errno == EAGAIN) { continue; } if (errno) { qWarning()<<"[KyIpv4Arping]" <<"poll failed, errno" << errno; } exit_loop = 1; continue; } for (index = 0; index < POLLFD_COUNT; index++) { if (pfds[index].revents == 0) { continue; } switch (index) { case POLLFD_TIMER: bytes = read(tfd, &exp, sizeof(uint64_t)); if (bytes != sizeof(uint64_t)) { qWarning() <<"[KyIpv4Arping]" << "could not read timerfd"; continue; } total_expires += exp; if (0 < m_retryCount && (uint64_t)m_retryCount < total_expires) { exit_loop = 1; rc = 0; continue; } sendIpv4Packet(); break; case POLLFD_SOCKET: bytes = recvfrom(m_ipv4Socket, packet, sizeof(packet), 0, (struct sockaddr *)&from, &addr_len); if (bytes < 0) { qWarning()<<"[KyIpv4Arping]" << "recvfrom function failed, errno" << errno; continue; } if (ipv4PacketProcess(packet, bytes, (struct sockaddr_ll *)&from) == FINAL_PACKS) { exit_loop = 1; rc = 0; } break; default: qWarning()<<"[KyIpv4Arping]" <<"the fd index is undefine" << index; break; } } } close(tfd); freeifaddrs(m_ifa0); return rc; } int KyIpv4Arping::checkIfflags(unsigned int ifflags) { if (!(ifflags & IFF_UP)) { qWarning()<<"[KyIpv4Arping]" <<"the iface" << m_ifaceName <<" is down."; return -1; } if (ifflags & (IFF_NOARP | IFF_LOOPBACK)) { qWarning()<<"[KyIpv4Arping]" << "Interface" << m_ifaceName << "is not ARPable."; return -1; } return 0; } int KyIpv4Arping::checkDevice() { int rc; struct ifaddrs *ifa; int n = 0; rc = getifaddrs(&m_ifa0); if (rc < 0) { qWarning()<<"[KyIpv4Arping]" <<"get iface address failed, erron"<< errno; return -errno; } for (ifa = m_ifa0; ifa; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) { continue; } if (ifa->ifa_addr->sa_family != AF_PACKET) { continue; } if (!m_ifaceName.isEmpty() && (NULL != ifa->ifa_name) && strcmp(ifa->ifa_name, m_ifaceName.toUtf8())) { continue; } if (checkIfflags(ifa->ifa_flags) < 0) { continue; } if (!((struct sockaddr_ll *)ifa->ifa_addr)->sll_halen) { continue; } if (!ifa->ifa_broadaddr) { continue; } m_ifa = ifa; if (n++) break; } if (n == 1 && m_ifa) { m_ifindex = if_nametoindex(m_ifa->ifa_name); if (!m_ifindex) { qWarning()<<"[KyIpv4Arping]" <<"if_nametoindex is invalid"; freeifaddrs(m_ifa0); return -1; } m_ifaceName = m_ifa->ifa_name; return 0; } freeifaddrs(m_ifa0); return -1; } void KyIpv4Arping::findBroadcastAddress() { struct sockaddr_ll *he = (struct sockaddr_ll *)&(m_he); if (m_ifa) { struct sockaddr_ll *sll = (struct sockaddr_ll *)m_ifa->ifa_broadaddr; if (sll->sll_halen == he->sll_halen) { memcpy(he->sll_addr, sll->sll_addr, he->sll_halen); return; } } qWarning()<<"[KyIpv4Arping]" <<"using default broadcast address."; memset(he->sll_addr, -1, he->sll_halen); return; } int KyIpv4Arping::ipv4ConflictCheck() { limit_capabilities(); int ret = checkDevice(); if (ret < 0) { qWarning()<<"[KyIpv4Arping]"<<"the device is invalid" << m_ifaceName; return -1; } enable_capability_raw(); m_ipv4Socket = socket(PF_PACKET, SOCK_DGRAM, 0); disable_capability_raw(); if (m_ipv4Socket < 0) { qWarning()<<"[KyIpv4Arping]" << "create ipv4 socket failed, errno" << errno; return -1; } inet_aton(m_ipv4Address.toUtf8(), &m_destAddress); m_destAddressFamily = AF_INET; ((struct sockaddr_ll *)&m_me)->sll_family = AF_PACKET; ((struct sockaddr_ll *)&m_me)->sll_ifindex = m_ifindex; ((struct sockaddr_ll *)&m_me)->sll_protocol = htons(ETH_P_ARP); ret = bind(m_ipv4Socket, (struct sockaddr *)&m_me, sizeof(m_me)); if (ret < 0) { qWarning()<<"[KyIpv4Arping]" <<"ipv4 socket bind failed, errno"<< errno; close(m_ipv4Socket); return -1; } socklen_t alen = sizeof(m_me); ret = getsockname(m_ipv4Socket, (struct sockaddr *)&m_me, &alen); if (ret < 0) { qWarning()<<"[KyIpv4Arping]" <<"ipv4 get socket name failed, errno" << errno; close(m_ipv4Socket); return -1; } if (((struct sockaddr_ll *)&m_me)->sll_halen == 0) { qWarning()<<"[KyIpv4Arping]" <<"the iface"<< m_ifaceName <<" is not suitable for arp"; close(m_ipv4Socket); return -1; } m_he = m_me; findBroadcastAddress(); drop_capabilities(); ret = ipv4EventLoop(); close(m_ipv4Socket); return ret; } kylin-nm/src/backend/dbus_adaptor.cpp0000664000175000017500000002212315167651420016576 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "dbus_adaptor.h" #include #include #include #include #include #include #include /* * Implementation of adaptor class NetworkAdaptor */ NetworkAdaptor::NetworkAdaptor(QObject *parent) : QDBusAbstractAdaptor(parent) { // constructor setAutoRelaySignals(true); } NetworkAdaptor::~NetworkAdaptor() { // destructor } void NetworkAdaptor::activateConnect(int type, const QString &devName, const QString &ssid) { // handle method call com.kylin.network.activateConnect QMetaObject::invokeMethod(parent(), "activateConnect", Q_ARG(int, type), Q_ARG(QString, devName), Q_ARG(QString, ssid)); } void NetworkAdaptor::activeWirelessAp(const QString &apName, const QString &apPassword, const QString &band, const QString &apDevice) { // handle method call com.kylin.network.activeWirelessAp QMetaObject::invokeMethod(parent(), "activeWirelessAp", Q_ARG(QString, apName), Q_ARG(QString, apPassword), Q_ARG(QString, band), Q_ARG(QString, apDevice)); } void NetworkAdaptor::deActivateConnect(int type, const QString &devName, const QString &ssid) { // handle method call com.kylin.network.deActivateConnect QMetaObject::invokeMethod(parent(), "deActivateConnect", Q_ARG(int, type), Q_ARG(QString, devName), Q_ARG(QString, ssid)); } void NetworkAdaptor::deActivateConnectConcise(int type, bool concise, const QString &devName, const QString &ssid) { // handle method call com.kylin.network.deActivateConnect QMetaObject::invokeMethod(parent(), "deActivateConnectConcise", Q_ARG(int, type), Q_ARG(bool, concise), Q_ARG(QString, devName), Q_ARG(QString, ssid)); } void NetworkAdaptor::deleteConnect(int type, const QString &ssid) { // handle method call com.kylin.network.deleteConnect QMetaObject::invokeMethod(parent(), "deleteConnect", Q_ARG(int, type), Q_ARG(QString, ssid)); } void NetworkAdaptor::setDeviceAutoConnectState(const QString &deviceName, bool state) { // handle method call com.kylin.network.setDeviceAutoConnectState QMetaObject::invokeMethod(parent(), "setDeviceAutoConnectState", Q_ARG(QString, deviceName), Q_ARG(bool, state)); } void NetworkAdaptor::deactiveWirelessAp(const QString &apName, const QString &uuid) { // handle method call com.kylin.network.deactiveWirelessAp QMetaObject::invokeMethod(parent(), "deactiveWirelessAp", Q_ARG(QString, apName), Q_ARG(QString, uuid)); } QString NetworkAdaptor::getActiveConnectionPath(const QString &uuid) { // handle method call com.kylin.network.getActiveConnectionPath QString out0; QMetaObject::invokeMethod(parent(), "getActiveConnectionPath", Q_RETURN_ARG(QString, out0), Q_ARG(QString, uuid)); return out0; } QString NetworkAdaptor::getApConnectionPath(const QString &uuid) { // handle method call com.kylin.network.getApConnectionPath QString out0; QMetaObject::invokeMethod(parent(), "getApConnectionPath", Q_RETURN_ARG(QString, out0), Q_ARG(QString, uuid)); return out0; } QStringList NetworkAdaptor::getApInfoBySsid(const QString &devName, const QString &ssid) { // handle method call com.kylin.network.getApInfoBySsid QStringList out0; QMetaObject::invokeMethod(parent(), "getApInfoBySsid", Q_RETURN_ARG(QStringList, out0), Q_ARG(QString, devName), Q_ARG(QString, ssid)); return out0; } QVariantMap NetworkAdaptor::getDeviceListAndEnabled(int devType) { // handle method call com.kylin.network.getDeviceListAndEnabled QVariantMap out0; QMetaObject::invokeMethod(parent(), "getDeviceListAndEnabled", Q_RETURN_ARG(QVariantMap, out0), Q_ARG(int, devType)); return out0; } QStringList NetworkAdaptor::getStoredApInfo() { // handle method call com.kylin.network.getStoredApInfo QStringList out0; QMetaObject::invokeMethod(parent(), "getStoredApInfo", Q_RETURN_ARG(QStringList, out0)); return out0; } QVariantList NetworkAdaptor::getWiredList(const QString &devName) { // handle method call com.kylin.network.getWiredList QVariantList out0; QMetaObject::invokeMethod(parent(), "getWiredList", Q_RETURN_ARG(QVariantList, out0), Q_ARG(QString, devName)); return out0; } QVariantMap NetworkAdaptor::getWirelessDeviceCap() { // handle method call com.kylin.network.getWirelessDeviceCap QVariantMap out0; QMetaObject::invokeMethod(parent(), "getWirelessDeviceCap", Q_RETURN_ARG(QVariantMap, out0)); return out0; } QVariantList NetworkAdaptor::getWirelessList(const QString &devName) { // handle method call com.kylin.network.getWirelessList QVariantList out0; QMetaObject::invokeMethod(parent(), "getWirelessList", Q_RETURN_ARG(QVariantList, out0), Q_ARG(QString, devName)); return out0; } bool NetworkAdaptor::getWirelessSwitchBtnState() { // handle method call com.kylin.network.getWirelessSwitchBtnState bool out0; QMetaObject::invokeMethod(parent(), "getWirelessSwitchBtnState", Q_RETURN_ARG(bool, out0)); return out0; } bool NetworkAdaptor::getWiredMainSwitchBtnState() { // handle method call com.kylin.network.getWiredMainSwitchBtnState bool out0; QMetaObject::invokeMethod(parent(), "getWiredMainSwitchBtnState", Q_RETURN_ARG(bool, out0)); return out0; } void NetworkAdaptor::keyRingClear() { // handle method call com.kylin.network.keyRingClear QMetaObject::invokeMethod(parent(), "keyRingClear"); } void NetworkAdaptor::keyRingInit() { // handle method call com.kylin.network.keyRingInit QMetaObject::invokeMethod(parent(), "keyRingInit"); } void NetworkAdaptor::reScan() { // handle method call com.kylin.network.reScan QMetaObject::invokeMethod(parent(), "reScan"); } void NetworkAdaptor::passwordConnect(QString devName, QString ssid, QString type, QString psk, bool autoConnect) { // handle method call com.kylin.network.passwordConnect QMetaObject::invokeMethod(parent(), "passwordConnect", Q_ARG(QString, devName), Q_ARG(QString, ssid), Q_ARG(QString, type), Q_ARG(QString, psk), Q_ARG(bool, autoConnect)); } void NetworkAdaptor::setDeviceEnable(const QString &devName, bool enable) { // handle method call com.kylin.network.setDeviceEnable QMetaObject::invokeMethod(parent(), "setDeviceEnable", Q_ARG(QString, devName), Q_ARG(bool, enable)); } void NetworkAdaptor::setWiredSwitchEnable(bool enable) { // handle method call com.kylin.network.setWiredSwitchEnable QMetaObject::invokeMethod(parent(), "setWiredSwitchEnable", Q_ARG(bool, enable)); } void NetworkAdaptor::setWirelessSwitchEnable(bool enable) { // handle method call com.kylin.network.setWirelessSwitchEnable QMetaObject::invokeMethod(parent(), "setWirelessSwitchEnable", Q_ARG(bool, enable)); } void NetworkAdaptor::showAddOtherWlanWidget(const QString &devName) { // handle method call com.kylin.network.showAddOtherWlanWidget QMetaObject::invokeMethod(parent(), "showAddOtherWlanWidget", Q_ARG(QString, devName)); } void NetworkAdaptor::showCreateWiredConnectWidget(const QString &devName) { // handle method call com.kylin.network.showCreateWiredConnectWidget QMetaObject::invokeMethod(parent(), "showCreateWiredConnectWidget", Q_ARG(QString, devName)); } void NetworkAdaptor::showKylinNM(int type) { // handle method call com.kylin.network.showKylinNM QMetaObject::invokeMethod(parent(), "showKylinNM", Q_ARG(int, type)); } void NetworkAdaptor::showPropertyWidget(const QString &devName, const QString &ssid) { // handle method call com.kylin.network.showPropertyWidget QMetaObject::invokeMethod(parent(), "showPropertyWidget", Q_ARG(QString, devName), Q_ARG(QString, ssid)); } bool NetworkAdaptor::getCableStateByDevice(const QString deviceName) { // handle method call com.kylin.network.getCableStateByDevice bool out0; QMetaObject::invokeMethod(parent(), "getCableStateByDevice", Q_RETURN_ARG(bool, out0), Q_ARG(QString, deviceName)); return out0; } int NetworkAdaptor::getDeviceConnectivity(const QString deviceName) { // handle method call com.kylin.network.getDeviceConnectivity int out0; QMetaObject::invokeMethod(parent(), "getDeviceConnectivity", Q_RETURN_ARG(int, out0), Q_ARG(QString, deviceName)); return out0; } kylin-nm/src/backend/dbus_interface.h0000664000175000017500000002634315167651420016561 0ustar fengfeng/* * This file was generated by qdbusxml2cpp version 0.8 * Command line was: qdbusxml2cpp dbus.xml -p dbus_interface * * qdbusxml2cpp is Copyright (C) 2020 The Qt Company Ltd. * * This is an auto-generated file. * Do not edit! All changes made to it will be lost. */ #ifndef DBUS_INTERFACE_H #define DBUS_INTERFACE_H #include #include #include #include #include #include #include #include /* * Proxy class for interface com.kylin.network */ class ComKylinNetworkInterface: public QDBusAbstractInterface { Q_OBJECT public: static inline const char *staticInterfaceName() { return "com.kylin.network"; } public: ComKylinNetworkInterface(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = nullptr); ~ComKylinNetworkInterface(); public Q_SLOTS: // METHODS inline Q_NOREPLY void deleteConnect(int type, const QString ssid) { QList argumentList; argumentList << QVariant::fromValue(type) << QVariant::fromValue(ssid); callWithArgumentList(QDBus::NoBlock, QStringLiteral("deleteConnect"), argumentList); } inline Q_NOREPLY void activateConnect(int type, const QString &devName, const QString &ssid) { QList argumentList; argumentList << QVariant::fromValue(type) << QVariant::fromValue(devName) << QVariant::fromValue(ssid); callWithArgumentList(QDBus::NoBlock, QStringLiteral("activateConnect"), argumentList); } inline Q_NOREPLY void setDeviceAutoConnectState(const QString &devName,bool stated) { QList argumentList; argumentList << QVariant::fromValue(devName) << QVariant::fromValue(stated) ; callWithArgumentList(QDBus::NoBlock, QStringLiteral("setDeviceAutoConnectState"), argumentList); } inline QDBusPendingReply<> activeWirelessAp(const QString &apName, const QString &apPassword, const QString &band, const QString &apDevice) { QList argumentList; argumentList << QVariant::fromValue(apName) << QVariant::fromValue(apPassword) << QVariant::fromValue(band) << QVariant::fromValue(apDevice); return asyncCallWithArgumentList(QStringLiteral("activeWirelessAp"), argumentList); } inline Q_NOREPLY void deActivateConnect(int type, const QString &devName, const QString &ssid) { QList argumentList; argumentList << QVariant::fromValue(type) << QVariant::fromValue(devName) << QVariant::fromValue(ssid); callWithArgumentList(QDBus::NoBlock, QStringLiteral("deActivateConnect"), argumentList); } inline Q_NOREPLY void deActivateConnectConcise(int type, bool concise, const QString &devName, const QString &ssid) { QList argumentList; argumentList << QVariant::fromValue(type) << QVariant::fromValue(concise) << QVariant::fromValue(devName) << QVariant::fromValue(ssid); callWithArgumentList(QDBus::NoBlock, QStringLiteral("deActivateConnectConcise"), argumentList); } inline QDBusPendingReply<> deactiveWirelessAp(const QString &apName, const QString &uuid) { QList argumentList; argumentList << QVariant::fromValue(apName) << QVariant::fromValue(uuid); return asyncCallWithArgumentList(QStringLiteral("deactiveWirelessAp"), argumentList); } inline QDBusPendingReply getActiveConnectionPath(const QString &uuid) { QList argumentList; argumentList << QVariant::fromValue(uuid); return asyncCallWithArgumentList(QStringLiteral("getActiveConnectionPath"), argumentList); } inline QDBusPendingReply getApConnectionPath(const QString &uuid) { QList argumentList; argumentList << QVariant::fromValue(uuid); return asyncCallWithArgumentList(QStringLiteral("getApConnectionPath"), argumentList); } inline QDBusPendingReply getApInfoBySsid(const QString &devName, const QString &ssid) { QList argumentList; argumentList << QVariant::fromValue(devName) << QVariant::fromValue(ssid); return asyncCallWithArgumentList(QStringLiteral("getApInfoBySsid"), argumentList); } inline QDBusPendingReply getDeviceListAndEnabled(int devType) { QList argumentList; argumentList << QVariant::fromValue(devType); return asyncCallWithArgumentList(QStringLiteral("getDeviceListAndEnabled"), argumentList); } inline QDBusPendingReply getStoredApInfo() { QList argumentList; return asyncCallWithArgumentList(QStringLiteral("getStoredApInfo"), argumentList); } inline QDBusPendingReply getWiredList(const QString &devName) { QList argumentList; argumentList << QVariant::fromValue(devName); return asyncCallWithArgumentList(QStringLiteral("getWiredList"), argumentList); } inline QDBusPendingReply getWirelessDeviceCap() { QList argumentList; return asyncCallWithArgumentList(QStringLiteral("getWirelessDeviceCap"), argumentList); } inline QDBusPendingReply getWirelessList(const QString &devName) { QList argumentList; argumentList << QVariant::fromValue(devName); return asyncCallWithArgumentList(QStringLiteral("getWirelessList"), argumentList); } inline QDBusPendingReply getWirelessSwitchBtnState() { QList argumentList; return asyncCallWithArgumentList(QStringLiteral("getWirelessSwitchBtnState"), argumentList); } inline QDBusPendingReply getWiredMainSwitchBtnState() { QList argumentList; return asyncCallWithArgumentList(QStringLiteral("getWiredMainSwitchBtnState"), argumentList); } inline QDBusPendingReply<> keyRingClear() { QList argumentList; return asyncCallWithArgumentList(QStringLiteral("keyRingClear"), argumentList); } inline QDBusPendingReply<> keyRingInit() { QList argumentList; return asyncCallWithArgumentList(QStringLiteral("keyRingInit"), argumentList); } inline QDBusPendingReply<> reScan() { QList argumentList; return asyncCallWithArgumentList(QStringLiteral("reScan"), argumentList); } inline Q_NOREPLY void passwordConnect(QString devName, QString ssid, QString type, QString psk, bool autoConnect) { QList argumentList; argumentList << QVariant::fromValue(devName) << QVariant::fromValue(ssid) << QVariant::fromValue(type) << QVariant::fromValue(psk) << QVariant::fromValue(autoConnect); callWithArgumentList(QDBus::NoBlock, QStringLiteral("passwordConnect"), argumentList); } inline Q_NOREPLY void setDeviceEnable(const QString &devName, bool enable) { QList argumentList; argumentList << QVariant::fromValue(devName) << QVariant::fromValue(enable); callWithArgumentList(QDBus::NoBlock, QStringLiteral("setDeviceEnable"), argumentList); } inline Q_NOREPLY void setWiredSwitchEnable(bool enable) { QList argumentList; argumentList << QVariant::fromValue(enable); callWithArgumentList(QDBus::NoBlock, QStringLiteral("setWiredSwitchEnable"), argumentList); } inline Q_NOREPLY void setWirelessSwitchEnable(bool enable) { QList argumentList; argumentList << QVariant::fromValue(enable); callWithArgumentList(QDBus::NoBlock, QStringLiteral("setWirelessSwitchEnable"), argumentList); } inline Q_NOREPLY void showAddOtherWlanWidget(const QString &devName) { QList argumentList; argumentList << QVariant::fromValue(devName); callWithArgumentList(QDBus::NoBlock, QStringLiteral("showAddOtherWlanWidget"), argumentList); } inline Q_NOREPLY void showCreateWiredConnectWidget(const QString &devName) { QList argumentList; argumentList << QVariant::fromValue(devName); callWithArgumentList(QDBus::NoBlock, QStringLiteral("showCreateWiredConnectWidget"), argumentList); } inline QDBusPendingReply<> showKylinNM(int type) { QList argumentList; argumentList << QVariant::fromValue(type); return asyncCallWithArgumentList(QStringLiteral("showKylinNM"), argumentList); } inline Q_NOREPLY void showPropertyWidget(const QString &devName, const QString &ssid) { QList argumentList; argumentList << QVariant::fromValue(devName) << QVariant::fromValue(ssid); callWithArgumentList(QDBus::NoBlock, QStringLiteral("showPropertyWidget"), argumentList); } inline QDBusPendingReply getDeviceConnectivity(const QString deviceName) { QList argumentList; argumentList << QVariant::fromValue(deviceName); return callWithArgumentList(QDBus::NoBlock, QStringLiteral("getDeviceConnectivity"), argumentList); } inline QDBusPendingReply getCableStateByDevice(const QString deviceName) { QList argumentList; argumentList << QVariant::fromValue(deviceName); return callWithArgumentList(QDBus::NoBlock, QStringLiteral("getCableStateByDevice"), argumentList); } Q_SIGNALS: // SIGNALS void activateFailed(const QString &errorMessage); void deactivateFailed(const QString &errorMessage); void deviceNameChanged(const QString &oldName, const QString &newName, int type); void deviceStatusChanged(); void hotspotActivated(const QString &devName, const QString &ssid, const QString &uuid, const QString &activePath, const QString &settingPath); void hotspotDeactivated(const QString &devName, const QString &ssid); void lanActiveConnectionStateChanged(const QString &devName, const QString &uuid, int status); void lanAdd(const QString &devName, const QStringList &info); void lanRemove(const QString &dbusPath); void lanUpdate(const QString &devName, const QStringList &info); void secuTypeChange(const QString &devName, const QString &ssid, const QString &secuType); void showAddOtherWlanWidgetSignal(const QString &display, const QString &devName); void showCreateWiredConnectWidgetSignal(const QString &display, const QString &devName); void showKylinNMSignal(const QString &display, int type); void showPropertyWidgetSignal(const QString &display, const QString &devName, const QString &ssid); void signalStrengthChange(const QString &devName, const QString &ssid, int strength); void timeToUpdate(); void wirelessDeviceStatusChanged(); void wirelessSwitchBtnChanged(bool state); void wiredMainSwitchBtnChanged(bool state); void wlanAdd(const QString &devName, const QStringList &info); void wlanRemove(const QString &devName, const QString &ssid); void wlanactiveConnectionStateChanged(const QString &devName, const QString &ssid, const QString &uuid, int status); }; namespace com { namespace kylin { typedef ::ComKylinNetworkInterface network; } } #endif kylin-nm/src/backend/sysdbusregister.h0000664000175000017500000000306515167646234017050 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include #include #include #include #include #include #include class SysdbusRegister : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "com.kylin.NetworkManager.interface") public: explicit SysdbusRegister(); ~SysdbusRegister(); private: // QString m_name; Q_SIGNALS: // Q_SCRIPTABLE void nameChanged(QString); // Q_SCRIPTABLE void computerinfo(QString); public Q_SLOTS: Q_SCRIPTABLE void systemRun(QString cmd); Q_SCRIPTABLE QStringList getWifiInfo(QString wifiName); Q_SCRIPTABLE bool appendWifiInfo(QString name, QString eap, QString inner, QString user); Q_SCRIPTABLE bool appendWifiUser(QString name, QString user); }; #endif // SYSDBUSREGISTER_H kylin-nm/src/backend/sysdbusregister.cpp0000664000175000017500000000617415167646234017407 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include #include SysdbusRegister::SysdbusRegister() { } SysdbusRegister::~SysdbusRegister() { } void SysdbusRegister::systemRun(QString cmd){ QProcess::execute(cmd); } QStringList SysdbusRegister::getWifiInfo(QString wifiName) { //返回名为wifiName的企业wifi的配置信息,包括eap,inner和用户列表 QStringList wlist; QString filename = "/usr/share/kylin-nm/wpaconn.conf"; QFile file(filename); if(!file.exists()) { return wlist; } QSharedPointer autoSettings = QSharedPointer(new QSettings(filename, QSettings::IniFormat)); wlist << autoSettings.get()->value("eap").toString(); wlist << autoSettings.get()->value("inner").toString(); int size = autoSettings.get()->beginReadArray(wifiName); for (int i = 0; i < size; ++i) { autoSettings.get()->setArrayIndex(i); wlist << autoSettings.get()->value("user").toString(); } autoSettings.get()->endArray(); return wlist; } bool SysdbusRegister::appendWifiInfo(QString name, QString eap, QString inner, QString user) { //向配置文件添加名为name的wifi配置,包括eap,inner和它的第一个用户 QString filename = "/usr/share/kylin-nm/wpaconn.conf"; QSharedPointer autoSettings = QSharedPointer(new QSettings(filename, QSettings::IniFormat)); autoSettings.get()->beginGroup(name); autoSettings.get()->setValue("eap", eap); autoSettings.get()->setValue("inner", inner); //以数组形式写入用户名 autoSettings.get()->beginWriteArray(name); autoSettings.get()->setArrayIndex(0); autoSettings.get()->setValue("user", user); autoSettings.get()->endArray(); return true; } bool SysdbusRegister::appendWifiUser(QString name, QString user) { //向名为name的wifi用户列表添加名为user的用户名 QString filename = "/usr/share/kylin-nm/wpaconn.conf"; QSharedPointer autoSettings = QSharedPointer(new QSettings(filename, QSettings::IniFormat)); autoSettings.get()->beginWriteArray(name); autoSettings.get()->setArrayIndex(0); //读到用户名列表长度并在队尾添加一个用户名 int size = autoSettings.get()->beginReadArray(name); autoSettings.get()->setArrayIndex(size); autoSettings.get()->setValue("user", user); autoSettings.get()->endArray(); return true; } kylin-nm/src/backend/kylinipv4arping.h0000664000175000017500000000524715167646234016745 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLIN_IPV4_ARPING #define KYLIN_IPV4_ARPING #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kylinarping.h" #include #include #include enum { POLLFD_TIMER = 0, POLLFD_SOCKET, POLLFD_COUNT }; class KyIpv4Arping : public QObject { Q_OBJECT public: explicit KyIpv4Arping(QString ifaceName, QString ipAddress, int retryCount=3, int timeout=1, QObject *parent = nullptr); ~KyIpv4Arping(); public: bool ipv4IsConflict() { return m_ipConflict; } QString getMacAddress() { return m_conflictMac; } int ipv4ConflictCheck(); private: void monoGetTime(struct timespec *ts); void saveMacAddress(const uint8_t *ptr, size_t len); void findBroadcastAddress(); int checkDevice(); int checkIfflags(unsigned int ifflags); int sendIpv4Packet(); int ipv4EventLoop(); int ipv4PacketProcess(unsigned char *buf, ssize_t len, struct sockaddr_ll *from); void setConflictFlag(bool isConflict); private: struct in_addr m_srcAddress; struct in_addr m_destAddress; int m_destAddressFamily; struct sockaddr_storage m_me; struct sockaddr_storage m_he; int m_ipv4Socket = 0; QString m_ifaceName; int m_ifindex; struct ifaddrs *m_ifa; struct ifaddrs *m_ifa0; QString m_ipv4Address; int m_retryCount; int m_timeout; bool m_ipConflict = false; QString m_conflictMac = nullptr; }; #endif kylin-nm/src/backend/kylinipv6arping.h0000664000175000017500000000662015167646234016743 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINIPV6ARPING_H #define KYLINIPV6ARPING_H //#include #include #include #include /* div() */ #include /* uint8_t */ #include /* UINT_MAX */ #include #include #include /* EMFILE */ #include #include /* close() */ #include /* clock_gettime() */ #include /* poll() */ #include #include #include //#include "gettime.h" #ifdef HAVE_GETOPT_H # include #endif #include /* getaddrinfo() */ #include /* inet_ntop() */ #include /* if_nametoindex() */ #include #include #ifndef IPV6_RECVHOPLIMIT /* Using obsolete RFC 2292 instead of RFC 3542 */ # define IPV6_RECVHOPLIMIT IPV6_HOPLIMIT #endif /* BSD-like systems define ND_RA_FLAG_HA instead of ND_RA_FLAG_HOME_AGENT */ #ifndef ND_RA_FLAG_HOME_AGENT # ifdef ND_RA_FLAG_HA # define ND_RA_FLAG_HOME_AGENT ND_RA_FLAG_HA # endif #endif #ifndef AI_IDN # define AI_IDN 0 #endif #include #include #include typedef struct { struct nd_neighbor_solicit hdr; struct nd_opt_hdr opt; uint8_t hw_addr[6]; } solicit_packet; class KyIpv6Arping: public QObject { Q_OBJECT public: explicit KyIpv6Arping(QString ifaceName, QString ipAddress, int retryCount=3, int timeout=1000, QObject *parent = nullptr); ~KyIpv6Arping(); public: bool ipv6IsConflict() { return m_ipv6Conflict; } void setIpv6ConflictFlag(bool conflict) { m_ipv6Conflict = conflict; } QString getConflictMacAddress() { return m_conflictMacAddress; } int ipv6ConflictCheck(); private: void monoGetTime (struct timespec *ts); void saveMacAddress (const uint8_t *ptr, size_t len); int getLocalMacAddress(const char *ifname, unsigned char *addr); int getIpv6ByName(struct sockaddr_in6 *addr); int buildSolicitationPacket(solicit_packet *ns, struct sockaddr_in6 *tgt, const char *ifname); int parseIpv6Packet(const uint8_t *buf, size_t len, const struct sockaddr_in6 *tgt); int readIpv6Packet(void *buf, size_t len, int flags, struct sockaddr_in6 *addr); int reciveAndProcessIpv6Packet(const struct sockaddr_in6 *tgt, unsigned wait_ms); private: int m_ipv6Socket = 0; QString m_ifaceName; QString m_ipv6Address; int m_retryCount; int m_timeoutMs; bool m_ipv6Conflict = false; QString m_conflictMacAddress = nullptr; }; #endif // KYLINIPV6ARPING_H kylin-nm/src/backend/kylinarping.h0000664000175000017500000000552415167646234016140 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINARPING_H #define KYLINARPING_H #include #include #include static cap_flag_value_t cap_raw = CAP_CLEAR; static const cap_value_t caps[] = { CAP_NET_RAW }; static void limit_capabilities() { cap_t cap_p; cap_p = cap_get_proc(); if (!cap_p) { qWarning()<<"cap_get_proc failed."; } cap_get_flag(cap_p, CAP_NET_RAW, CAP_PERMITTED, &cap_raw); if (cap_raw != CAP_CLEAR) { if (cap_clear(cap_p) < 0) { qWarning()<<"cap clear failed"< kylin-nm/src/backend/dbus_adaptor.h0000664000175000017500000003644215167651420016254 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef DBUS_ADAPTOR_H #define DBUS_ADAPTOR_H #include #include #include QT_BEGIN_NAMESPACE class QByteArray; template class QList; template class QMap; class QString; class QVariant; QT_END_NAMESPACE /* * Adaptor class for interface com.kylin.network */ class NetworkAdaptor: public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "com.kylin.network") Q_CLASSINFO("D-Bus Introspection", "" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" "") public: NetworkAdaptor(QObject *parent); virtual ~NetworkAdaptor(); public: // PROPERTIES public Q_SLOTS: // METHODS Q_NOREPLY void activateConnect(int type, const QString &devName, const QString &ssid); void activeWirelessAp(const QString &apName, const QString &apPassword, const QString &band, const QString &apDevice); Q_NOREPLY void deActivateConnect(int type, const QString &devName, const QString &ssid); Q_NOREPLY void deActivateConnectConcise(int type, bool concise, const QString &devName, const QString &ssid); Q_NOREPLY void deleteConnect(int type, const QString &ssid); Q_NOREPLY void setDeviceAutoConnectState(const QString &deviceName, bool state); void deactiveWirelessAp(const QString &apName, const QString &uuid); QString getActiveConnectionPath(const QString &uuid); QString getApConnectionPath(const QString &uuid); QStringList getApInfoBySsid(const QString &devName, const QString &ssid); QVariantMap getDeviceListAndEnabled(int devType); QStringList getStoredApInfo(); QVariantList getWiredList(const QString &devName); QVariantMap getWirelessDeviceCap(); QVariantList getWirelessList(const QString &devName); bool getWirelessSwitchBtnState(); bool getWiredMainSwitchBtnState(); void keyRingClear(); void keyRingInit(); void reScan(); Q_NOREPLY void passwordConnect(QString devName, QString ssid, QString type, QString psk, bool autoConnect); Q_NOREPLY void setDeviceEnable(const QString &devName, bool enable); Q_NOREPLY void setWiredSwitchEnable(bool enable); Q_NOREPLY void setWirelessSwitchEnable(bool enable); Q_NOREPLY void showAddOtherWlanWidget(const QString &devName); Q_NOREPLY void showCreateWiredConnectWidget(const QString &devName); void showKylinNM(int type); Q_NOREPLY void showPropertyWidget(const QString &devName, const QString &ssid); int getDeviceConnectivity(const QString deviceName); //获取网卡是否插入了网线 bool getCableStateByDevice(const QString deviceName); Q_SIGNALS: // SIGNALS void activateFailed(const QString &errorMessage); void deactivateFailed(const QString &errorMessage); void deviceNameChanged(const QString &oldName, const QString &newName, int type); void deviceStatusChanged(); void hotspotActivated(const QString &devName, const QString &ssid, const QString &uuid, const QString &activePath, const QString &settingPath); void hotspotDeactivated(const QString &devName, const QString &ssid); void lanActiveConnectionStateChanged(const QString &devName, const QString &uuid, int status); void lanAdd(const QString &devName, const QStringList &info); void lanRemove(const QString &dbusPath); void lanUpdate(const QString &devName, const QStringList &info); void secuTypeChange(const QString &devName, const QString &ssid, const QString &secuType); void showAddOtherWlanWidgetSignal(const QString &display, const QString &devName); void showCreateWiredConnectWidgetSignal(const QString &display, const QString &devName); void showKylinNMSignal(const QString &display, int type); void showPropertyWidgetSignal(const QString &display, const QString &devName, const QString &ssid); void signalStrengthChange(const QString &devName, const QString &ssid, int strength); void timeToUpdate(); void wirelessDeviceStatusChanged(); void wirelessSwitchBtnChanged(bool state); void wiredMainSwitchBtnChanged(bool state); void wlanAdd(const QString &devName, const QStringList &info); void wlanRemove(const QString &devName, const QString &ssid); void wlanactiveConnectionStateChanged(const QString &devName, const QString &ssid, const QString &uuid, int status); }; #endif kylin-nm/src/backend/kylinipv6arping.cpp0000664000175000017500000003043215167651420017265 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinipv6arping.h" #include #include #include #include "kylinarping.h" KyIpv6Arping::KyIpv6Arping(QString ifaceName, QString ipAddress, int retryCount, int timeout, QObject *parent) : QObject(parent) { m_ifaceName = ifaceName; m_ipv6Address = ipAddress; m_retryCount = retryCount; m_timeoutMs = timeout; m_ipv6Conflict = false; } KyIpv6Arping::~KyIpv6Arping() { } void KyIpv6Arping::monoGetTime (struct timespec *ts) { #ifdef CLOCK_MONOTONIC if (clock_gettime (CLOCK_MONOTONIC, ts)) #endif { static long freq = 0; if (freq == 0) freq = sysconf (_SC_CLK_TCK); struct tms dummy; clock_t t = times (&dummy); ts->tv_sec = t / freq; ts->tv_nsec = (t % freq) * (1000000000 / freq); } } int KyIpv6Arping::getLocalMacAddress(const char *ifname, unsigned char *addr) { # ifdef SIOCGIFHWADDR struct ifreq req; memset (&req, 0, sizeof (req)); if (((unsigned)qstrlen (ifname)) >= (unsigned)IFNAMSIZ) { return -1; /* buffer overflow = local root */ } memcpy(req.ifr_name, ifname, sizeof(ifname)); int fd = socket (AF_INET6, SOCK_DGRAM, 0); if (fd == -1) { return -1; } if (ioctl (fd, SIOCGIFHWADDR, &req)) { qWarning()<<"[KyIpv6Arping]"<<"get local mac address failed, errno" << errno; close (fd); return -1; } close (fd); memcpy (addr, req.ifr_hwaddr.sa_data, 6); return 0; # else /* No SIOCGIFHWADDR, which seems Linux specific. */ struct ifaddrs *ifa = NULL; struct ifaddrs *ifp = NULL; getifaddrs(&ifa); ifp = ifa; /* preserve the address of ifa to free memory later */ while (ifp != NULL) { if (ifp->ifa_addr->sa_family == AF_LINK && strcmp(ifp->ifa_name, ifname) == 0) { const struct sockaddr_dl* sdl = (const struct sockaddr_dl*) ifp->ifa_addr; memcpy(addr, sdl->sdl_data + sdl->sdl_nlen, 6); freeifaddrs(ifa); return 0; } ifp = ifp->ifa_next; } freeifaddrs(ifa); return -1; # endif } int KyIpv6Arping::getIpv6ByName(struct sockaddr_in6 *addr) { struct addrinfo hints, *res; memset (&hints, 0, sizeof (hints)); hints.ai_family = PF_INET6; hints.ai_socktype = SOCK_DGRAM; /* dummy */ hints.ai_flags = 0; int val = getaddrinfo (m_ipv6Address.toUtf8(), NULL, &hints, &res); if (val) { qWarning()<<"[KyIpv6Arping]" << m_ipv6Address <<"get addrinfo failed, errno" << val; return -1; } memcpy (addr, res->ai_addr, sizeof (struct sockaddr_in6)); freeaddrinfo (res); val = if_nametoindex (m_ifaceName.toUtf8()); if (val == 0) { qWarning()<<"[KyIpv6Arping]" <<"if_nametoindex failed, errno" << errno; return -1; } addr->sin6_scope_id = val; return 0; } int KyIpv6Arping::buildSolicitationPacket(solicit_packet *ns, struct sockaddr_in6 *tgt, const char *ifname) { /* builds ICMPv6 Neighbor Solicitation packet */ ns->hdr.nd_ns_type = ND_NEIGHBOR_SOLICIT; ns->hdr.nd_ns_code = 0; ns->hdr.nd_ns_cksum = 0; /* computed by the kernel */ ns->hdr.nd_ns_reserved = 0; memcpy (&ns->hdr.nd_ns_target, &tgt->sin6_addr, 16); /* determines actual multicast destination address */ memcpy (&tgt->sin6_addr.s6_addr, "\xff\x02\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x01\xff", 13); /* gets our own interface's link-layer address (MAC) */ if (getLocalMacAddress (m_ifaceName.toUtf8().constData(), ns->hw_addr)) { return sizeof (ns->hdr); } ns->opt.nd_opt_type = ND_OPT_SOURCE_LINKADDR; ns->opt.nd_opt_len = 1; /* 8 bytes */ return sizeof (*ns); } void KyIpv6Arping::saveMacAddress (const uint8_t *ptr, size_t len) { int index; char macAddress[64] = {0}; for (index = 0; index < len; index++) { snprintf(&macAddress[qstrlen(macAddress)], sizeof(macAddress) - qstrlen(macAddress), "%02X", ptr[index]); if (index != len - 1) { snprintf(&macAddress[qstrlen(macAddress)], sizeof(macAddress) - qstrlen(macAddress), "%s", ":"); } } m_conflictMacAddress = QString(macAddress); return ; } int KyIpv6Arping::parseIpv6Packet(const uint8_t *buf, size_t len, const struct sockaddr_in6 *tgt) { const struct nd_neighbor_advert *na = (const struct nd_neighbor_advert *)buf; const uint8_t *ptr; /* checks if the packet is a Neighbor Advertisement, and * if the target IPv6 address is the right one */ if ((len < sizeof (struct nd_neighbor_advert)) || (na->nd_na_type != ND_NEIGHBOR_ADVERT) || (na->nd_na_code != 0) || memcmp (&na->nd_na_target, &tgt->sin6_addr, 16)) { return -1; } len -= sizeof (struct nd_neighbor_advert); /* looks for Target Link-layer address option */ ptr = buf + sizeof (struct nd_neighbor_advert); int index; char macAddress[64] = {0}; uint8_t hw_addr[6] = {0}; getLocalMacAddress(m_ifaceName.toUtf8().constData(), hw_addr); for (index = 0; index < 6; index++) { snprintf(&macAddress[qstrlen(macAddress)], sizeof(macAddress) - qstrlen(macAddress), "%02X", hw_addr[index]); if (index != 5) { snprintf(&macAddress[qstrlen(macAddress)], sizeof(macAddress) - qstrlen(macAddress), "%s", ":"); } } QString localAddr(macAddress); while (len >= 8) { uint16_t optlen; optlen = ((uint16_t)(ptr[1])) << 3; if (optlen == 0) break; /* invalid length */ if (len < optlen) /* length > remaining bytes */ break; len -= optlen; /* skips unrecognized option */ if (ptr[0] != ND_OPT_TARGET_LINKADDR) { ptr += optlen; continue; } /* Found! displays link-layer address */ ptr += 2; optlen -= 2; saveMacAddress (ptr, optlen); if (!localAddr.isEmpty() && getConflictMacAddress() == localAddr) { break; } setIpv6ConflictFlag(true); return 0; } return -1; } int KyIpv6Arping::readIpv6Packet(void *buf, size_t len, int flags, struct sockaddr_in6 *addr) { char cbuf[CMSG_SPACE (sizeof (int))]; struct iovec iov = { .iov_base = buf, .iov_len = len }; struct msghdr hdr = { .msg_name = addr, .msg_namelen = sizeof (*addr), .msg_iov = &iov, .msg_iovlen = 1, .msg_control = cbuf, .msg_controllen = sizeof (cbuf) }; ssize_t val = recvmsg (m_ipv6Socket, &hdr, flags); if (val == -1) { return val; } /* ensures the hop limit is 255 */ for (struct cmsghdr *cmsg = CMSG_FIRSTHDR (&hdr); cmsg != NULL; cmsg = CMSG_NXTHDR (&hdr, cmsg)) { if ((cmsg->cmsg_level == IPPROTO_IPV6) && (cmsg->cmsg_type == IPV6_HOPLIMIT)) { if (255 != *(int *)CMSG_DATA (cmsg)) { // pretend to be a spurious wake-up errno = EAGAIN; return -1; } } } return val; } int KyIpv6Arping::reciveAndProcessIpv6Packet(const struct sockaddr_in6 *tgt, unsigned wait_ms) { struct timespec end; struct pollfd fds; /* computes deadline time */ monoGetTime (&end); div_t d; d = div (wait_ms, 1000); end.tv_sec = end.tv_sec + d.quot; end.tv_nsec = end.tv_nsec + (d.rem * 1000000); /* receive loop */ for (;;) { /* waits for reply until deadline */ struct timespec now; int val = 0; monoGetTime (&now); if (end.tv_sec >= now.tv_sec) { val = (end.tv_sec - now.tv_sec) * 1000 + (int)((end.tv_nsec - now.tv_nsec) / 1000000); if (val < 0) { val = 0; } } fds.fd = m_ipv6Socket; fds.events = POLLIN; val = poll (&fds, 1, val); if (val < 0) break; if (val == 0) return 0; /* receives an ICMPv6 packet */ // TODO: use interface MTU as buffer size uint8_t buf[1460]; struct sockaddr_in6 addr; val = readIpv6Packet(buf, sizeof (buf), MSG_DONTWAIT, &addr); if (val < 0) { if (errno != EAGAIN) qWarning()<<"[KyIpv6Arping]"<<"Receiving ICMPv6 packet failed"; continue; } /* ensures the response came through the right interface */ if (addr.sin6_scope_id && (addr.sin6_scope_id != tgt->sin6_scope_id)) continue; if (parseIpv6Packet(buf, val, tgt) == 0) { return 1 /* = responses */; } } return -1; /* error */ } int KyIpv6Arping::ipv6ConflictCheck() { struct sockaddr_in6 tgt; struct icmp6_filter filter; int retry = 0; limit_capabilities(); enable_capability_raw(); m_ipv6Socket = socket (PF_INET6, SOCK_RAW, IPPROTO_ICMPV6); disable_capability_raw(); if (m_ipv6Socket < 0) { qDebug()<<"[KyIpv6Arping]" <<"create ipv6 socket failed:"; return -1; } fcntl (m_ipv6Socket, F_SETFD, FD_CLOEXEC); /* set ICMPv6 filter */ ICMP6_FILTER_SETBLOCKALL (&filter); ICMP6_FILTER_SETPASS (ND_NEIGHBOR_ADVERT, &filter); enable_capability_raw(); setsockopt (m_ipv6Socket, IPPROTO_ICMPV6, ICMP6_FILTER, &filter, sizeof (filter)); int soDontRoute = 1; setsockopt (m_ipv6Socket, SOL_SOCKET, SO_DONTROUTE, &soDontRoute, sizeof(soDontRoute)); /* sets Hop-by-hop limit to 255 */ int multicastHopLimit = 255; setsockopt (m_ipv6Socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &multicastHopLimit, sizeof (multicastHopLimit)); int unicastHops = 255; setsockopt (m_ipv6Socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &unicastHops, sizeof (unicastHops)); int recvHopLimit = 1; setsockopt(m_ipv6Socket, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &recvHopLimit, sizeof (recvHopLimit)); disable_capability_raw(); drop_capabilities(); /* resolves target's IPv6 address */ int ret = getIpv6ByName(&tgt); if (ret < 0) { qWarning()<<"[KyIpv6Arping]"<<"get ipv6 by name failed."; close (m_ipv6Socket); return ret; } solicit_packet packet; struct sockaddr_in6 dst; ssize_t plen; memcpy (&dst, &tgt, sizeof (dst)); plen = buildSolicitationPacket(&packet, &dst, m_ifaceName.toUtf8().constData()); if (plen == -1) { qWarning()<<"[KyIpv6Arping]"<<"build solicit packet failed."; close (m_ipv6Socket); return -1; } while (retry < m_retryCount) { /* sends a Solitication */ if (sendto (m_ipv6Socket, &packet, plen, MSG_DONTROUTE, (const struct sockaddr *)&dst, sizeof (dst)) != plen) { qWarning()<<"[KyIpv6Arping]"<<"Sending ICMPv6 packet failed."; close (m_ipv6Socket); return -1; } retry++; /* receives an Advertisement */ ssize_t val = reciveAndProcessIpv6Packet(&tgt, m_timeoutMs); if (val > 0) { close (m_ipv6Socket); return 0; } else if (val == 0) { continue; } else { close (m_ipv6Socket); return -1; } } close(m_ipv6Socket); if (retry == m_retryCount) { return 0; } else { return -2; } } kylin-nm/src/backend/dbus_interface.cpp0000664000175000017500000000236615167651420017113 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "dbus_interface.h" /* * Implementation of interface class ComKylinNetworkInterface */ ComKylinNetworkInterface::ComKylinNetworkInterface(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) : QDBusAbstractInterface(service, path, staticInterfaceName(), connection, parent) { } ComKylinNetworkInterface::~ComKylinNetworkInterface() { } kylin-nm/src/backend/dbusadaptor.cpp0000664000175000017500000002030715167651420016441 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "dbusadaptor.h" #include #include #include #include #include #include #include const QByteArray GSETTINGS_SCHEMA_KYLIN_NM = "org.ukui.kylin-nm.switch"; const QString KEY_WIRELESS_SWITCH = "wirelessswitch"; const QString KEY_WIRED_SWITCH = "wiredswitch"; /* * Implementation of adaptor class DbusAdaptor */ DbusAdaptor::DbusAdaptor(MainWindow *parent) : QDBusAbstractAdaptor(parent) { // constructor qDBusRegisterMetaType >(); qDBusRegisterMetaType >(); qDBusRegisterMetaType >(); qDBusRegisterMetaType >>(); //setAutoRelaySignals(true)后会自动转发mainwindow发出的同名信号,因此不必再额外写一个转发 setAutoRelaySignals(true); } DbusAdaptor::~DbusAdaptor() { // destructor } //无线列表 QMap > DbusAdaptor::getWirelessList() { QMap > map; parent()->getWirelessList(map); return map; } bool DbusAdaptor::getWirelessSwitchBtnState() { return parent()->getWirelessSwitchBtnState(); } //有线列表 QMap> DbusAdaptor::getWiredList() { QMap> map; parent()->getWiredList(map); return map; } //有线开关 void DbusAdaptor::setWiredSwitchEnable(bool enable) { //todo mainwindow调用backend 对开关 打开/关闭 if (QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA_KYLIN_NM)) { QGSettings *gsetting = new QGSettings(GSETTINGS_SCHEMA_KYLIN_NM); if (gsetting->get(KEY_WIRED_SWITCH).toBool() != enable) { gsetting->set(KEY_WIRED_SWITCH, enable); } delete gsetting; gsetting = nullptr; } else { qDebug()<<"isSchemaInstalled false"; } } //无线开关 void DbusAdaptor::setWirelessSwitchEnable(bool enable) { //todo mainwindow调用backend 对开关 打开/关闭 // if (QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA_KYLIN_NM)) { // QGSettings *gsetting = new QGSettings(GSETTINGS_SCHEMA_KYLIN_NM); // if (gsetting->get(KEY_WIRELESS_SWITCH).toBool() != enable) { // gsetting->set(KEY_WIRELESS_SWITCH, enable); // } // delete gsetting; // gsetting = nullptr; // } else { // qDebug()<<"isSchemaInstalled false"; // } parent()->setWirelessSwitchEnable(enable); } //启用/禁用网卡 void DbusAdaptor::setDeviceEnable(QString devName, bool enable) { parent()->setWiredDeviceEnable(devName, enable); } //设置默认网卡 //void DbusAdaptor::setDefaultWiredDevice(QString deviceName) //{ // if (!checkDeviceExist(WIRED, deviceName)) { // return; // } // setDefaultDevice(WIRED, deviceName); // parent()->setWiredDefaultDevice(deviceName); // return; //} //QString DbusAdaptor::getDefaultWiredDevice() //{ // QSettings * m_settings = new QSettings(CONFIG_FILE_PATH, QSettings::IniFormat); // m_settings->beginGroup("DEFAULTCARD"); // QString key("wired"); // QString deviceName = m_settings->value(key, "").toString(); // m_settings->endGroup(); // delete m_settings; // m_settings = nullptr; // return deviceName; //} //void DbusAdaptor::setDefaultWirelessDevice(QString deviceName) //{ // if (!checkDeviceExist(WIRED, deviceName)) { // return; // } // setDefaultDevice(WIRELESS, deviceName); // parent()->setWirelessDefaultDevice(deviceName); // return; //} //QString DbusAdaptor::getDefaultWirelessDevice() //{ // QSettings * m_settings = new QSettings(CONFIG_FILE_PATH, QSettings::IniFormat); // m_settings->beginGroup("DEFAULTCARD"); // QString key("wireless"); // QString deviceName = m_settings->value(key, "").toString(); // m_settings->endGroup(); // delete m_settings; // m_settings = nullptr; // return deviceName; //} //删除 void DbusAdaptor::deleteConnect(int type, QString ssid) { if (type == WIRED) { parent()->deleteWired(ssid); } else if (type == WIRELESS) { //待实现 } else { qDebug() << "[DbusAdaptor] deleteConnect type is invalid"; } } //连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid void DbusAdaptor::activateConnect(int type, QString devName, QString ssid) { if (type == WIRED) { parent()->activateWired(devName,ssid); } else if (type == WIRELESS) { parent()->activateWireless(devName,ssid); } else { qDebug() << "[DbusAdaptor] activateConnect type is invalid"; } } //断开连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid void DbusAdaptor::deActivateConnect(int type, QString devName, QString ssid) { if (type == WIRED) { qDebug() << "deactivateWired"; parent()->deactivateWired(devName,ssid); } else if (type == WIRELESS) { parent()->deactivateWireless(devName,ssid); } else { qDebug() << "[DbusAdaptor] deactivateConnect type is invalid"; } } //获取设备列表和启用/禁用状态 QMap DbusAdaptor::getDeviceListAndEnabled(int devType) { QMap map; map.clear(); getDeviceEnableState(devType, map); return map; } //获取无线设备能力 QMap DbusAdaptor::getWirelessDeviceCap() { QMap map; parent()->getWirelessDeviceCap(map); return map; } //唤起属性页 根据网卡类型 参数2 为ssid/uuid void DbusAdaptor::showPropertyWidget(QString devName, QString ssid) { qDebug() << "showPropertyWidget"; parent()->showPropertyWidget(devName,ssid); } //唤起新建有线连接界面 void DbusAdaptor::showCreateWiredConnectWidget(QString devName) { qDebug() << "showCreateWiredConnectWidget"; parent()->showCreateWiredConnectWidget(devName); } //唤起加入其他无线网络界面 void DbusAdaptor::showAddOtherWlanWidget(QString devName) { qDebug() << "showAddOtherWlanWidget"; parent()->showAddOtherWlanWidget(devName); } //开启热点 void DbusAdaptor::activeWirelessAp(const QString apName, const QString apPassword, const QString band, const QString apDevice) { parent()->activeWirelessAp(apName, apPassword, band, apDevice); } //断开热点 void DbusAdaptor::deactiveWirelessAp(const QString apName, const QString uuid) { parent()->deactiveWirelessAp(apName, uuid); } //获取热点 QStringList DbusAdaptor::getStoredApInfo() { QStringList list; list.clear(); parent()->getStoredApInfo(list); return list; } //获取热点path QString DbusAdaptor::getApConnectionPath(QString uuid) { QString path; path.clear(); parent()->getApConnectionPath(path, uuid); return path; } //获取热点path QString DbusAdaptor::getActiveConnectionPath(QString uuid) { QString path; path.clear(); parent()->getActiveConnectionPath(path, uuid); return path; } QStringList DbusAdaptor::getApInfoBySsid(QString devName, QString ssid) { QStringList list; list.clear(); parent()->getApInfoBySsid(devName, ssid, list); return list; } void DbusAdaptor::showKylinNM(int type) { parent()->onShowMainWindow(type); } //扫描 void DbusAdaptor::reScan() { parent()->rescan(); } void DbusAdaptor::keyRingInit() { parent()->keyRingInit(); } void DbusAdaptor::keyRingClear() { parent()->keyRingClear(); } kylin-nm/src/backend/hotspot/0000775000175000017500000000000015167646234015132 5ustar fengfengkylin-nm/src/backend/hotspot/dlghotspotcreate.ui0000664000175000017500000000654615167646234021057 0ustar fengfeng DlgHotspotCreate 0 0 432 250 Dialog 0 0 120 32 9 9 16 16 34 6 80 20 215 210 90 30 315 210 90 30 76 60 90 20 175 55 200 32 76 105 90 20 175 100 200 32 76 150 90 20 175 145 200 32 QLineEdit::Password 350 157 18 9 kylin-nm/src/backend/hotspot/hotspot.pri0000664000175000017500000000023015167646234017341 0ustar fengfengINCLUDEPATH += $$PWD FORMS += \ $$PWD/dlghotspotcreate.ui HEADERS += \ $$PWD/dlghotspotcreate.h SOURCES += \ $$PWD/dlghotspotcreate.cpp kylin-nm/src/backend/hotspot/dlghotspotcreate.h0000664000175000017500000000324315167646234020660 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include #include namespace Ui { class DlgHotspotCreate; } class DlgHotspotCreate : public QDialog { Q_OBJECT public: explicit DlgHotspotCreate(QString wiFiCardName, QWidget *parent = nullptr); ~DlgHotspotCreate(); public Q_SLOTS: void changeDialog(); private Q_SLOTS: void on_btnCancel_clicked(); void on_btnOk_clicked(); void on_checkBoxPwd_stateChanged(int arg1); void on_leNetName_textEdited(const QString &arg1); void on_lePassword_textEdited(const QString &arg1); private: Ui::DlgHotspotCreate *ui; QString wirelessCardName; void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); bool isPress; QPoint winPos; QPoint dragPos; Q_SIGNALS: void updateHotspotList(); void btnHotspotState(); }; #endif // DLGHOTSPOTCREATE_H kylin-nm/src/backend/hotspot/dlghotspotcreate.cpp0000664000175000017500000001333015167646234021211 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see setupUi(this); this->setWindowFlags(Qt::FramelessWindowHint); this->setStyleSheet("background-color:white;"); ui->lbLeftup->setStyleSheet("QLabel{background-color:#266ab5;}"); ui->lbLeftupIcon->setStyleSheet("QLabel{background-image:url(:/res/h/no-pwd-wifi.png);background-color:transparent;}"); ui->lbLeftupTitle->setStyleSheet("QLabel{font-size:12px;color:#ffffff;background-color:transparent;}"); ui->btnCancel->setStyleSheet("QPushButton{border:1px solid #aaaaaa;background-color:#f5f5f5;}" "QPushButton:Hover{border:2px solid #629ee8;background-color:#eeeeee;}" "QPushButton:Pressed{border:1px solid #aaaaaa;background-color:#d8d8d8;}"); ui->btnOk->setStyleSheet("QPushButton{border:1px solid #aaaaaa;background-color:#f5f5f5;}" "QPushButton:Hover{border:2px solid #629ee8;background-color:#eeeeee;}" "QPushButton:Pressed{border:1px solid #aaaaaa;background-color:#d8d8d8;}"); ui->checkBoxPwd->setStyleSheet("QCheckBox::indicator {width: 18px; height: 9px;}" "QCheckBox::indicator:checked {image: url(:/res/h/show-pwd.png);}" "QCheckBox::indicator:unchecked {image: url(:/res/h/hide-pwd.png);}"); ui->lbLeftupTitle->setText(tr("Create Hotspot")); //创建个人热点 ui->lbNetName->setText(tr("Network name")); //网络名称: ui->lbSecurity->setText(tr("WLAN security")); //WLAN 安全性: ui->lbPassword->setText(tr("Password")); //密码: ui->btnCancel->setText(tr("Cancel")); //取消 ui->btnOk->setText(tr("Ok")); //确定 ui->btnOk->setEnabled(false); ui->cbxSecurity->addItem(tr("None")); //无 ui->cbxSecurity->addItem(tr("WPA and WPA2 Personal")); //WPA 及 WPA2 个人 ui->cbxSecurity->setCurrentIndex(1); connect(ui->cbxSecurity,SIGNAL(currentIndexChanged(QString)),this,SLOT(changeDialog())); } DlgHotspotCreate::~DlgHotspotCreate() { delete ui; } void DlgHotspotCreate::mousePressEvent(QMouseEvent *event){ if(event->button() == Qt::LeftButton){ this->isPress = true; this->winPos = this->pos(); this->dragPos = event->globalPos(); event->accept(); } } void DlgHotspotCreate::mouseReleaseEvent(QMouseEvent *event){ this->isPress = false; this->setWindowOpacity(1); } void DlgHotspotCreate::mouseMoveEvent(QMouseEvent *event){ if(this->isPress){ this->move(this->winPos - (this->dragPos - event->globalPos())); this->setWindowOpacity(0.9); event->accept(); } } void DlgHotspotCreate::on_btnCancel_clicked() { this->close(); Q_EMIT btnHotspotState(); } void DlgHotspotCreate::on_btnOk_clicked() { //nmcli device wifi hotspot [ifname ifname] [con-name name] [ssid SSID] [band {a | bg}] [channel channel] [password password] //example: nmcli device wifi hotspot ifname wlan0 con-name MyHostspot ssid MyHostspotSSID password 12345678 QString str; if(ui->cbxSecurity->currentIndex() == 0 ){ str = "nmcli device wifi hotspot ifname '" + wirelessCardName + "' con-name '" + ui->leNetName->text() + "' ssid '" + ui->leNetName->text() + "' SSID"; }else{ str = "nmcli device wifi hotspot ifname '" + wirelessCardName + "' con-name '" + ui->leNetName->text() + "' ssid '" + ui->leNetName->text() + "' password '" + ui->lePassword->text() + "'"; } Utils::m_system(str.toUtf8().data()); this->close(); Q_EMIT updateHotspotList(); } void DlgHotspotCreate::on_checkBoxPwd_stateChanged(int arg1) { if (arg1 == 0) { ui->lePassword ->setEchoMode(QLineEdit::Password); } else { ui->lePassword->setEchoMode(QLineEdit::Normal); } } void DlgHotspotCreate::on_leNetName_textEdited(const QString &arg1) { if(ui->cbxSecurity->currentIndex() == 0 ){ if (ui->leNetName->text() == ""){ ui->btnOk->setEnabled(false); } else { ui->btnOk->setEnabled(true); } }else{ if (ui->leNetName->text() == "" || ui->lePassword->text().size() < 5){ ui->btnOk->setEnabled(false); } else { ui->btnOk->setEnabled(true); } } } void DlgHotspotCreate::on_lePassword_textEdited(const QString &arg1) { if (ui->leNetName->text() == "" || ui->lePassword->text().size() < 5){ ui->btnOk->setEnabled(false); } else { ui->btnOk->setEnabled(true); } } void DlgHotspotCreate::changeDialog() { if(ui->cbxSecurity->currentIndex()==0){ ui->lbPassword->setEnabled(false); ui->lePassword->setEnabled(false); ui->checkBoxPwd->setEnabled(false); } else { ui->lbPassword->setEnabled(true); ui->lePassword->setEnabled(true); ui->checkBoxPwd->setEnabled(true); } } kylin-nm/src/backend/vpndbusadaptor.cpp0000664000175000017500000000460115167651420017164 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "vpndbusadaptor.h" #include #include #include #include #include #include #include /* * Implementation of adaptor class VpnDbusAdaptor */ VpnDbusAdaptor::VpnDbusAdaptor(vpnObject *parent) : QDBusAbstractAdaptor(parent) { // constructor qDBusRegisterMetaType >(); qDBusRegisterMetaType >(); qDBusRegisterMetaType >(); //setAutoRelaySignals(true)后会自动转发mainwindow发出的同名信号,因此不必再额外写一个转发 setAutoRelaySignals(true); } VpnDbusAdaptor::~VpnDbusAdaptor() { // destructor } //虚拟连接列表 QVector VpnDbusAdaptor::getVirtualList() { QVector vector; parent()->getVirtualList(vector); return vector; } //删除 void VpnDbusAdaptor::deleteVpn(QString uuid) { qDebug() << "delete vpn" << uuid; parent()->deleteVpn(uuid); } //连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid void VpnDbusAdaptor::activateVpn(const QString& connUuid) { qDebug() << "activate vpn" << connUuid; parent()->activateVpn(connUuid); } //断开连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid void VpnDbusAdaptor::deactivateVpn(const QString& connUuid) { qDebug() << "deactivate vpn" << connUuid; parent()->deactivateVpn(connUuid); } void VpnDbusAdaptor::showKylinVpn() { parent()->onShowMainWindow(); } kylin-nm/src/backend/utils.cpp0000664000175000017500000001154315167646234015302 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include #include #include #include #include #include #include #include /////////////////////////////////////////////////////////////////////////////// // The Utils class Utils::Utils(){} int Utils::m_system(char *cmd) { int status = 0; pid_t pid; clock_t start,finish; if ((pid = vfork()) <0) { qDebug()<<"failed to create a subprocess by using vfork"; status = -1; } else if (pid==0) { const char *new_argv[4]; struct sigaction sa_cld; sa_cld.sa_handler = SIG_DFL; sa_cld.sa_flags = 0; // 在子进程中放开SIGINT信号 sigemptyset(&sa_cld.sa_mask); sigaction (SIGINT, &sa_cld, NULL); sigaction (SIGQUIT, &sa_cld, NULL); new_argv[0] = "sh"; new_argv[1] = "-c"; new_argv[2] = cmd; new_argv[3] = NULL; // execl("/bin/sh","sh","-c" ,cmd,(char *)0); start = clock(); if (execve("/bin/sh",(char *const *) new_argv, NULL) <0) { qDebug()<<"failed to execve a shell command in function m_system"; exit(1); } else { exit(0); } } else { waitpid(pid,&status,0); finish = clock(); } //double duration = (double)(finish-start)/CLOCKS_PER_SEC; //qDebug()<<"It takes "< args; args<<(tr("Kylin NM")) <<((unsigned int) 0) < #include #include #include "singlepage.h" #include "../dbus-interface/kylinnetworkdeviceresource.h" QT_BEGIN_NAMESPACE class QByteArray; //template class QList; template class QMap; class QString; class QStringList; class QVariant; template class QVector; QT_END_NAMESPACE /* * Adaptor class for interface com.kylin.weather */ #include "vpnobject.h" class VpnDbusAdaptor: public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "com.kylin.vpnTool") public: VpnDbusAdaptor(vpnObject *parent); virtual ~VpnDbusAdaptor(); inline vpnObject *parent() const { return static_cast(QObject::parent()); } public: // PROPERTIES public Q_SLOTS: // METHODS //虚拟连接列表 QVector getVirtualList(); //刪除 根据网络名称 参数1 0:lan 1:wlan 参数2 为ssid/uuid Q_NOREPLY void deleteVpn(QString uuid); //连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid Q_NOREPLY void activateVpn(const QString& connUuid); //断开连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid Q_NOREPLY void deactivateVpn(const QString& connUuid); //just show void showKylinVpn(); Q_SIGNALS: // SIGNALS void vpnAdd(QStringList info); void vpnRemove(QString dbusPath); void vpnUpdate(QStringList info); void vpnActiveConnectionStateChanged(QString uuid, int status); void activateFailed(QString errorMessage); void deactivateFailed(QString errorMessage); }; #endif kylin-nm/src/backend/utils.h0000664000175000017500000000521415167646234014745 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* qt会将glib里的signals成员识别为宏,所以取消该宏 * 后面如果用到signals时,使用Q_SIGNALS代替即可 * #ifdef signals #undef signals #endif extern "C" { #include #include } */ /////////////////////////////////////////////////////////////////////////////// // wifi property struct typedef struct structWifiProperty{ QString objectPath; QString bssid; int priority; }structWifiProperty; /////////////////////////////////////////////////////////////////////////////// // The Utils class, used to do some assist function class Utils : public QObject { Q_OBJECT public: Utils(); static int m_system(char *cmd); public Q_SLOTS: void onRequestSendDesktopNotify(QString message); }; /////////////////////////////////////////////////////////////////////////////// // The UseQssFile class, set control style by using .qss file class UseQssFile { public: static void setStyle(const QString &style) { QString styleName = ":/qss/" + style; QFile qss(styleName); qss.open(QFile::ReadOnly); qApp->setStyleSheet(qss.readAll()); qss.close(); } }; /////////////////////////////////////////////////////////////////////////////// // The NetworkSpeed class, get the network upload and download speed class NetworkSpeed : public QObject { Q_OBJECT public: explicit NetworkSpeed(QObject *parent = nullptr); int getCurrentDownloadRates(char *netname,long int * save_rate,long int * tx_rate); //获取当前的流量,参数为将获取到的流量保 }; #endif // UTILS_H kylin-nm/src/backend/dbus.cpp0000664000175000017500000004506315167651420015074 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "dbus.h" #include #include #include #include #include #include #include const QByteArray GSETTINGS_SCHEMA_KYLIN_NM = "org.ukui.kylin-nm.switch"; const QString KEY_WIRELESS_SWITCH = "wirelessswitch"; const QString KEY_WIRED_SWITCH = "wiredswitch"; /* * Implementation of adaptor class DbusAdaptor */ DbusAdaptor::DbusAdaptor(QString display, MainWindow *m, QObject *parent) : QObject(parent), m_display(display), m_mainWindow(m) { // constructor qDBusRegisterMetaType >(); qDBusRegisterMetaType >(); qDBusRegisterMetaType >(); qDBusRegisterMetaType >>(); bool isServiceRegistered = QDBusConnection::sessionBus().interface()->isServiceRegistered(QStringLiteral("com.kylin.network")); if(!isServiceRegistered) { registerService(); } m_watcher = new QDBusServiceWatcher(QStringLiteral("com.kylin.network"),QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForOwnerChange, this); connect(m_watcher, &QDBusServiceWatcher::serviceOwnerChanged, this, &DbusAdaptor::onServiceOwnerChanged); m_pSysBusInterfaces = new QDBusInterface(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, QDBusConnection::systemBus()); if (m_pSysBusInterfaces->isValid()) { QDBusConnection::systemBus().connect(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, "sysWiredMainSwitchChanged", this, SLOT(onWiredMainSwitchBtnChanged(bool))); } else { qWarning() << Q_FUNC_INFO << __LINE__ ; } connectToMainwindow(); } DbusAdaptor::~DbusAdaptor() { if(mNetworkAdaptor) delete mNetworkAdaptor; } void DbusAdaptor::onServiceOwnerChanged(const QString &service, const QString &oldOwner, const QString &newOwner) { if (newOwner.isEmpty()) { bool success = registerService(); if (success) { m_watcher->deleteLater(); } qDebug() << "try to register service:" << success; return; } uint newOwnerPid = QDBusConnection::sessionBus().interface()->servicePid(newOwner); qDebug() << "newOwnerPid:" << newOwnerPid << ", myPid:" << QCoreApplication::applicationPid() << ", display:" << m_display; } bool DbusAdaptor::registerService() { mNetworkAdaptor=new NetworkAdaptor(this); QDBusConnection conn = QDBusConnection::sessionBus(); auto reply = conn.interface()->registerService(QStringLiteral("com.kylin.network"), QDBusConnectionInterface::ReplaceExistingService, QDBusConnectionInterface::DontAllowReplacement); if (reply.value() == QDBusConnectionInterface::ServiceNotRegistered) { return false; } bool res = QDBusConnection::sessionBus().registerObject("/com/kylin/network", this); if (!res) { QDBusConnection::sessionBus().interface()->unregisterService(QStringLiteral("com.kylin.network")); } return res; } //无线列表 QVariantList DbusAdaptor::getWirelessList(QString devName) { QList list; m_mainWindow->getWirelessList(devName, list); QVariantList vList; for (int i = 0; i < list.size(); ++i) { vList.append(QVariant::fromValue(list.at(i))); } return vList; } bool DbusAdaptor::getWirelessSwitchBtnState() { return m_mainWindow->getWirelessSwitchBtnState(); } bool DbusAdaptor::getWiredMainSwitchBtnState() { if (m_pSysBusInterfaces && m_pSysBusInterfaces->isValid()) { QDBusReply reply = m_pSysBusInterfaces->call("getWiredMainSwitch"); if (reply.isValid()) { bool status = reply.value(); return status; } } return false; } int DbusAdaptor::getDeviceConnectivity(const QString deviceName) { return m_mainWindow->getDeviceConnectivity(deviceName); } //获取网卡是否插入了网线 bool DbusAdaptor::getCableStateByDevice(const QString deviceName) { return m_mainWindow->getCableStateByDevice(deviceName); } //有线列表 QVariantList DbusAdaptor::getWiredList(QString devName) { QList list; m_mainWindow->getWiredList(devName, list); QVariantList vList; for (int i = 0; i < list.size(); ++i) { vList.append(QVariant::fromValue(list.at(i))); } return vList; } //有线开关 void DbusAdaptor::setWiredSwitchEnable(bool enable) { //todo if (m_pSysBusInterfaces->isValid()) { m_pSysBusInterfaces->call(QStringLiteral("setWiredMainSwitch"), enable); } else { qWarning()<< Q_FUNC_INFO << __LINE__ <<"m_pSysBusInterfaces is isValid!"; } if (!enable) { // int devType 0:lan 1:wlan int devType = 0; const auto devList = mNetworkAdaptor->getDeviceListAndEnabled(devType); for (auto it = devList.cbegin(); it != devList.cend(); ++it) { const QString &devName = it.key(); const auto connections = getWiredList(devName); for (const QVariant &conn : connections) { // 网卡名称,uuid,对应DBUS路径 const auto connInfo = conn.toList(); if (connInfo.size() >= 2) { // 只需确保有UUID即可 deActivateConnectConcise(0, true, devName, connInfo.at(1).toString()); //关闭有线开关触发的断开连接不清除连接信息 } } setDeviceAutoConnectState(devName,false); } } else { int devType = 0; const auto devList = mNetworkAdaptor->getDeviceListAndEnabled(devType); for (auto it = devList.cbegin(); it != devList.cend(); ++it) { const QString &devName = it.key(); setDeviceAutoConnectState(devName,true); } } #if 0 if (QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA_KYLIN_NM)) { QGSettings *gsetting = new QGSettings(GSETTINGS_SCHEMA_KYLIN_NM); if (gsetting->get(KEY_WIRED_SWITCH).toBool() != enable) { gsetting->set(KEY_WIRED_SWITCH, enable); } delete gsetting; gsetting = nullptr; } else { qDebug()<<"isSchemaInstalled false"; } #endif } //无线开关 void DbusAdaptor::setWirelessSwitchEnable(bool enable) { //todo mainwindow调用backend 对开关 打开/关闭 // if (QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA_KYLIN_NM)) { // QGSettings *gsetting = new QGSettings(GSETTINGS_SCHEMA_KYLIN_NM); // if (gsetting->get(KEY_WIRELESS_SWITCH).toBool() != enable) { // gsetting->set(KEY_WIRELESS_SWITCH, enable); // } // delete gsetting; // gsetting = nullptr; // } else { // qDebug()<<"isSchemaInstalled false"; // } m_mainWindow->setWirelessSwitchEnable(enable); } //启用/禁用网卡 void DbusAdaptor::setDeviceEnable(QString devName, bool enable) { m_mainWindow->setWiredDeviceEnable(devName, enable); } //设置默认网卡 //void DbusAdaptor::setDefaultWiredDevice(QString deviceName) //{ // if (!checkDeviceExist(WIRED, deviceName)) { // return; // } // setDefaultDevice(WIRED, deviceName); // parent()->setWiredDefaultDevice(deviceName); // return; //} //QString DbusAdaptor::getDefaultWiredDevice() //{ // QSettings * m_settings = new QSettings(CONFIG_FILE_PATH, QSettings::IniFormat); // m_settings->beginGroup("DEFAULTCARD"); // QString key("wired"); // QString deviceName = m_settings->value(key, "").toString(); // m_settings->endGroup(); // delete m_settings; // m_settings = nullptr; // return deviceName; //} //void DbusAdaptor::setDefaultWirelessDevice(QString deviceName) //{ // if (!checkDeviceExist(WIRED, deviceName)) { // return; // } // setDefaultDevice(WIRELESS, deviceName); // parent()->setWirelessDefaultDevice(deviceName); // return; //} //QString DbusAdaptor::getDefaultWirelessDevice() //{ // QSettings * m_settings = new QSettings(CONFIG_FILE_PATH, QSettings::IniFormat); // m_settings->beginGroup("DEFAULTCARD"); // QString key("wireless"); // QString deviceName = m_settings->value(key, "").toString(); // m_settings->endGroup(); // delete m_settings; // m_settings = nullptr; // return deviceName; //} //连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid void DbusAdaptor::activateConnect(int type, QString devName, QString ssid) { if (type == WIRED) { m_mainWindow->activateWired(devName,ssid); } else if (type == WIRELESS) { m_mainWindow->activateWireless(devName,ssid); } else { qDebug() << "[DbusAdaptor] activateConnect type is invalid"; } } void DbusAdaptor::setDeviceAutoConnectState(QString devName, bool state) { m_mainWindow->setWiredDeviceAutoconnect(devName,state); } //断开连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid void DbusAdaptor::deActivateConnect(int type, QString devName, QString ssid) { if (type == WIRED) { qDebug() << "deactivateWired"; m_mainWindow->deactivateWired(devName,ssid); } else if (type == WIRELESS) { m_mainWindow->deactivateWireless(devName,ssid); } else { qDebug() << "[DbusAdaptor] deactivateConnect type is invalid"; } } //断开连接 根据网卡类型 参数1 0:lan 1:wlan 参数2 true:只断开 false:断开并清除连接的网络信息 参数3 为ssid/uuid void DbusAdaptor::deActivateConnectConcise(int type, bool concise, const QString &devName, const QString &ssid) { if (type == WIRED) { qDebug() << "deactivateWired"; m_mainWindow->deactivateWired(devName, ssid, concise); } else if (type == WIRELESS) { m_mainWindow->deactivateWireless(devName,ssid); } else { qDebug() << "[DbusAdaptor] deactivateConnect type is invalid "; } } //delete连接 void DbusAdaptor::deleteConnect(int type,QString Uuid) { qWarning() << Q_FUNC_INFO << __LINE__ << type << Uuid; if (type == WIRED) { qWarning() << Q_FUNC_INFO << __LINE__; m_mainWindow->deleteWiredConnect(type,Uuid); } else if (type == WIRELESS) { qWarning() << Q_FUNC_INFO << __LINE__; m_mainWindow->deleteWireleeConnect(type,Uuid); } else { qWarning() << Q_FUNC_INFO << __LINE__ << "deleteConnect type is invalid"; } } //获取设备列表和启用/禁用状态 QVariantMap DbusAdaptor::getDeviceListAndEnabled(int devType) { QMap map; map.clear(); getDeviceEnableState(devType, map); QVariantMap vMap; QMap::const_iterator item = map.cbegin(); QString switchSettingFile = "/etc/kylin-nm/switch.conf"; QSettings switchSetting(switchSettingFile, QSettings::IniFormat, this); while (item != map.cend()) { if (switchSetting.contains(item.key())) vMap.insert(item.key(), QVariant::fromValue(switchSetting.value(item.key()))); else vMap.insert(item.key(), QVariant::fromValue(item.value())); item ++; } return vMap; } //获取无线设备能力 QVariantMap DbusAdaptor::getWirelessDeviceCap() { QMap map; m_mainWindow->getWirelessDeviceCap(map); QVariantMap vMap; QMap::const_iterator item = map.cbegin(); while (item != map.cend()) { vMap.insert(item.key(), QVariant::fromValue(item.value())); item ++; } return vMap; } //唤起属性页 根据网卡类型 参数2 为ssid/uuid void DbusAdaptor::showPropertyWidget(QString devName, QString ssid) { QString display = checkDisplay(); if (m_display == display) { m_mainWindow->showPropertyWidget(devName,ssid); } else { Q_EMIT showPropertyWidgetSignal(display, devName, ssid); } } //唤起新建有线连接界面 void DbusAdaptor::showCreateWiredConnectWidget(QString devName) { QString display = checkDisplay(); if (m_display == display) { m_mainWindow->showCreateWiredConnectWidget(devName); } else { Q_EMIT showCreateWiredConnectWidgetSignal(display, devName); } } //唤起加入其他无线网络界面 void DbusAdaptor::showAddOtherWlanWidget(QString devName) { QString display = checkDisplay(); if (m_display == display) { qDebug() << "showAddOtherWlanWidget"; m_mainWindow->showAddOtherWlanWidget(devName); } else { qDebug() << display; Q_EMIT showAddOtherWlanWidgetSignal(display, devName); } } //开启热点 void DbusAdaptor::activeWirelessAp(const QString apName, const QString apPassword, const QString band, const QString apDevice) { m_mainWindow->activeWirelessAp(apName, apPassword, band, apDevice); } //断开热点 void DbusAdaptor::deactiveWirelessAp(const QString apName, const QString uuid) { m_mainWindow->deactiveWirelessAp(apName, uuid); } void DbusAdaptor::passwordConnect(QString devName, QString ssid, QString type, QString psk, bool autoConnect) { m_mainWindow->passwordConnect(devName, ssid, type, psk, autoConnect); } //获取热点 QStringList DbusAdaptor::getStoredApInfo() { QStringList list; list.clear(); m_mainWindow->getStoredApInfo(list); return list; } //获取热点path QString DbusAdaptor::getApConnectionPath(QString uuid) { QString path; path.clear(); m_mainWindow->getApConnectionPath(path, uuid); return path; } //获取热点path QString DbusAdaptor::getActiveConnectionPath(QString uuid) { QString path; path.clear(); m_mainWindow->getActiveConnectionPath(path, uuid); return path; } QStringList DbusAdaptor::getApInfoBySsid(QString devName, QString ssid) { QStringList list; list.clear(); m_mainWindow->getApInfoBySsid(devName, ssid, list); return list; } void DbusAdaptor::showKylinNM(int type) { qDebug() << "display" << checkDisplay(); QString display = checkDisplay(); if (m_display == display) { m_mainWindow->onShowMainWindow(type); } else { Q_EMIT showKylinNMSignal(display, type); } } //扫描 void DbusAdaptor::reScan() { m_mainWindow->rescan(); } void DbusAdaptor::keyRingInit() { m_mainWindow->keyRingInit(); } void DbusAdaptor::keyRingClear() { m_mainWindow->keyRingClear(); } void DbusAdaptor::connectToMainwindow() { connect(m_mainWindow, &MainWindow::lanAdd, this, &DbusAdaptor::lanAdd); connect(m_mainWindow, &MainWindow::lanRemove, this, &DbusAdaptor::lanRemove); connect(m_mainWindow, &MainWindow::lanUpdate, this, &DbusAdaptor::lanUpdate); connect(m_mainWindow, &MainWindow::wlanAdd, this, &DbusAdaptor::wlanAdd); connect(m_mainWindow, &MainWindow::wlanRemove, this, &DbusAdaptor::wlanRemove); connect(m_mainWindow, &MainWindow::wlanactiveConnectionStateChanged, this, &DbusAdaptor::wlanactiveConnectionStateChanged); connect(m_mainWindow, &MainWindow::lanActiveConnectionStateChanged, this, &DbusAdaptor::lanActiveConnectionStateChanged); connect(m_mainWindow, &MainWindow::activateFailed, this, &DbusAdaptor::activateFailed); connect(m_mainWindow, &MainWindow::deactivateFailed, this, &DbusAdaptor::deactivateFailed); connect(m_mainWindow, &MainWindow::deviceStatusChanged, this, &DbusAdaptor::deviceStatusChanged); connect(m_mainWindow, &MainWindow::wirelessDeviceStatusChanged, this, &DbusAdaptor::wirelessDeviceStatusChanged); connect(m_mainWindow, &MainWindow::deviceNameChanged, this, &DbusAdaptor::deviceNameChanged); connect(m_mainWindow, &MainWindow::wirelessSwitchBtnChanged, this, &DbusAdaptor::wirelessSwitchBtnChanged); connect(m_mainWindow, &MainWindow::wiredMainSwitchBtnChanged, this, &DbusAdaptor::wiredMainSwitchBtnChanged); connect(m_mainWindow, &MainWindow::hotspotDeactivated, this, &DbusAdaptor::hotspotDeactivated); connect(m_mainWindow, &MainWindow::hotspotActivated, this, &DbusAdaptor::hotspotActivated); connect(m_mainWindow, &MainWindow::signalStrengthChange, this, &DbusAdaptor::signalStrengthChange); connect(m_mainWindow, &MainWindow::secuTypeChange, this, &DbusAdaptor::secuTypeChange); connect(m_mainWindow, &MainWindow::timeToUpdate, this, &DbusAdaptor::timeToUpdate); } QString DbusAdaptor::checkDisplay() { uint pid = 0; QDBusReply pidReply = connection().interface()->servicePid(message().service()); qDebug() << "caller pid: " << pidReply.value(); if(pidReply.isValid()) { pid = pidReply.value(); } else { return {}; } return displayFromPid(pid);; } QString DbusAdaptor::displayFromPid(uint pid) { QFile environFile(QStringLiteral("/proc/%1/environ").arg(QString::number(pid))); if (environFile.open(QIODevice::ReadOnly | QIODevice::Text)) { const QByteArray DISPLAY = qApp->property("sessionType").toString() == "wayland" ? QByteArrayLiteral("WAYLAND_DISPLAY") : QByteArrayLiteral("DISPLAY"); const auto lines = environFile.readAll().split('\0'); for (const QByteArray &line : lines) { const int equalsIdx = line.indexOf('='); if (equalsIdx <= 0) { continue; } const QByteArray key = line.left(equalsIdx); if (key == DISPLAY) { const QByteArray value = line.mid(equalsIdx + 1); return value; } } } return {}; } void DbusAdaptor::onWiredMainSwitchBtnChanged(bool state) { qDebug() << Q_FUNC_INFO << __LINE__ << state; Q_EMIT DbusAdaptor::wiredMainSwitchBtnChanged(state); } kylin-nm/src/backend/wifi-auth-thread.cpp0000664000175000017500000000474415167646234017311 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "wifi-auth-thread.h" #include WifiAuthThread::WifiAuthThread() { //检查连接状态 naManager = new QNetworkAccessManager(this); // QString url=QString("http://nmcheck.gnome.org/check_network_status.txt"); QString url=QString("http://connectivity-check.ubuntu.com/"); request.setUrl(QUrl(url)); naManager->get(request); //qDebug()<<"-------------------Network state check!----------------------"; connect(naManager,&QNetworkAccessManager::finished,this,[=](QNetworkReply* reply){ _isReply=true; QNetworkReply::NetworkError err = reply->error(); //qDebug()<<"----------------NetworkReply error:----------------------"<readAll().isEmpty()) _isConnect=false; } else _isConnect=false; }); } WifiAuthThread::~WifiAuthThread() { delete naManager; } void WifiAuthThread::run() { sleep(3); QDBusInterface interface( "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.NetworkManager", QDBusConnection::systemBus() ); QDBusReply reply= interface.call("CheckConnectivity"); if (reply.isValid()) { //qDebug()<<"---------------------wifi type:----------------------"< true wireless switch Wireless switch.true is open,false is close. true wired switch Wired switch.true is open,false is close. kylin-nm/README.md0000664000175000017500000001576615167651420012543 0ustar fengfeng## kylin-nm介绍 ### 简介 麒麟网络工具(kylin-network-manager,简称kylin-nm)是操作系统的网络前端,其主要功能有: 1、托盘栏图标及右键菜单 查看当前网络状态 左键点击托盘网络图标显示kylin-nm主界面 右键点击托盘网络图标显示右键菜单 2、对有线网络的管理 有线网络界面管理 连接/断开网络 网线拔插 多有线网卡支持 打开或关闭有线开关 查看或修改无线网络基本信息 3、对无线网络的管理 切换及刷新无线界面 查看无线网络列表 连接/断开无需密码的无线网 连接/断开有密码类型的无线网 无线网卡插拔 多无线网卡支持 打开或关闭无线开关 查看或修改无线网络基本信息 4、连接隐藏无线网络 连接无安全性的无线网络 连接WPA及WPA2个人安全性的无线网络 连接WPA及WPA2企业安全性的无线网络 连接WPA3个人安全性的无线网络 5、窗口样式调节 深色与浅色窗口样式切换 调节网络工具窗口透明度 普通窗口与具有毛玻璃效果的窗口的切换 ### 运行 麒麟网络工具的进程为kylin-nm,默认开机自启,依赖NetworkManger ### 命令行和dbus接口 kylin-nm进程的命令行如下: Usage: kylin-nm #### dbus接口: DBUS类型:SESSION BUS DBUS名称:com.kylin.network OBJECT路径:/ 接口名称:com.kylin.network #### dbus方法 getWirelessList 参数:无 返回值:QMap> 键:网卡名称 值:无线网络的集合(第一项为已连接网络信息,若无连接则为"--",否则为"名称/信号强度/加密类型/Uuid/是否为本机开放热点";其余为未连接的网络信息,为"名称/信号强度/加密类型/是否为本机开放热点" 功能:获取无线列表及每个对应无线网络的信号强度、加密类型等信息。 getWiredList 参数:无 返回值:QMap> 键:网卡名称 值:有线网络的集合("名称/UUID/对应DBUS路径"),若无已连接网络则第一项默认为"--" 功能:获取有线列表及每个对应的有线网络的uuid及dbus路径 setWiredSwitchEnable(bool enable) 参数:(bool)开启有线总开关(true)关闭有线总开关(false) 返回值:无 功能:打开或关闭有线总开关 setWirelessSwitchEnable(bool enable) 参数:(bool)开启无线总开关(true)关闭无线总开关(false) 返回值:无 功能:打开或关闭无线总开关 setDeviceEnable(QString devName, bool enable) 参数:(QString)devName 设备名称,(bool) enable 开启/关闭 返回值:无 功能:打开或关闭单个有线网卡开关 activateConnect(int type, QString devName, QString ssid) 参数:根据网卡类型 参数1 0:lan 1:wlan 参数2:网卡名称 参数3:uuid/ssid 返回值:无 功能:激活一个网络连接 deActivateConnect(int type, QString devName, QString ssid) 参数:根据网卡类型 参数1 0:lan 1:wlan 参数2:网卡名称 参数3:uuid/ssid 返回值:无 功能:断开一个网络连接 deActivateConnectConcise(int type, bool concise, const QString &devName, const QString &ssid) 参数:根据网卡类型 参数1 0:lan 1:wlan 参数2:是否只断开网络,不删除网络信息 参数3:网卡名称 参数4:uuid/ssid 返回值:无 功能:断开一个网络连接 concise: 当concise=true时,说明是关闭有线网卡或关闭有线开关导致的断开网络,不删除网络信息。否则主动断开连接删除网络信息 getDeviceListAndEnabled(int devType) 参数:int devType 0:lan 1:wlan 返回值:QMap 键:设备名称 值:bool 开启(true)关闭 (false) 功能:获取设备列表和启用/禁用状态 getWirelessDeviceCap 返回值:QMap 键:设备名称 值:int 0:不支持热点 3:支持2.4GHz 7:支持5GHz&&2.4Ghz 功能:获取无线设备能力(2.4G/5G) showPropertyWidget(QString devName, QString ssid) 参数:QString devName 设备名称 QString ssid 根据网卡类型 有线为uuid/无线为ssid 返回值:无 功能:唤起对应网络连接的属性页,可以对基础信息的显示或修改 showCreateWiredConnectWidget(QString devName) 参数:QString devName 有线网卡名称 返回值:无 功能:唤起新建有线连接界面 activeWirelessAp(const QString apName, const QString apPassword, const QString band, const QString apDevice) 参数:QString apName 热点名称 QString apPassword 热点密码 QString band 频带 QString apDevice 返回值:无 功能:开启移动热点 deactiveWirelessAp(const QString apName, const QString uuid) 参数:QStringList(名称/密码/设备名称/状态/UUID/频带) 返回值:无 功能: 断开移动热点 getStoredApInfo 参数:QStringList(名称/密码/设备名称/状态/UUID/频带) 返回值:无 功能:获取已保存的移动热点信息 getApInfoBySsid(QString devName, QString ssid) 参数:QString devName 设备名称 QString ssid 返回值:无 功能:通过名称获取已保存的移动热点信息 reScan() 参数:无 返回值:无 功能:申请重新进行无线扫描 keyRingInit() 参数:QString apName 热点名称 QString uuid 返回值:无 功能:断开移动热点 keyRingClear() 参数:无 返回值:无 功能: 断开移动热点 ### 原理与主要使用的技术 kylin-nm主要与NetworkManager进行交互,通过对应的dbus信号驱动UI界面的更新。并通过提供的dbus方法来进行网络相关功能的调用。 麒麟网络工具按照功能划分成两层:UI层和逻辑层。UI层实现网络资源的显示,以及用户的交互,逻辑层通过NetworkManager提供的Dbus接口,完成网络资源的管理及其配置。 ### 配置文件 kylin-nm的配置文件保存在如下路径: ~/.config/ukui/kylin-nm.conf 有线无线开关状态 设备状态 org.ukui.kylin-nm.switch 对应的gsetting值 (有线无线开关状态) ### 编译 cd kylin-nm mkdir build cd build qmake .. make sudo make install  ### 运行命令 ./kylin-nm ### 调试 kylin-nm目前并采用ukui-log4qt模块的日志功能。日志默认保存在~/.log/kylin-nm.log中 kylin-nm/AUTHORS0000664000175000017500000000004315167646234012321 0ustar fengfengshine kylin-nm/man/0000775000175000017500000000000015167651420012020 5ustar fengfengkylin-nm/man/kylin-nm.10000664000175000017500000000140215167646234013644 0ustar fengfeng.\" Man page for Kylin-nm .TH KYLIN-NM 1 "20 September 2019" "UKUI Desktop Environment" .\" Please adjust this date when revising the manpage. .\" .SH "NAME" kylin-nm \- The tool for the UKUI Desktop Environment .SH "SYNOPSIS" .B kylin-nm .SH "DESCRIPTION" The \fBkylin-nm\fR program is a part of the ukui-indicators, It provides network manager for the the UKUI Desktop Environment. Detect the system disk automatically, Can pop up and open the device. .PP This manual page documents the \fBkylin-nm\fR command. .P .SH "BUGS" .SS Should you encounter any bugs, they may be reported at: https://github.com/ukui/kylin-nm/issues .SH "AUTHORS" .SS This Man Page has been written for the UKUI Desktop Environment by: shine (2019) .SH "SEE ALSO"kylin-nm/man/kylin-vpn.10000664000175000017500000000123415167651420014031 0ustar fengfeng.\" Man page for Kylin-vpn .TH KYLIN-NM-VPN 1 "26 January 2026" "UKUI Desktop Environment" .\" Please adjust this date when revising the manpage. .\" .SH "NAME" kylin-vpn \- The tool for the kylin-nm .SH "SYNOPSIS" .B kylin-vpn .SH "DESCRIPTION" The \fBkylin-vpn\fR program is a part of the kylin-nm, It provides a user configuration interface for VPN. .PP This manual page documents the \fBkylin-vpn\fR command. .P .SH "BUGS" .SS Should you encounter any bugs, they may be reported at: https://gitee.com/openkylin/kylin-nm/issues .SH "AUTHORS" .SS This Man Page has been written for the UKUI Desktop Environment by: maqiang (2026) .SH "SEE ALSO"kylin-nm/man/kylin-nm-sysdbus.10000664000175000017500000000133415167651420015333 0ustar fengfeng.\" Man page for Kylin-nm-sysdbus .TH KYLIN-NM-SYSDBUS 1 "26 January 2026" "UKUI Desktop Environment" .\" Please adjust this date when revising the manpage. .\" .SH "NAME" kylin-nm-sysdbus \- The tool for the kylin-nm .SH "SYNOPSIS" .B kylin-nm-sysdbus .SH "DESCRIPTION" The \fBkylin-nm-sysdbus\fR program is a part of the kylin-nm, It provides auxiliary functions for network proxy and IP conflict detection. .PP This manual page documents the \fBkylin-nm-sysdbus\fR command. .P .SH "BUGS" .SS Should you encounter any bugs, they may be reported at: https://gitee.com/openkylin/kylin-nm/issues .SH "AUTHORS" .SS This Man Page has been written for the UKUI Desktop Environment by: maqiang (2026) .SH "SEE ALSO"kylin-nm/res.qrc0000664000175000017500000000000715167646234012551 0ustar fengfeng kylin-nm/res/0000775000175000017500000000000015167646234012045 5ustar fengfengkylin-nm/res/h/0000775000175000017500000000000015167646234012274 5ustar fengfengkylin-nm/res/h/show-pwd.png0000664000175000017500000000241115167646234014550 0ustar fengfengPNG  IHDR FtEXtSoftwareAdobe ImageReadyqe<iTXtXML:com.adobe.xmp sIDATxbgL P@@ }.@ @y @14q,H) T:07d%@<b5 UU$3n): `&| @٧ ]@\;A ?1/bv  @ ԁ t^J ^@ $ Ӂ;x ?b)  >ę@`]hx8q@# ٠t0T$U5. ?] rZ 6h-O@OqT=:騏IENDB`kylin-nm/res/h/right-pwd.png0000664000175000017500000000256615167646234014720 0ustar fengfengPNG  IHDRhOGtEXtSoftwareAdobe ImageReadyqe<iTXtXML:com.adobe.xmp ԟIDATxb9h@#P Ȩ@D:gr&d b2 ^qK @<a@ VfƁ$q́:9 ևJ$B%@1@}@]0ǃ {@d4 cAZ#IA,G`b(d(~;u Inb1 n@x;'*0Wˡ T\Aa @MQ nP (΅+a b?hb@Á"T@|(((RX B@^PdFOTp"?3I "l3hI14^`)RP@2/Po4Cda SC4IENDB`kylin-nm/res/h/hide-pwd.png0000664000175000017500000000265415167646234014512 0ustar fengfengPNG  IHDR HLtEXtSoftwareAdobe ImageReadyqe<iTXtXML:com.adobe.xmp Za`IDATxb+' UUUfPNx_[T$d^ZHTցL dt dGyxx=XO*Zijoowx>@  @3ֻ@[KT :5cp'A} q)<|WfGp ^@|awpb_`H#p*`0E0, fwYT EO'^|IENDB`kylin-nm/res/h/no-pwd-wifi.png0000664000175000017500000000315315167646234015144 0ustar fengfengPNG  IHDRagzTXtRaw profile type exifxڽa =q13A߇Mɦdfb%>AB˟ߍ~lj|s>K zv~win1.c~=\_0?ӽl~pĻHr8R<)JY<goS!Yխw")Ьv8{|ԏܭA?wLrl.ˊ{ˈe,e_k5l+>cQ#L E4'`lkh7ZR'r2 or<#E/zYt%52P|od&ANa=^"WLa8FGûQk̙]ڵB^ itrYmhV}VA02',is1֖TVHɰ#;1f sQ/p YW;\ q6`G췄*C1XH!5b9UL[hfɲɧbRN%KVcr̖Sι-W$N~ SlJSʌ8ۜ<*U+ZM5ײRZؒZk| -6kVvj=#xPTgWj0]\p?NBgbĭ@AKg{/\g(Aé܉_XBݕܗ&QG䨣! ZVW@}BS K*J]zw_6JHj4}*Etfe];eMa?׎~ľ$?7w]^}]G-E>7.Vz_^{]O_*Obz:}}iW{5g1'2ô7g6m>qex̤ ?r]qs i*y^xwwgoisrbKGD pHYs.#.#x?vtIME 7:IDAT8˥m0 O~S47G(#d# @_B"B@Ё?Ǔ(I/Z@/)I%"&+pk2 8sbx;F`/d>]ncb04 G'[XtZ^v}f4R+ZFW L55uZ]XR%}H: R`vmLng :@~u+ g#<IuTP+<IENDB`kylin-nm/res/hw/0000775000175000017500000000000015167646234012463 5ustar fengfengkylin-nm/res/hw/wifi6+-none-pwd.png0000664000175000017500000000137515167646234016023 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxWjA3*@I!@PT''tP2FAi( N\aGޚze|qavWw;og̞%vr Ӆji=xP&M9BiS9'TWr ><&Sb$ഭhd BA/ER1Լ-Dk@4=)̄z̦7gCq@ L$+)] @ENMʹ7z$vM?;jU;*sS=?vPRia|wf6]:.dwM N# :iD>F%iNq "Ej!^*NNl+'*+/X뙍 lY:( C66,hb-sQR 5T'^ S ?` ]1(.MS:OV 9@<{>x+,u*B}7UB˴ޱzK {KoRp<[jn}wߨ-", ۶>pZyS !1gFQ4!)rH#]+!" Gddf-gF@Y`4*1/IENDB`kylin-nm/res/hw/wifi6+-full.png0000664000175000017500000000123115167646234015225 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<;IDATxW=S@M QN,cG?!tvJGG_@쌝;;))cGe|1M0vfrݻݽ0LՉ㸎yh_)иpj Ne`W  IJTM٘$c@F@F8͹?4?_D mr"qO=<"sǩ/T 9۹&k o #.|_)g+HxiGpGވ3Oay#epC;.R3xnlQd?N42;RU:O))b#E"ARV֐TMXsFZsR< \3o-$i 4H8 ~]F%Ih; p=xWb @Y,q끥'.+ ͷ(JyF" f3OlI=ԋ g@#ۅ s /#Z$niAgk)Yc4v[I84ʆIENDB`kylin-nm/res/hw/wifi-none.png0000664000175000017500000000106515167646234015066 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxVn@4.pa pHPP$M OOIC)R@qn\@ 7JctZ~@4|sk{^ϫWw?!p z65&R +#+I| ~K%y@$$Α8gU;ʽٺ1k"kY: 0ȣCj1m/ڒ户U$\dkH$RCbg'+l~`3=Pe*Ho\jlD"_ <+Qvkր;&,@Hmq@Lb~E"p|@KfJ<1fy?|HeY'pO`HfduTĘӺ hHDwyƼBhgw5cV6UŝyŬN'k6DvxѮ1ӪUtL<O%gd"0dv:L;{mfY 1./.Ns@'<\xJ&A* yw%8ȅxtYgJ&=:؈7C Ĺsd--8sոB~ JWw*qKhp@<9r6" |){+)R!z pX=F"|= vubMxJq |p )e^甹mY͘}Zq-K,ƓdL""'ߘ'JB!^%g㵁m95c~W1NQe-S*e8dL㉒EU)k1/!ȏ8vI%jbg=SSHe@r Ew'4h[${r N<Ω]yɁm e pⅢYA[xmya{aF%?H41;*؄R7G2x4HQoN CexUc^!E6{vS; Fx)X/Vտ{Vs4D)s.j0HD-4'- ^؊ QsF-~hIT>۶>p\!X3D{LR@ ky%3d g_i1ˤa8K8?.RX .Y@?s*%i&IENDB`kylin-nm/res/hw/wifi6-low.png0000664000175000017500000000136315167646234015017 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxW1o`Q#A$D@: ebؑ6FF6dؑ)]*RC" %z_t9>qХtr}.Iܮu+\;p## o1ٯBQF"#?F Mt9'<_) w=vBLJ_?#XXVJy# ;IENDB`kylin-nm/res/hw/wifi-full.png0000664000175000017500000000105515167646234015070 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxVQ@ L8$Tܸܸ%  b* ``f3;Besf4Ļ'=o /^mۑg<* iL>A.@:0~MGeN Hs%q@u<|֌$=3+TJژu)`phx+ΰ0wb0:lpe%Or]QU AUl \cF`.V8qID9:%Kk 0k[1⿕C'PR6\Th C0*3a̓*"HJ‹ D IDATxb?2`̝h&D"LhbD7Hbz XmA@c{|FN;DgE n`b X!@~P*=T$ K@ X4%݇@*ـqy @T0 PN> @|(FZ u5DPr%da 4M@k8f1G u@SFYhlGn4b@& E(@iB`TN ҼYZ:r|?(C?H '>+5= aXeE UX~ Fa%A N-if82?H P~B15@hLl (&Bt6d?ʄ~t62V*As)FJnl43}&`^P8!`ldp@:b#W~)GhYQ T6.j>@ЦhR*bF+;>BK X uFR) ~hXG!IS4 ^ ȅ 4`ĕ@>G B Z -Ā\.| ,i 4 -@ EhM\1 ?`iAM~"!VaQL7S b? > gnaK|KXGoC{a+mLeD+QGNx &fIENDB`kylin-nm/res/hw/wifi6-medium.png0000664000175000017500000000134615167646234015477 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxVkSQJ&%`Ct qsԭ[uS/hFǺ"FAi Kj61#ۗ~qߏ{sL?ѨaZէ;H@VsP= @*Ȋ3hH#ƹH4O='Z7"s+~@AOߛIP EK5@& p̩IdZʁ J!0D?Ća}  a7y ÌyXstB )Myt#҇~%x+֕@$D-蹠F%ivuOI gieYkV<@_~ʕM\ڶ\Y聮}eM($P/rqAku{cFh(*^ӜJ!.\ |<0Tdklf ;vS`"A;2I^0Vr1il+|fj1RptWs1]ɺ>ыН3F[qB0!^b[S/IW J2]XcS쾑4nVҒ? AziIENDB`kylin-nm/res/hw/wifi-high.png0000664000175000017500000000113515167646234015044 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxVNA `ACrZ؂ vvpvvbg|~~Y[6\C! Rhoٌ+w 6Lrvg͛=-vc,MހY#6&-E !yds@:ʒ|$K]K SF{2|JA-R>QF,U,%)xn%MD2TԐ؃)C#,>aѷ+QJ@p$|=o EN 2|?k3YX# DGIWtV$"c( [DR:cS{x 9xBc/1:)&۠c_Ũek#VS*I{髓n܏Qs$H5D&{'|z 1kϵB HtHҝ8W BsWoFCDqF :g:g&kl-˾PQphIENDB`kylin-nm/res/hw/wifi6+-high.png0000664000175000017500000000130115167646234015200 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<cIDATxVKBaES*Ư4 JJL1 >0-,f.CaCreQMb<TV4^q?!rXC3>F~ִB}`7VB 7(; /x_v&JOxL`[BF{;f*lO*MxC=\LK_9NBM<DT7&#3Q6u.k$ekiO FFn|}Xg?<h5ߑ4P HeĪ  55R4`"P D~M%$Tk> naXW pUˌu߱=*G5wEf ~ "CKz6 wT Kjh%,.61^Beyx{oe |sh\ӳ-}?SCfHOZ,b ÀDeXFަ{Fk\fcm;tunN̞}IO͈qd/q^pr;*CsztXAi':]-a&#' Arv˕r9UPnKQ% ռ[9WEKId  2QvUx-]uф>/[W'kN_IENDB`kylin-nm/res/hw/wifi6+-medium.png0000664000175000017500000000131015167646234015541 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<jIDATxVK[Q}(A!t J, ϭknM4EKq3B`.o0:@zn}1y&/]9^g `0,Ԡ%-'a6$0'L MNBUNl+.(]OHT]/1)`H~0l`/+B .I#QZrc4! !uے_iJv¤< Ce*1ߩ!E1{)d> <DQ/`=p-wMKkLtj}\6=%i Cw@eT3 }@X3@⑗t%$5gM7qF0ki=ʣ% x>!IENDB`kylin-nm/res/hw/wifi6+-none.png0000664000175000017500000000126215167646234015226 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<TIDATxVJAI " L#H IF,KK?#`cB+!12{&yq`ؽe7ylL& U*FkIXd4 ~u`; ~`CxIHNj~5`i -4pr[G[(Ė&KԀ7D M}fz>C&5aZ*3VF>= 0&ܚT6=v^y.1 _rD*MOܞ&Hq.B%k n.zsڪf*9&NpٷN-`eyX5)Iuc<;#=;EM&u+NS','+XHJD/&~qI D߱@|bb0Y땀'ކi&6& Dʰh*Mr ghY@w<[<nTte"v/)%c)|y̙iQ -va%TE+/_ۂLw,eLk^^Mfߒ73GIENDB`kylin-nm/res/hw/wifi6-high-pwd.png0000664000175000017500000000144315167646234015724 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxWnA E.$7i,@@BTKG$%aP%4s4 `)z pJH;{;v6T0L1l4 $*5 ;pI /?SxLMEm Np!3H;ZwӋu o/BG@#1#V0RSȬz] ÖH-sjs?{- nˌy_T3cs4EFBnm?%dUw6> R.,jbi5uo=THh(cK pAe8{c[vzA^3KmtHG 34$PzaNq2F:HԘ.#*5juV nkƹOl6nC/؉$N#y75wFyGEi5xU3](X+ uX ,<]If2q !Â'*Լ-Wk b5ϻfY'H;9m.4g{˔+0v@2,%|$e%+H':]n--,DW5R(MN} 4R[Reqs3 8>8՚rod֮Id33+9H-28*6ub`,IO8|VHb;Jieᖨ(KUBziS g=*vC4H}˽%Pzֈ8+Obn W O*l2S.t,=aj-G10K hsRѝd[^*ԊyѫAk>26b덍i'w^e3<07;^!L Oʵe!&zeS8+!-O99$'A}A%_3p4TEd8>t7 r_4{)@.0%VHH=Ƿ7(_IENDB`kylin-nm/res/hw/wifi6-full-pwd.png0000664000175000017500000000137215167646234015750 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxVr@չfUY¬B5, R 첲:, 3VACyy\OYMHwfGt۽W6c_6.}xCk5I`m<\\o F >`?UDDi{|sc$Mkݮ$M Z7#<22rV"Y(R&7?ȴ3=+}Ա> SI|s ߇w3#wE7®>o r)ת4OHf&)BpW+unL>NJ:D˨DJ[ x#`ѮDc*%v%1䕈'"_o[qlOś.)ts] !đ4LMEf%7;$R͞FL:+Ѕ/ qH%\;dIXBf^H߿jDƺ~(8+@"dʳ.I#w;Q`-~u,$]ASWᶁu<ļ9/;$1{Khr@8`ރv@j3b1[|I6E5g}ة D]\g (V-]2TY숮kxeVzŸ]}tkyiV; V@SB^$V IENDB`kylin-nm/res/hw/wifi-medium.png0000664000175000017500000000113615167646234015406 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxV=OP-2I0: .Ln'O` :8PHtDX4sSҼ5~ I`ܻIENDB`kylin-nm/res/hw/wifi6+-low.png0000664000175000017500000000130015167646234015061 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<bIDATxV=KcA}OE"faILOnKK;)-mlYºEVyM!,=ul̇^y9gνwE+[^o /h?tfA؄3&'*~D > '"24UqI׀#R P50wQ~oMCU*z.$r^,X 5?2+ :5R3r.Ȱ3qO>`ѯR @s<Sϲ1ٝc$ni?,pGy9Ӷ , 搲uOT H""'9uF-iv@DR@>H g'(Ψݙ oTlbn)zw ^ vz!`'ш$BJwކ4{MR;cQ~ CmXrƜD@s2缊nIĞxjx*ZoXxKƫbٽ'بmҐE 2},_)o.$^X;HQ^H<݆MG@[}=ۻ]'w 0vIENDB`kylin-nm/res/hw/wifi6-none-pwd.png0000664000175000017500000000142515167646234015744 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxW=kAStਐ(AH\DM R?!eʔ.]:eʔjr)r bg+,p Qވa}8 ۝y;fvy,Z:vOj?@η0ʘй ƕp^E /sÿ  Hiprvu-/%t{Ų6SOxg)B@&©M`8ȁ {UB`g287brp_p`hBq[WҌyXsz[4 L=s-3i7o*a< BNDV#X%GRjW*i|!% O@$-/G݊co?*Y";<ƺȕn@"03!ddl%7#˱LN!P 3C⚦N~vz ˈ8uS)b~]:y`>H h3>HC&Vj:ƔItc崴\R쎗y#psBKRENM2"-hFI$Ǽ5w!mH$S/`#!HP~'I}iR?g憉1Mt"=E]wȘ!(Kn/la&T<МHm dmxOJ:,n=wް42Qf= d ,޹ c9`' -J@Ӱ9}OWRk9=s O}!αL?,]\b}_hRZ@UQ 0en*\`IENDB`kylin-nm/res/hw/wifi6-medium-pwd.png0000664000175000017500000000145415167646234016267 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxWkSQ~7&P24D0:XAN?nvf$ft[!.p0 uHYB"w^}t:;?]3cX40l[\Ƙ^Ta,cH@ z@_cp (݋DډxJz#2Jy:6Y ŀ99 nȪ}=0JSvP6`0lTJ# @~$of84}ϭ@(`XW*^SŒsǸsW' Ti~VLQ)#L5ě񷕰<@j*BDhFp7:Rʪtw,a"a;VBmO?+o.#<\٤ⁱYAUrF`: KXݍI0tqwV{rCT?( tZ`UsS滴t.LC@d2"ФZl}uE馸3rAMI (~>Xj^&rYL^0FBn^Y''"xwSm]zgh| kg AbBb.!څՇJZKRN}'ZNI>ߖz cbGse}ޗQ\1.΍}F(yL oG5,hjIENDB`kylin-nm/res/hw/wifi6-none.png0000664000175000017500000000131615167646234015153 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<pIDATxV=kA&:UXk *\t韐2K)2e4 ٠ A$7mlt9=iwgμJ?岁͡}c2T|K1 }_* :?*"Ds|;7q\6,97v /ZWwl}@"mbrx`+:0NSu~9pᐠTBH]@+X -_5-hM9q5%Xw=ÿ1=8LJ3εL2%̿ W D818hKIS=bqBk{HZv݊7xbi/?*i"'Fȕ=@"02)kTP0 ?r@?.#DZ,j'(!sϖO~j=LjrksTs i$+U:Y`>H h3=ICFNjƘucԵLX nK}8oy.I)&7IpLxQ_pθy//Z!IvWqN.!,8t܅Y lֲ[IENDB`kylin-nm/res/hw/wifi-medium-pwd.png0000664000175000017500000000122715167646234016177 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<9IDATxVNP]H~nn 1bLM0@ ,\s\^rRz߽{^K&É|Rրjw?v :P܄ Qx )U=Fıۖ`@L̪=*IkVLRH8Hm+RŲH<\5XK`4#ܡw=qb_I>e%SucEVxϳf+ṖQY ak^6ը/I_{@aDaVFMO{o+Xxt0W6ix`째EP3# DS0ˢ]nܳn퓵\|"N\5otTsjRQV]{,D0MO(3>CVhZ䦕'r2HHȍpjwQ3);ɉx4\EWi x{K!9EB,/(>ΰn;`y-~AxpwG }؊~knИ5>T5ݘW [\>.T/]XS֛=-s` ׳c_R?d`8,v%IENDB`kylin-nm/res/hw/wifi6+-full-pwd.png0000664000175000017500000000134115167646234016017 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxWr@2* tXYTV0V֚aa *+̬.3ܜ%9oI޻Q-vWq%c l' ASO&")#5jg۽%H]#ծ F8>c ٪qtlJڢlvo>§Ud):M~DZGO|k <o c_W ITa@bk >hצ4EflV)Qp < K>P[M߈})VAF щ7$M@о2:.a>+NiRep ̈́`+c >! IE:"zHd>;Zp9q T+^< i{#fMĘI}BzxEһ0p|„kE@տ7FTn^VSpwuB}닍*HDڒye-g5DA`J)b$$ڔ[C'hm]pl_j/~x (1nmyH{%3dŻ559q&{3:C`('ѼMQ4ЧxaXIENDB`kylin-nm/res/hw/wifi-none-pwd.png0000664000175000017500000000117215167646234015655 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxV1O@vM`\BbI$F\ upСt tF||MǵK]q؏U7uѥC8&C-dA$L Ų1o0ȨgSPe.MD8>7 3 2iC)u"4'6@ABƙͲ)_*+3)+Xs`Dy)7KR{ʝx0/Q85$J S0L DB/9#33İU{#xP"f8&Rө f<,/jP۷BDs^ӭ2n dmHc$yW@ 8@/:a̅VdN-6u(^X;} xw8N`%M]/[1X5%'aZr)BRmdHlB.8'Y$I49;0qB= e{}ƻv+= }Uu!o$A2fzhLfh9;{E`\7['IENDB`kylin-nm/res/hw/wifi6+-high-pwd.png0000664000175000017500000000141515167646234015776 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxW1o@Q2!KY E a@BPl'knMnmXTu# HEJT^ƱXO;} |oih? 0hlSPf qZ+S+6#Q7GjG{)Hukj@ۊF! 9wO7eH[1V- KH4vCќQSydּ`ci`H%&[3) 9)pӵLFy}[g pQ3]"iv;"> Dm){isiuDO%4hݛшf& ޚQ/N2zxH8;!廚* Vlc,63wG 35(q,ZHDthb,qU$41h: Wi ,9Ԗ:cցUE(>(H!RAm*5 yG+D_F J}-d{ =_v-}(T~jKW3֖l'psb =eȝ7*cKJlǎ9^v r>U PdJtu DR2pg=2Ͻ~s}/t L5p-8K,(juK*c槏IENDB`kylin-nm/res/hw/wifi6-full.png0000664000175000017500000000126215167646234015156 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<TIDATxWvA)8LL] Hpu 4_p5p .p/NIwe;睝ngy7,`Zчwj 9& <x kP[ĬQ}'h3=ƹk4O]0vN xX9xo,B2PX J<|O"=_裎 }T<2nk]1~wGp4۪+/x )cnz|1oj6} weΈthm|# a4&,Is*.Sļ{_)>P5[׶@٣9f^6]eT~f+$~)a*x(%kV, û(]¬T /c``B')+dN ncFml RU ȞwG@hINt[ $X#Qb%0]I%Pᾁu"Ģ9_wWYY%H]6'rÁ EKId*8drnWM@tG'2lWV`֔`&>IENDB`kylin-nm/res/hw/wifi-low-pwd.png0000664000175000017500000000121315167646234015513 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<-IDATxVNP# ԁ:0؅01: |##.ƄAt@. ^sG5,䤴s;َPY W]J=KB&08&B@-"FRp@r'e(΅ g02)B)u"/4o$$5Ա#)_ *+Ӎ+\Xs`gyܜ /I5(Ń|C2 ViP4 P+%'z`fC5x4Ԩ/d$= Gڄ$CJc:)ĖXmjK̰>TҌ'2x>rf%Їs ׷:ả: 2[hUzv҉kHū؊x灾Xުܮŗ-,\0Z,t9JK2Cq6!~֓$!#=$ڳ.^.ﹻs 5/\X *4[B]tTN4af(8[E5K(- IENDB`kylin-nm/res/l/0000775000175000017500000000000015167646234012300 5ustar fengfengkylin-nm/res/l/network-online.png0000664000175000017500000000062615167646234015765 0ustar fengfengPNG  IHDR szz pHYs  ~HIDATXc?@}08?#!FFFXr^AO`^`4 :`uF0P'VeIn0"U/O<0\`]R`Q/ܟBf@Q<T@D9C!~D1yx b@-OХ9XPb޽xp>3> Û?vE>!QE ݀K߿$z߿:^SCl```( v g@Hht`xm,IENDB`kylin-nm/res/l/network-offline.png0000664000175000017500000000077215167646234016125 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxb`  t_$Hi;i[x]`(uF0Q:`Pkn' CK z.1 1\ k ir,P7ܸX.*UKoTHjͥz?zhs0PdqIx⻤@4v2;ߑ L6 Y aH K[Gr0aA |zZ, f, /fk$ jYƨ F he߿@>___O?j@,o^EqiFZI^i&rshRx4-XHbh@zfW[IENDB`kylin-nm/res/l/network-offline.svg0000664000175000017500000000234115167646234016132 0ustar fengfeng kylin-nm/res/l/network-online.svg0000664000175000017500000000142115167646234015772 0ustar fengfenggnome-dev-ethernet32kylin-nm/res/g/0000775000175000017500000000000015167646234012273 5ustar fengfengkylin-nm/res/g/down_arrow.png0000664000175000017500000000016115167646234015160 0ustar fengfengPNG  IHDR8IDAT]I g>ha)`'Q)5as,ӽwIENDB`kylin-nm/res/g/close_black.png0000664000175000017500000000031515167646234015241 0ustar fengfengPNG  IHDR;0IDATH E-a'{n &%zg8V__5Ir1/RʵQ"h 8t[LީVl㭘lb0yiPqRzZUɶt,>s~8_ k^WJIENDB`kylin-nm/res/g/close_white.png0000664000175000017500000000023015167646234015301 0ustar fengfengPNG  IHDR;0_IDATHA 0 DzKT!EBJX/BDd_|${w"ͷ?.RgWL=;EQOR*2OIENDB`kylin-nm/res/w/0000775000175000017500000000000015167646234012313 5ustar fengfengkylin-nm/res/w/wifi6+-full.png0000664000175000017500000000133415167646234015061 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<~IDATxV!Sa ∬:\z:J.p8qEv-|tjfvwo߾KWwoIa}&vMa`Oz41p%@.`y"mɲa2Xݒ'Myg8@'?B%^, )wr'<|d] +{\$+e/wd&A*= V o;@_ԋ00Ȉ~ umD@ͤ8%S3vyPw`&ŊSxm?8[ch"&m(g3fd/.lKY9UM?FuJ'ipm<\b\ ][g44t&ް9 S=>avj d'9E vNd'gӥ%sS=Q)H\خklwvx@׎k-Jj=5f\u--@_.QOPY,s`]n 'AkiI7^+<1 <3>2+Lx:-*2IENDB`kylin-nm/res/w/wifi-none.png0000664000175000017500000000106515167646234014716 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxVn@4.pa pHPP$M OOIC)R@qn\@ 7JctZ~@4|sk{^ϫWw?!p z65&R +#+I| ~K%y@$$Α8gU;ʽٺ1k"kY: 0ȣCj1m/ڒ户U$\dkH$RCbg'+l~`3=Pe*Ho\jlD"_ <+Qvkր;&,@Hmq@Lb~E"p|@KfJ<1fy?|HeY'pO`HfduTĘӺ hHDwyƼBhgw5cV6UŝyŬN'k6DvxѮ1ӪUtL<O%gd"0dv:L;{mfY 1./.Ns@'<\xJ&A* yw%8ȅxtYgJ&=:؈7C Ĺsd--8sոB~ JWw*qKhp@<9r6" |){+)R!z pX=F"|= vubMxJq |p )e^甹mY͘}Zq-K,ƓdL""'ߘ'JB!^%g㵁m95c~W1NQe-S*e8dL㉒EU)k1/!ȏ8vI%jbg=SqХtr}.Iܮu+\;p## o1ٯBQF"#?F Mt9'<_) w=vBLJ_?#XXVJy# ;IENDB`kylin-nm/res/w/wifi-full.png0000664000175000017500000000105515167646234014720 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxVQ@ L8$Tܸܸ%  b* ``f3;Besf4Ļ'=o /^mۑg<* iL>A.@:0~MGeN Hs%q@u<|֌$=3+TJژu)`phx+ΰ0wb0:lpe%Or]QU AUl \cF`.V8qID9:%Kk 0k[1⿕C'PR6\Th C0*3a̓*"HJ‹ D IDATxb?2`̝h&D"LhbD7Hbz XmA@c{|FN;DgE n`b X!@~P*=T$ K@ X4%݇@*ـqy @T0 PN> @|(FZ u5DPr%da 4M@k8f1G u@SFYhlGn4b@& E(@iB`TN ҼYZ:r|?(C?H '>+5= aXeE UX~ Fa%A N-if82?H P~B15@hLl (&Bt6d?ʄ~t62V*As)FJnl43}&`^P8!`ldp@:b#W~)GhYQ T6.j>@ЦhR*bF+;>BK X uFR) ~hXG!IS4 ^ ȅ 4`ĕ@>G B Z -Ā\.| ,i 4 -@ EhM\1 ?`iAM~"!VaQL7S b? > gnaK|KXGoC{a+mLeD+QGNx &fIENDB`kylin-nm/res/w/wifi6-medium.png0000664000175000017500000000137515167646234015331 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxWjP %mPjP; IBQ[3fL>![&[_ЌK]J!CݡtP ^4xH -u-G,qA=wywnxͷ2.`(U5 \?~-ud3. y\ '4АvOl6gNןc͙U言1?zN1Y[(bܫ 6 -Ωںe$o}쵺=V"LY^+; QWY-Ȑ"y뽓 4 /#"H5渵9(,!Kև$(g3/"آmpe$oمVXTF5j@*P{` 2Stϳxl E9wQpms[,ZƑ{cISv\BG*[:q"J&xdJ_?#Ñ"mYk#"IENDB`kylin-nm/res/w/wifi-high.png0000664000175000017500000000113515167646234014674 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxVNA `ACrZ؂ vvpvvbg|~~Y[6\C! Rhoٌ+w 6Lrvg͛=-vc,MހY#6&-E !yds@:ʒ|$K]K SF{2|JA-R>QF,U,%)xn%MD2TԐ؃)C#,>aѷ+QJ@p$|=o EN 2|?k3YX# DGIWtV$"c( [DR:cS{x 9xBc/1:)&۠c_Ũek#VS*I{髓n܏Qs$H5D&{'|z 1kϵB HtHҝ8W BsWoFCDqF :g:g&kl-˾PQphIENDB`kylin-nm/res/w/wifi6+-high.png0000664000175000017500000000142315167646234015035 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxV=oADRKHc@l $*t0]ttK.Mt(rH! \%"¼Fއχhywg޼sr7Aލ}Ycx,͖o0kat4 R? ,cD.3 8~q M)*=+Tι=gy S" {Ta$3؛^ 8|Id6b;vsYőX 6j Cn pv9[:ȏg'. 9>lML7X/H׀\2M=bE8 D]O=1K'3lRm>/Y}0A2oMMڛ`@py^2dti6[1رI FW3*Iz8347Yyn[λ̩C̛s;l6ց*KD5Ăɐ$;i9OT۞sD̚h^Zj'Kԯǯ3z ZtVp>5# >u%g yYvLхE۵KAU3r(5#yO8bjb8, 귪-oo"pEx.(#Ք\/co, mt幣( w{\=zt8:kcIENDB`kylin-nm/res/w/wifi6-high.png0000664000175000017500000000137515167646234014770 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxWnA!GB)%St@l $*ta:8@::LGIt4HGD@ 4E,.%7m4Lwg;&+=ٷ;͛={ef܌<o:pw̔9p.^4~-,@͘<1A=`X]e! g } 4ݗ6ѩX+AzX8%m[uH8AѥN6Y amF!ktnܐ' R =PUH9cmY[:N'g s`K&@2Sm8= m lPTHKqE*.]gtOpR4 Q lP ŐMxkF;O!μy;3(?xу+&:#`#O zGct= L\9 H,p"Jp._{C}+z6J/p,HF^G86ublI_`orK&jq8 VHby[ʹl`sTcʝR髐ZRa'O@ؽ$c/I'w-K @[} tHͅĒ ٟ_U B2S.t=8V 1pVV $**E >bBut'̭ >a^rAQٲulSS9PUefJ8Llr} &\f3yu\Jq4!/o ǜIZN%8ɴ NA`Pt; 9JOY9;8T;tk;]Ɂ }2 \oсe$\DK۳|eN8 Ix*()^0_βa){ߩrڇJ<F^x`%9IIENDB`kylin-nm/res/w/wifi6-high-pwd.png0000664000175000017500000000145415167646234015556 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxWkqI C !K rBی[nn/heέsԥ,783b|^y.]rZ]}ޯH[ȍg. 6G?+@ K&7@,o-.vEy|A +sq|834% Uy6TV :B2i&YlO)MZ.JAF dʹ|cj #yDЍu2| щq}FgL<@RS]00= 6#w3Aԅec(_S q 6YU}XNDOyuпl?âEe6WbdOcǦ4]Ͱ$@gd&'v.ca_)Wy5w欹~۸ֹcRhrA 2>쭳T; l/0̀c($`k;搌IτLl3.I=Y,`9y{[!)`Z!<lBz`* -5t]ע[rMD$Z@9̓Hz)L5e^eeUJaTI~ [?XL}f1VDv 6QUM&!ZJ'?#P|K=te5Gf2c܉$IENDB`kylin-nm/res/w/wifi-low.png0000664000175000017500000000111515167646234014554 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxV;N@uP\$EFP"ihrJG8 PIIAr")Hx#=G:ݙ7ogvzG#ƝS@|K`5>(MN} 4R[Reqs3 8>8՚rod֮Id33+9H-28*6ub`,IO8|VHb;Jieᖨ(KUBziS g=*vC4H}˽%Pzֈ8+Obn W O*l2S.t,=aj-G10K hsRѝd[^*ԊyѫAk>26b덍i'w^e3<07;^!L Oʵe!&zeS8+!-O99$'A}A%_3p4TEd8>t7 r_4{)@.0%VHH=Ƿ7(_IENDB`kylin-nm/res/w/wifi6-full-pwd.png0000664000175000017500000000137115167646234015577 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxWr@:a5 TYUVaeIXYVV_PEeauXXU&TmgYhҒ̎oW`8QۅO> qI`))X~r~Tw3,k5~{ dYg+88#;Uzb ;3uPyc_B\zo̩s.c2znYC/T" p-Mɰ>@-4cyIxsLW}P/Rk`B[п ?ڣ'd*qz©|3Nr$o)%esu/|٥ e<3 VLat5e{ֻ1xUe4.T•xކ>eNC07vv{!'Q xs;dN[\c'NT.!vځ1}Șhf̃c6s^8;?1sV\FeAyrTP!^x8&E%i;b C#ضk_r-|!i5=_4/m kK*%ϳt*T7a]wbS9e#NNGヂ8PM*ajJX( K` fHRR.IENDB`kylin-nm/res/w/wifi-medium.png0000664000175000017500000000113615167646234015236 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxV=OP-2I0: .Ln'O` :8PHtDX4sSҼ5~ I`ܻIENDB`kylin-nm/res/w/wifi6+-low.png0000664000175000017500000000140715167646234014721 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxV1K#A9`؃ ,Nl#e vڙ2eJmb!*€B=F&l65|dg}xxynyZ£|fxn4j@3>42~y+P*8K$ñ14ܯ2[3G+p"cy† U%  ^ psCE-.r5؎ 5˹,ag]""-7.p6v a H'F_xW@dWm5(гs@ʭ$V*P"Ye@KfJ\噊'l2".*kd hh\QI7skWj<`Q鲍zTT]Uc2q*RwB_C8_`3n,#902p--CjB::^K8_ό1sgjɝLp.Qoaɴ Alκ~+;pvX-g@3)E>c8];=>u?!q`dOrB}Dd]pƫA`/!́Wdl+z4ό& %qjJDnػ3-ǬuHTHK@N"jFK. )S )&\D) A(*(o[1"4^xHy͜E~W} >c`hG0ϵ 0ii&pedρg@ʒ 2_I%@bhF2iP 9 `WE16NꔍxM5/7[}S$dIAEF ];9`LI( 7B^ph֓DCJ.#V1$~ٮN%j3]۔hJ$]1]ÎkهXu'oy3K0{Jx~́#8jl-}R6ga]y8'y,h߱, cdvS^G Tmn1w! KcjĈfǵ<]bv)wdסub>`{_~;`"E8$pXvXQ66Hs9XC<E"|+g6dyn bNM?#~K`ld4UIENDB`kylin-nm/res/w/wifi6-medium-pwd.png0000664000175000017500000000145615167646234016121 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxW1oPQ"UHa T0 U:z#cXQ66П,HaA:$C#  D\]g;&>铓ww}wzպZycpus 8?l|_6,q?'mP]Re  K;)>YgJ5ڟIN;0IjTm^IozN&k 8tV*m5wUpy /YݠUB&"}R M*|v@=L1 yQ׼;"=eXHHGDS/]2S:mj;uT2wqp7 |'H殚&}[@D=6dTFwyZg RW1== k <2olFfrꮩ*c$_ǟ!_5Dpql'2J8ɘ+}v} 42RKC2 njS=o jt̀} 7x@>|٧b3!`x 4Ü`A{w^Gm R\VEߥDȺk(l-}0MX/%I.QF_#~WDZ2TS&l_U|RIx1R)ݦfTu$ ;R/M`?eɝaIENDB`kylin-nm/res/w/wifi6-none.png0000664000175000017500000000134215167646234015002 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxWNA8)qa#] GHI)rʔ|eʔ|%%e$D(H@q Kƅc( zkώt3o޾ xZO?p֍Ͼ/fg4dq]dydœį ZPeI 2($xӓSz*T*\x 0{"ceF*UlWR psT- >JPцQCbg@3L_O-.vc <]jQ= 5$-ԐE6ܞb'3%L3N}`e ".:)ldV)hȴ$F1h*۶GtNUe?FuV3K'\ډɷ8L]Q}R{ 申a!אR?)5@"'H|V#@u>l V!l׬,I.wC҄mv<`WdLWw\;>gτ*殝gڳy@W$*S0\a#s5gΝx\ĄLnp8U|PfRI+h&*}'q '΅D ײT # 0IENDB`kylin-nm/res/w/wifi-medium-pwd.png0000664000175000017500000000122715167646234016027 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<9IDATxVNP]H~nn 1bLM0@ ,\s\^rRz߽{^K&É|Rրjw?v :P܄ Qx )U=Fıۖ`@L̪=*IkVLRH8Hm+RŲH<\5XK`4#ܡw=qb_I>e%SucEVxϳf+ṖQY ak^6ը/I_{@aDa1Qa'=9ݽ{߻K7f.7kԁ0|~W&m*7&@RD&,HxVTY')\@rIȓQx֩T39`'E 6Nxu1O7[}S$dHdv;q"\${FHG|S}jao "?8®HGNcs-2`> &nSMb:@- r d {f‘o0 नL̆c,K  Wѝd>[[<¸(@wmVe60uU6YN[78L]Q}P&.۔saPhHċOC^~V !'H|\;1$B@†.x4gz3zrhHe4'zO%jcb'>lRv5]r.v7!\s?W<@IRK<0{~}lkFW `v]53hH6쉲$`(d$5-l'$Zq` kk@Em#^BO\yxmtq.?bDġ!3-I.?yͮciߤZX;!vϴG6o `E[rϮz("/\ ?:3!NT G~PWwNěxVQ"|kb\ W9|ݭČLk~y^r^F)yF |3 WƁ‚ge\#>{r0T2fϣza\Ci@>k $'H|-w1s"&9rl ;R,7MI\x?uPHH|_QI )2āydCGطkYXY IU/}wEzOZJ%P.6+/$CIdkYi(_Yr(?"$^:W$Jp,iN7(*!ɉh?%`^,ltw*IENDB`kylin-nm/res/w/wifi-none-pwd.png0000664000175000017500000000117215167646234015505 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxV1O@vM`\BbI$F\ upСt tF||MǵK]q؏U7uѥC8&C-dA$L Ų1o0ȨgSPe.MD8>7 3 2iC)u"4'6@ABƙͲ)_*+3)+Xs`Dy)7KR{ʝx0/Q85$J S0L DB/9#33İU{#xP"f8&Rө f<,/jP۷BDs^ӭ2n dmHc$yW@ 8@/:a̅VdN-6u(^X;} xw8N`%M]/[1X5%'aZr)BRmdHlB.8'Y$I49;0qB= e{}ƻv+= }Uu!o$A2fzhLfh9;{E`\7['IENDB`kylin-nm/res/w/wifi6+-meidum-pwd.png0000664000175000017500000000147415167646234016174 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxV=oAC)lKGqHX2R !W.]Li~]ʔtpI$AR`H$%+b)@7[pMVz̛3xݺ[yE{Gxl5u+?ߘ@J&7@ExT6TY'9@p 8SlS{m3':yZdpV&mRņ$ |wTp⒭$m*PjY)>NSzD+t7K-TN! ڀd{bQqYwvW Sf $ +ȟ׆)d5T35Rwqp &Ifꨀ>)ǂN2Y[¸(gw5Cf6QSsuUs=65D]]8ɨ>VR.W}߿|,HċOt1|F({Vᙵ0HXU>QkU;٣O (ԁ[!p4~F ;Zey%Xz 4ؼFC+PD'h0Z߇&8W~W7Kz/1ֻ\k'\G B+./ol&,"WQJ Yp}E-$"P;ǙCWEµ(E QZ'P2`MV7J1;aOjFn mb3fF.KGl wIENDB`kylin-nm/res/w/wifi6+-high-pwd.png0000664000175000017500000000147615167646234015635 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<IDATxVkaI C !Ktl9A:-qskحqsٺcn-8b b ( o~\҈K?x/w 76{` mD~q׵2PJ+&7@Lpؾ&<"Ksq|9ͪV dV b;u4s cMy$M<%2|ĸdo9p9Ʀa`{@mG$3f/aQPZSx:ux>"Tl\# 3Ir6u?刬z2XW1hع)fW4,Iyɉu5y&A_C8o5gKfBWrA0VfaC"ȐAKH`3PH58>Zּw`A1i0Xg^1Jw2El2~dYN1,GfCU܄F=@}^]=Et]ע[L{qy Hx?FTP9Dvk@)8ͻJc(lJ#1([iw1YQFj)]pVwwLl"'){x6RNBDL='v/ lIENDB`kylin-nm/res/w/wifi6-full.png0000664000175000017500000000130715167646234015006 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<iIDATxWVPm8(_p rsgxL3I̝;wA^W[`O>u{%|j`l,raa,Kv i)'F`tѬ¶VhL@' B%&U҆ Z97|epcZdž*x9Y(́[8!:5@Ѝh rϨk^@3QNȨ#y&ͤ8"S1vy$a&ɜPxm7>1T"*m({ԙe}b Af턣7:'eԣ.Sպ Ϛ w̚_f:>~I44&ް3g*w@*avJ xH%w . . EHd*V^%%LٮqUNU*: .\t\;`9yNJW_y7pD}+mCu)V]8y^.u9,ŦUq jI'txg1U5 ʲT/ k#:B_؋IENDB`kylin-nm/res/w/wifi-low-pwd.png0000664000175000017500000000121315167646234015343 0ustar fengfengPNG  IHDR szztEXtSoftwareAdobe ImageReadyqe<-IDATxVNP# ԁ:0؅01: |##.ƄAt@. ^sG5,䤴s;َPY W]J=KB&08&B@-"FRp@r'e(΅ g02)B)u"/4o$$5Ա#)_ *+Ӎ+\Xs`gyܜ /I5(Ń|C2 ViP4 P+%'z`fC5x4Ԩ/d$= Gڄ$CJc:)ĖXmjK̰>TҌ'2x>rf%Їs ׷:ả: 2[hUzv҉kHū؊x灾Xުܮŗ-,\0Z,t9JK2Cq6!~֓$!#=$ڳ.^.ﹻs 5/\X *4[B]tTN4af(8[E5K(- IENDB`kylin-nm/res/s/0000775000175000017500000000000015167646234012307 5ustar fengfengkylin-nm/res/s/rescan/0000775000175000017500000000000015167646234013562 5ustar fengfengkylin-nm/res/s/rescan/3.png0000664000175000017500000003603715167646234014443 0ustar fengfengPNG  IHDRh pHYs  9iTXtXML:com.adobe.xmp xmp.did:eaa61c88-d2e6-7f41-bbed-73d1b7cbab27 xmp.did:2B06AA9A0A8311E9BD01B7EB82C639A0 xmp.iid:a3333cfd-5484-4246-804e-5c88ce396322 xmp.iid:d96babfe-a040-214a-bc06-feb643c37b81 adobe:docid:photoshop:9673d7dd-fc51-11e8-a001-be3e9f4db054 saved xmp.iid:a3333cfd-5484-4246-804e-5c88ce396322 2018-12-29T09:53:18+08:00 Adobe Photoshop CC 2017 (Windows) / Adobe Photoshop CC 2017 (Windows) 2018-12-10T16:03:48+08:00 2018-12-29T09:53:18+08:00 2018-12-29T09:53:18+08:00 image/png 3 1 720000/10000 720000/10000 2 65535 16 16 f cHRMz%u0`:o_FIDATxb?"#`1200, f``Hg`` 000|d`` P0- \Ρ 0ׄ@u hJ<&n8qaƎ /KVgFLH=:(P\б awE&f\f vrV!bhhk?7,3%0L2?0*eι XţYs<*gu:jp/4h=Lq/PE0m6A"l5 O hX&e.( ̙36tPEF0WC=/s|`T1o]n$yA0wlu'K"+EVq98\Ųx3"P6d%<$x;v IENDB`kylin-nm/res/s/rescan/12.png0000664000175000017500000003572415167646234014525 0ustar fengfengPNG  IHDRh pHYs  9iTXtXML:com.adobe.xmp xmp.did:eaa61c88-d2e6-7f41-bbed-73d1b7cbab27 xmp.did:4B40959B0A8311E99E4DE2469BAC3BCF xmp.iid:f211972f-f026-104f-9f04-42d7b1b1a617 xmp.iid:d96babfe-a040-214a-bc06-feb643c37b81 adobe:docid:photoshop:9673d7dd-fc51-11e8-a001-be3e9f4db054 saved xmp.iid:f211972f-f026-104f-9f04-42d7b1b1a617 2018-12-29T09:51:30+08:00 Adobe Photoshop CC 2017 (Windows) / Adobe Photoshop CC 2017 (Windows) 2018-12-10T16:04:44+08:00 2018-12-29T09:51:30+08:00 2018-12-29T09:51:30+08:00 image/png 3 1 720000/10000 720000/10000 2 65535 16 16 e cHRMz%u0`:o_FIDATxb? `193 AֻQ lGR1J3\α !$2 !=]ʎ{$,h7+>T=l @X@CZB[cJ+H IDz7 &U<C W8ݹGl8ýNbOtW{ט眎Q( +Z"6<`% x O#7S<vJpae1?ehUSCܰ `ajɰE-9J &Ec_/x]=N8@,~wC׸8Jz(} IENDB`kylin-nm/res/s/rescan/7.png0000664000175000017500000003564715167646234014455 0ustar fengfengPNG  IHDRh pHYs  9iTXtXML:com.adobe.xmp xmp.did:eaa61c88-d2e6-7f41-bbed-73d1b7cbab27 xmp.did:3A055C320A8311E9A5B6FBCD249A229B xmp.iid:b7833fd5-5af2-8e48-85ea-930ecc35c4eb xmp.iid:d96babfe-a040-214a-bc06-feb643c37b81 adobe:docid:photoshop:9673d7dd-fc51-11e8-a001-be3e9f4db054 saved xmp.iid:b7833fd5-5af2-8e48-85ea-930ecc35c4eb 2018-12-29T09:52:37+08:00 Adobe Photoshop CC 2017 (Windows) / Adobe Photoshop CC 2017 (Windows) 2018-12-10T16:04:10+08:00 2018-12-29T09:52:37+08:00 2018-12-29T09:52:37+08:00 image/png 3 1 720000/10000 720000/10000 2 65535 16 16 Nk cHRMz%u0`:o_FiIDATxb?` `15 _A{a 蠫_?B5{-X\GB t 0 %QDa2A$hƑ^g+P, )V̀2Xwo6]#+1 ` a(S8z <*1ݔ%Oi;%yt?_Xe`o6>d xmp.did:eaa61c88-d2e6-7f41-bbed-73d1b7cbab27 xmp.did:2F8F03970A8311E98631AE1FB8E699EE xmp.iid:eacc68bb-2ba3-e046-a59f-50d8648b0e28 xmp.iid:d96babfe-a040-214a-bc06-feb643c37b81 adobe:docid:photoshop:9673d7dd-fc51-11e8-a001-be3e9f4db054 saved xmp.iid:eacc68bb-2ba3-e046-a59f-50d8648b0e28 2018-12-29T09:53:08+08:00 Adobe Photoshop CC 2017 (Windows) / Adobe Photoshop CC 2017 (Windows) 2018-12-10T16:03:54+08:00 2018-12-29T09:53:08+08:00 2018-12-29T09:53:08+08:00 image/png 3 1 720000/10000 720000/10000 2 65535 16 16 J cHRMz%u0`:o_FIDATxb?#b:M KAAL1C6f 100p000b%C;T000@`Z200200dϱ 7j6U%XQ+K~n~I8pFGB>4,(xTϿ Qϑɨ(?)N$waccʨlb4sx}jWwsg,7ZxGdqp"x8P8 0>aov πGL53_xO)WxBe|$=aD[4Q PGv3pR0MIENDB`kylin-nm/res/s/rescan/8.png0000664000175000017500000003571515167646234014452 0ustar fengfengPNG  IHDRh pHYs  9iTXtXML:com.adobe.xmp xmp.did:eaa61c88-d2e6-7f41-bbed-73d1b7cbab27 xmp.did:3D325C9A0A8311E98914C2F2D3A308B3 xmp.iid:95bb0191-f431-ce46-9ca4-78bb214398a0 xmp.iid:d96babfe-a040-214a-bc06-feb643c37b81 adobe:docid:photoshop:9673d7dd-fc51-11e8-a001-be3e9f4db054 saved xmp.iid:95bb0191-f431-ce46-9ca4-78bb214398a0 2018-12-29T09:52:26+08:00 Adobe Photoshop CC 2017 (Windows) / Adobe Photoshop CC 2017 (Windows) 2018-12-10T16:04:16+08:00 2018-12-29T09:52:26+08:00 2018-12-29T09:52:26+08:00 image/png 3 1 720000/10000 720000/10000 2 65535 16 16 cHRMz%u0`:o_FIDATxb?` `1xQ{AֻY @R!3B?;/@Vn[ ?3VB`dtСPDG4h@Pĉϼ0;/]`=J1F!*̹Sv2{ZԧX%/+!YDۏS:!(0I(%*F@*T DӋ[Hl@OsA̙?Z*$ Ƹ_2VҔ 68J \x5c^ S xmp.did:eaa61c88-d2e6-7f41-bbed-73d1b7cbab27 xmp.did:40FFD2E90A8311E984D788ADC169D7FF xmp.iid:13deafe3-547e-5e42-8f4c-8f2b3d3fd3d7 xmp.iid:d96babfe-a040-214a-bc06-feb643c37b81 adobe:docid:photoshop:9673d7dd-fc51-11e8-a001-be3e9f4db054 saved xmp.iid:13deafe3-547e-5e42-8f4c-8f2b3d3fd3d7 2018-12-29T09:52:17+08:00 Adobe Photoshop CC 2017 (Windows) / Adobe Photoshop CC 2017 (Windows) 2018-12-10T16:04:25+08:00 2018-12-29T09:52:17+08:00 2018-12-29T09:52:17+08:00 image/png 3 1 720000/10000 720000/10000 2 65535 16 16 cHRMz%u0`:o_FIDATxb?#`1100 $200f``<105.b%3HITR9ԏz*ɍ ;J20_*\Ρ 0EaxS.Pmc ' &X0ذ7[2rWNn<lѱ P/ V: Z`a!2k<p8(rԙ0`! (ΈS*;xZܓO:xt`akidEh x,Yh[em`RP>O<}<~1OOWޖ(cJ{E5$^E GL )dpKN2q$Fb3'яu &-6b}7vYG|wIENDB`kylin-nm/res/s/rescan/2.png0000664000175000017500000003603215167646234014435 0ustar fengfengPNG  IHDRh pHYs  9iTXtXML:com.adobe.xmp xmp.did:eaa61c88-d2e6-7f41-bbed-73d1b7cbab27 xmp.did:2787D4220A8311E99F59FE76C5C2B30E xmp.iid:0be02822-72a7-ba42-8d47-a648423add3e xmp.iid:d96babfe-a040-214a-bc06-feb643c37b81 adobe:docid:photoshop:9673d7dd-fc51-11e8-a001-be3e9f4db054 saved xmp.iid:0be02822-72a7-ba42-8d47-a648423add3e 2018-12-29T09:53:27+08:00 Adobe Photoshop CC 2017 (Windows) / Adobe Photoshop CC 2017 (Windows) 2018-12-10T16:00:30+08:00 2018-12-29T09:53:27+08:00 2018-12-29T09:53:27+08:00 image/png 3 1 720000/10000 720000/10000 2 65535 16 16 G>R cHRMz%u0`:o_FIDATxb?$#d1300x200l a``X 000iy ,P` T;0DSE<PX xI<>۝;;Q$}`Ê3 7C;?Ì+Blϡ Aз9Cr ( :  `4ZA6?s\ N8-f BUIQwnXᎶXV7\( c5X{s|9C(: '@  IhTa@x0(,#I ,[ӑ7LoѢ*4|U2bF9stȿGݠ <ްnHI4&=+gPK9B:Fo;{]DuПIENDB`kylin-nm/res/s/rescan/5.png0000664000175000017500000003602515167646234014442 0ustar fengfengPNG  IHDRh pHYs  9iTXtXML:com.adobe.xmp xmp.did:eaa61c88-d2e6-7f41-bbed-73d1b7cbab27 xmp.did:334B640A0A8311E9B7FA8CF95C228968 xmp.iid:01f85d47-7c05-e346-9f5d-e1b8e47a5e3e xmp.iid:d96babfe-a040-214a-bc06-feb643c37b81 adobe:docid:photoshop:9673d7dd-fc51-11e8-a001-be3e9f4db054 saved xmp.iid:01f85d47-7c05-e346-9f5d-e1b8e47a5e3e 2018-12-29T09:52:59+08:00 Adobe Photoshop CC 2017 (Windows) / Adobe Photoshop CC 2017 (Windows) 2018-12-10T16:03:59+08:00 2018-12-29T09:52:59+08:00 2018-12-29T09:52:59+08:00 image/png 3 1 720000/10000 720000/10000 2 65535 16 16 4 cHRMz%u0`:o_FIDATxb?/#d1100V100x100 a``Hic``hba```p ôc``8T͡ 0 f`l 1AavXČ#D\X xQ\! BQ«vE\.@M6݂ M-h˻˝63?@EUts{41V&>PNf', YsJ8)vآ|<:8M?5+c}Q %IENDB`kylin-nm/res/s/rescan/1.png0000664000175000017500000003566115167646234014443 0ustar fengfengPNG  IHDRh pHYs  9iTXtXML:com.adobe.xmp xmp.did:eaa61c88-d2e6-7f41-bbed-73d1b7cbab27 xmp.did:2403A0260A8311E99104E9BF0F8265BA xmp.iid:f30d9ed6-62c1-ab49-a509-e1f5d31aec3e xmp.iid:d96babfe-a040-214a-bc06-feb643c37b81 adobe:docid:photoshop:9673d7dd-fc51-11e8-a001-be3e9f4db054 saved xmp.iid:f30d9ed6-62c1-ab49-a509-e1f5d31aec3e 2018-12-29T09:53:37+08:00 Adobe Photoshop CC 2017 (Windows) / Adobe Photoshop CC 2017 (Windows) 2018-12-10T16:00:25+08:00 2018-12-29T09:53:37+08:00 2018-12-29T09:53:37+08:00 image/png 3 1 720000/10000 720000/10000 2 65535 16 16 3u cHRMz%u0`:o_FsIDATxb? b@9@_A6mc$&k~2€/h _ ÙA @`E2A1 R%RO 9.Ê ;`?Fw9җa C(@)y;GcH}NШC%A$D).2 ^i]Š 8beqNKA/^pQA&!7{Obi\?<AOz0IENDB`kylin-nm/res/s/rescan/11.png0000664000175000017500000003602715167646234014521 0ustar fengfengPNG  IHDRh pHYs  9iTXtXML:com.adobe.xmp xmp.did:eaa61c88-d2e6-7f41-bbed-73d1b7cbab27 xmp.did:47D532CA0A8311E98A19C7A1ED55446A xmp.iid:900bf612-18ac-1142-9674-2b49a131bec2 xmp.iid:d96babfe-a040-214a-bc06-feb643c37b81 adobe:docid:photoshop:9673d7dd-fc51-11e8-a001-be3e9f4db054 saved xmp.iid:900bf612-18ac-1142-9674-2b49a131bec2 2018-12-29T09:51:54+08:00 Adobe Photoshop CC 2017 (Windows) / Adobe Photoshop CC 2017 (Windows) 2018-12-10T16:04:39+08:00 2018-12-29T09:51:54+08:00 2018-12-29T09:51:54+08:00 image/png 3 1 720000/10000 720000/10000 2 65535 16 16  cHRMz%u0`:o_FIDATxb?;#`d1X~3000200,```4˱ 0% t), pа{DSI^*Ia\α wpf!afeC* %.\رֽ(CHh?FPd!Aa pdflA̰%h.H6S7'yy$0G'@[G|JDRW4%"\jV" b}lQlԚS%/gt`aۄ`E&ALa`xb XEt1.XNwfY?`>ްE(Ztb)b8e0:ا>m_(b)FQ a˿~&xG*h83 /mvIENDB`kylin-nm/res/s/rescan/6.png0000664000175000017500000003604115167646234014441 0ustar fengfengPNG  IHDRh pHYs  9iTXtXML:com.adobe.xmp xmp.did:eaa61c88-d2e6-7f41-bbed-73d1b7cbab27 xmp.did:36C792430A8311E9BE9BD3B013D354F4 xmp.iid:f80865c5-d93d-9449-8407-5ded44ab354f xmp.iid:d96babfe-a040-214a-bc06-feb643c37b81 adobe:docid:photoshop:9673d7dd-fc51-11e8-a001-be3e9f4db054 saved xmp.iid:f80865c5-d93d-9449-8407-5ded44ab354f 2018-12-29T09:52:48+08:00 Adobe Photoshop CC 2017 (Windows) / Adobe Photoshop CC 2017 (Windows) 2018-12-10T16:04:05+08:00 2018-12-29T09:52:48+08:00 2018-12-29T09:52:48+08:00 image/png 3 1 720000/10000 720000/10000 2 65535 16 16 Y cHRMz%u0`:o_FIDATxb?F(d1200300H300DwA;W8Mָ74I/tȚ`a0XX0%a f*fq}`2Ł Z ij0 "X>tNr{?>#WXhߘOX ȣ-|e裊:UMx|K ELN';x[#7SbsʸA#l>^HIENDB`kylin-nm/res/s/rescan/10.png0000664000175000017500000003603615167646234014520 0ustar fengfengPNG  IHDRh pHYs  9iTXtXML:com.adobe.xmp xmp.did:eaa61c88-d2e6-7f41-bbed-73d1b7cbab27 xmp.did:445012F60A8311E983D7BF86387D11C7 xmp.iid:cd8966a6-8e66-7347-989e-5d8c83ed07b4 xmp.iid:d96babfe-a040-214a-bc06-feb643c37b81 adobe:docid:photoshop:9673d7dd-fc51-11e8-a001-be3e9f4db054 saved xmp.iid:cd8966a6-8e66-7347-989e-5d8c83ed07b4 2018-12-29T09:52:04+08:00 Adobe Photoshop CC 2017 (Windows) / Adobe Photoshop CC 2017 (Windows) 2018-12-10T16:04:31+08:00 2018-12-29T09:52:04+08:00 2018-12-29T09:52:04+08:00 image/png 3 1 720000/10000 720000/10000 2 65535 16 16 cE_ cHRMz%u0`:o_FIDATxb?#`1100, 100c``(41 04p1= . 'W"b5DǸ\1 0D $ 6S8hؙZKK?^%w=phgKAZcČ Tl- QgE$ DIč,d1'ksfWl "|{"xx9?gid`n6l`QE%~IJ]V`z"!?<Xmys9xdK9&Q1.w^. K}"XW bW`76E r8# e3u:?|G^c;O`F&15AIqޅGìj %LF;l0O<<2rIENDB`kylin-nm/res/s/conning-a/0000775000175000017500000000000015167646234014160 5ustar fengfengkylin-nm/res/s/conning-a/3.png0000664000175000017500000000053515167646234015033 0ustar fengfengPNG  IHDR $IDAT8ӱJA(HEXUL& ( *|0eNl&YQQi=EVy, 'V S;V:~mZNo3`$ %KD{%]JVӰFNΡ9L7;@/8 fwU)ٿ_9y`-;lÛ_:wm`7t Ww,P ->s ^IENDB`kylin-nm/res/s/conning-a/7.png0000664000175000017500000000054715167646234015042 0ustar fengfengPNG  IHDR .IDAT8JP,++( V+lOoaS >( 020%7q $g&LDpe#OUC0✣LHA5`/Pa( 7(]_Dp `׏1L=ngfЭlwJ9K+6,X Xè[/PaN߷R]wR -lxޒ6 "zV~є"*""" CK*;p6?r#IENDB`kylin-nm/res/s/conning-a/4.png0000664000175000017500000000615415167646234015037 0ustar fengfengPNG  IHDR pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3 cHRMz%u0`:o_FIDATxڌ=/DQAP[hUJQ QV4[눂% CNsdrs=3sf:IUn3̑RڑIY' T㧱OXVPJ\HBv0 xv.B~ZT`nku6`= eIENDB`kylin-nm/res/s/conning-a/8.png0000664000175000017500000000620115167646234015034 0ustar fengfengPNG  IHDR pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3 cHRMz%u0`:o_FIDATxڌ=kTQnb/P"`V!(6vFE{ha0DXPcl<=g=w{sfۨKk` t_"uu:kި#(JNWq5`&m$;YRcQuwRՁTgA';tD:z{juk,?;dlR6+GiR6O9<֨ Bѷ_X&Lt﨧vioI6]6p.n"ODOsiu #u_p&~ /SVV OG_dY,<))fO̅pr x8l֫9#\ riUfz)*=!ޟ嚽; eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3 cHRMz%u0`:o_FIDATxڬ=kQgw&"n v`6Vb'ZX*#V ~Tb PlF`=6yY.Ł[;s9gHbd9ɓ$Θ` 1Ln,暀VU2.7?p7/_Zn+v\O($wlPxļT濋-S xeSYY]YwLouy/;w{bn8_\§ t߶'%)qUY|ZRUdf8]X8X>b Po'{oB؟UݲUk≝Rr8m~E(yIENDB`kylin-nm/res/s/conning-a/5.png0000664000175000017500000000054315167646234015034 0ustar fengfengPNG  IHDR *IDAT8JAK L,$`! y{%J!l|k A+;k  -h!/ sy{!? w3fHоו.Ѐ:Z} ĩ l[o 8.'Vc`j}%# x agM97k&_cЃ:`$rI#IHnYXR/֛:  ݵ*UOǡXf+_L$=J4R^Z8]mpfQ<aaWsWSuKv4]C tK<{gwp|R^eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3 cHRMz%u0`:o_FIDATxڬԻjQo&1XB "X j%/tJ, IB,#1$ʸlvwgƘ}:k_[IA>a|ChȻLt+xX-5<sX$^XIC𩩰EԶ|UN]~?Шr pJ}'*ǫ-jHc:ד1{U.m][6>U8QLicIn'H s{fvIENDB`kylin-nm/res/s/conning-s/1x/12.png0000664000175000017500000000055415167646234015466 0ustar fengfengPNG  IHDRa pHYs  ~IDAT8SnA=,qf2/ Uz0(5UU*Qͮ 5I.f&C7ι2~z"#"u~]l"=G%ZE~LLu$-sADie*bG틘9mYߩM];$xD̋94uK!1^Pg~CfU )QSW":f'"I2RLM?bIJוlLE̘gY]1?gytSINIENDB`kylin-nm/res/s/conning-s/1x/7.png0000664000175000017500000000057515167646234015415 0ustar fengfengPNG  IHDRa pHYs  ~/IDAT8N@E__@ZZg_W$(K)ͦr;w^:ѓ+p]#?{'1. M،nl]uvjtr_nMZ5v"u`puq,|zysˤ9hѳ ̐m٫˵g`/\8>U(AlVIENDB`kylin-nm/res/s/conning-s/1x/9.png0000664000175000017500000000054215167646234015411 0ustar fengfengPNG  IHDRa pHYs  ~IDAT8/nAƿʊ7`AHՠ8@ UBz*|sf2 h>&I_ɼ - Gc kiM ~wI| GlcKyz|Ts/r EWr7-:Uk] Jn:9?@YSwJ@RaDL9f6sa1d Ex'3ckri8p˔S`;)<+ߖas0u[g%j.x.GPIENDB`kylin-nm/res/s/conning-s/1x/2.png0000664000175000017500000000057015167646234015403 0ustar fengfengPNG  IHDRa pHYs  ~*IDAT8S-OA}YlUU`P SPrsݤy܅\^yf=XnkPXUYg5 O]pB*WufZ n][[&U9BBG'Ű1F)b!bܓ?1O\Lt,KhN><hN9M&bq}D;܉g瞪dZ$㏈qTS /D 'q*bD+ My)I@\ysz>~7mOIENDB`kylin-nm/res/s/conning-s/1x/5.png0000664000175000017500000000063315167646234015406 0ustar fengfengPNG  IHDRa pHYs  ~MIDAT8NA?S1 ]S( * UBBUaPs@6\ۤ E2mp)lrw6n4{@0hGf]qt2E"x]Zt2RM4zj{Yj&Ieo4]m B髖mvD0 XuE6pF)kX/i]ژ8yA1Ud ;\B R0vWmOȲE+DV-_#5O';o:[q1Y0^m ZO<NPAoe1@[OIENDB`kylin-nm/res/s/conning-s/1x/1.png0000664000175000017500000000054215167646234015401 0ustar fengfengPNG  IHDRa pHYs  ~IDAT8nAIkh2pw€PU*To>\U  aidƙIM E28IyY+00Gށ?-7^Ȯ <.NK+<>U' Vn]ĽO;w-~qkfkN_96:oIV3вg{wdZee E۪aLu}%0q뜯qc>Vc>Y ui1RIENDB`kylin-nm/res/s/conning-s/1x/11.png0000664000175000017500000000053115167646234015460 0ustar fengfengPNG  IHDRa pHYs  ~ IDAT81N@EźnWK@E WJ*U*NOBHH+X"FZg猽!w=5ڦH>]<)7F]쒀ȏXg C9D:""W@^mC- U_*p mtˮm|c`h<`dy()7yqUjk"dUm/˹jnU3MnfY* |4]h8IENDB`kylin-nm/res/s/conning-s/1x/6.png0000664000175000017500000000062615167646234015411 0ustar fengfengPNG  IHDRa pHYs  ~HIDAT8SN@}$ĬMs~)0*ԩ\GqsiZTQm0Kgms&iҝy䍏IQ[sԵ\&bf"ke۟0O<H<\"bUY|9䕂x̱ǕrT^Lԯ&n]lw tmq"f ^ļuUo`VĜ8th '@PforΣ@FDԞx0 .hdIkDa&#AY },D2MvWmģZv4;c]ãnU>IENDB`kylin-nm/res/s/conning-s/1x/10.png0000664000175000017500000000054315167646234015462 0ustar fengfengPNG  IHDRa pHYs  ~IDAT8=NP? s.Qt4TTTt4TT8@@OG \#heLd'[^μF1glb L ù9p ܸK]m_Ww[PWe>LW%f{9-9Y *svRIENDB`kylin-nm/res/s/conning-s/12.png0000664000175000017500000000115715167646234015136 0ustar fengfengPNG  IHDR szz pHYs%%IR$!IDATXW-oA$BBP5)(?'avAW-R1A/p0[?^X;sR=8(D ~BK/X iDQu:Tf:)ݴ ( )|{S '|hR nioGn>\$kJv,IknLRkG4Re{qe?nri*6?WSe?s*^wI>s._Zr1J,B$i }=煨"R_|KaZMIENDB`kylin-nm/res/s/conning-s/7.png0000664000175000017500000000134015167646234015054 0ustar fengfengPNG  IHDR szz pHYs%%IR$IDATXWr@ȅ̉UըF%1 2oHQPPK!5F%6)h$TI3.)Y˒,ߌlYw{F^D'." ,9]Ѩ["Ga0m$FJ=^Q~k`]0}(zhR46Wz;":ǣ)'aȈߒsK= k^S.y$K澿Ck(̰>\s)]_}[ }F̘Gڡ?t-(Džp;Nىhnޭrii[^#~6,$w^KJq7ruz7iI\'H R>Ig _ٻAńRReݜlqۺM;^||]c܎1Gcծs2%MRޫY5 Q\UbeRGiĨlf %Q IENDB`kylin-nm/res/s/conning-s/8.png0000664000175000017500000000123015167646234015053 0ustar fengfengPNG  IHDR szz pHYs%%IR$JIDATXW-S@}dd2PBP(TU Uiw2`ޖKKMZL\.ٷ{q{'D'gz2%ȗrO^$pjʟ(7l-6Ųwr_ʼ | 6V?,jF.,|ڨ*!EU<1[7>?ȗ`or܏QW~|4C$c29U[}^uAX?efTXJ_?i ϬX1:t_]+0uށKDsKm ʇ7/ l?Pqu]vhrwޞ Pl]:{/XpKQb X ظ X:$2'GT@>E)AAu"`J1䲣EqRk"Zn|+͂}6wW' PvV}½ϸIͷJ'YNum ycqMt-`AҶA1=l-t=մ>6C-v0*|iރ8d iUzN{nq4XdlLMSZî /}Kqt@bBY=ZȪv =O㿠IENDB`kylin-nm/res/s/conning-s/9.png0000664000175000017500000000114515167646234015061 0ustar fengfengPNG  IHDR szz pHYs%%IR$IDATX͗S@GeO=xP(TU / S|dLYmgI?HCÛdoovoFq @? 8y5 b]j,5g鬖q^8ۙΒߊ w,leg4YZl/:\ۭ @5oa@ >*m:40??^3m]y~CNW96$f=•p8sc! 8Z6xMvU0T-TdE24;gpYz 3ncޱt4 PV3eJ=eF# P[cmKg_ \ooICO;Sq-7[Xvk.cֹ+xAY:qݗ%PufC빸|vl=RIENDB`kylin-nm/res/s/conning-s/2.png0000664000175000017500000000130515167646234015050 0ustar fengfengPNG  IHDR szz pHYs%%IR$wIDATXW!oPJE(**ȆJ  E% *iPIglKEEE'Ǫ_l/'YMwww~^>wqg`GᓋJ@}0t%K\8*>*Vs9WɵyVDJ3RJOt7Qc٫"v8 + 0> O(u \+pL!ID`0btO\7 $| +#)V1L(H}>wlY<+5}ELsE&"!}firF$41 fA ,Md$~pcPF2xB7!1] SQsJxD݇=v"fiCe4"FK+?=ـ϶0g*wy 䅭䱂U!jZ6X %wرݾۻWx!z 8eB jΔGw-T]'8 RJ {=c. t&P7d@koEރ(Q8TJH%ɶRzGuXb@@M<`yZkFoܞī4p1GW%6H$ h6w'+egX+8'$Dfe슓EHbʸhqOsEsx>tL(1+{"1 ~E]Y BE>v%!Zq¾׏Vn.y]ܥ̣Z$nsDr~d[ |,hLTJO*#]Tq.yRhXEK3/z,#vE'VRJUJK$AKuIDATXW!SA8InEEEI`2L&:$$ $ vdf!|ofcwݷmU1563~</lfHV9-Y@'G+L5/W8JIT@Yy#nr$oTqij|#@d<12(rCGD$Bb6>ʹ9ki$)w2.ϦAPSz]T+vx˸f`EқxDܨ+|̺,I Q0*x\{.]WZۅJXĈkA%3*i.0 Eu6tD‰  O1[ݻ$aN40C%ԟMw BꋧWU AU5Cޒz) Y\nw罝ݝM|Pp G#30Ϧ!pg+gI8X~Y-DӣX ଟ\35^5x4MÃHs`{>mclGZx !XmDYx\^- ;P'AwiT;,\VN7M.#";YR8/4l+x ``I\1 I&lRI z4v^3iu:".2m:ő rCf-2J11>C Υ>%ԒwB/9=R*|Og6S %͹F{@j9EжIg@krgUKǥUkv5!k7 D5U M-ӺzQ zSf"娫فBf}%\"G=WIENDB`kylin-nm/res/s/conning-s/6.png0000664000175000017500000000124115167646234015053 0ustar fengfengPNG  IHDR szz pHYs%%IR$SIDATXW-P` }ps03BPSSSS)ۨm-|}ۇGr@Ǐ:I0스!Y{l!e7aZd1CH m/k?Y^AafbCb3Aݩj+&ic$k4 ߣ Q,atk8!`Rou7GL<5+723FIENDB`kylin-nm/res/s/conning-s/10.png0000664000175000017500000000116315167646234015131 0ustar fengfengPNG  IHDR szz pHYs%%IR$%IDATXW-S@}t"K&SO=x`P(TU* 0$.f˻MB{$;$a3}>Z GkoT OtqgFxdHCOe)>PI-xq6![Lz#)YAK:I0cM̛_\Oz˕Oefb[-GVHco;+>Ay~vTsG'~_{`C9%gRã5?ݵ.meCE~ ҷh <~}aaHRƎ8jXj@MC%~!>+^SȇtWS&.9Lb/aDQːI5F7 AEC{ N~dVO t8F#ub. Qopo+w1QJNj6#yYH^5˹!ޑz 31~VpIENDB`kylin-nm/res/s/conning-b/0000775000175000017500000000000015167646234014161 5ustar fengfengkylin-nm/res/s/conning-b/3.png0000664000175000017500000001721415167646234015036 0ustar fengfengPNG  IHDR``w8zTXtRaw profile type exifx[& YE$r0 =}.9T5 YL8s?ШdIs9 W,<^bZjyoE H0ukuW끇:^6Ddz$|)mC!Pmmʾ5"0d+ )$q~E "#BZLƐ{1>'%ɏUxzK>-\nZnvώ厈_7LJ=ctޮ]Q+ُ M)XF7\^=؀FTFD* :ܨ!'fSb\f&E8`5>|BoY9@T#HN"8oʨ7MhSEjM `0A8 8$,:ēd PF:لNXKȅ [nߡ\[Įp4 >T+F v?OlǝOiCCPICC profilex}=H@_SKE* ␡:Y*"NZ"TB&~A$Qp-8XupqU?@ܜ]51ݽ;@hTfndBV+#efsw1}ѯ-DYf6Ԧmp'tAG+.q.X3'.VLx8j: YU[J_+\9$ "PF6bXH~?KRU# [0wB 8#@phq';j$ѢG@xhp >)$?MPr-зR7!0Zuwvv?ri3'iTXtXML:com.adobe.xmp ApbKGD pHYs  tIME;[ `IDATxk\esfvg.mR.T!jV[ A1Q?I41$^"Ab%oUJ"qmg\vaNs''3{?s{=0 ( "PUjƮ ue2D@uJDU]!Nǀq 'jF#` k,uPOAz"`V&`Q$GԁEgHE gmApHXOhI@Av~a(sl{ r֩0lY&'IZAK@Y_`c"!`\v ?cJ޺F鄄?&)b׉[Їq:΢Vq&ZP7i..j^Ax 5{AЍ&h ji`D2㬟OLHv}$efz|e/ֿ1f:ɸ q`+VeϧxLJJQ`60+M(Q:.j>:pHxKlO`"N3U)@؉_? ^ |Fjwo^[l9p-?"VҌ3kgoYx"o7,-9TvAyrWuN|^ mπ+gi4.I+g":-I_n(x5)쉅?2vg" jċ)\d a6~4擐Ęrf{)ZhoH' SmQךƃ~@1Asi1_"an 89"+[} cEQS"X e: x졦1r=ddkPP;aA%|дFgF 9\Ig,r3vK%P =)\q|EJV %KʸsfSӸahIUyVP~,a^ XG=w!߸VKwA:(nE+Bzg8/1+6-9$`WB9SUT2\OLj+g|~YB`dWb srL@6Њt (jŊэG sscGءVwM+JVU(琀U=n "p4Gb3Ɂ:(]9`/8p94C,8];{#Pj;5îĮh_?4TF #qTj9"bZ2k.PS(z^2Tb񅘼$.&qjĴj?J.w`WM=/U%&&j[2'dW"_nl~i}/5>!_qJ |W>oxac M.\:*|]5;m Xs̪~a .Vhݏk <#JN6ߨRܡ膏HPiq&l-vJ gm='>t2S[w/Կ?(!IO[;ϽÁq| 7>=iF&AέaqLޝ|lxJ7nphKN4 ppȌ-Y0ޞ,YQ/겘WrkTf A)4eXJ&5-;!'5I ̆ܓc$\ƹ6DB8qGEMl-njC:f]Nz /9(ﺮk!h{ {3(çH6΅ɇy1|mD 镲er@(il&+Za`R̉WeϹE@'DF)JI$QO`^uRH[#S# ?^ $ޯd$'Q%!IƐ{1>'%ɏYx={K>-\nZ.vώ厈_LJ=ct㼾]Q+0)ZF3܊V<؀FTFD* :ب!'FPSb\f&E8X6>|BoY92q(}Ֆ,=xm! ַ@)!@$>@T#HN"8octY9ln2)R+%EXrPUѤYM=hњ%9g&L-[ճ Ԓ/ʡQ #vQP>-5mYVZܥ[^z=)8)tO;,g!# yQFmߴߠF/RSnj ljNf Ɖ@&4Of)%&XBAd:Mb@Nbt"K܂/q"&\o}Zsmvi>T;Ftv?Oa!T_H6iCCPICC profilex}=H@_SKT:A!Cu *U(BP+`r41$).kŪ "%/)=B4g țSb"_B eJR%y?GZgaSy8*J|N.j8N3pwM`FGKm⺣){0dȦJAB7[w뭽 G]enC`Lk>tv?:rm X$'iTXtXML:com.adobe.xmp ZNUbKGD pHYs  tIME25 {IDATxy]e̝;KPZhԺ@Ȣ-h-UX*ĸbp#-`\ .HĸFQZ*@Q) `Sia{=sn;y/Ns=}}>)E _eiF )"4Jx(F5'fv?0 ljY`Z` (h@D&*D T*' OhUd0$O&^dxfB c킀~`X$,$TQ( (HƤ샟&z Nl ]*t[-}'|` 2UaL(xkF~È&bہ1tjR.+䊀"7BEjvڪ@PKY$ pjqbP Ze2&aܕZSp(*Ѥ\l ͦX.^_o_S`ڎOR?,`= `3Xd9|RiY~ ly*A8~XNAš,O,/U4  ۀہ|k$R /ޥc%{5!O=O? xÒfn~K6pQ8  ~Eu?o.o>/*Z~3aĻk5K]xٔ>IFĥj C[V X|H$n /:Wt@J{ }+6\Y*7GBqP,x@}xk#Y!J.Ū\&<7`,`<^K+|%QQaC߱I,4"5~8*㶑.Gr)c9Mwc}7Ey@y(9 / 2$-R# CO~ճ{]PuH Zz^,`x)%ʀo& Ҏ r`Wazɔ  K*֨^k&.vif,ݼ=@B@ձzN ഔ ~^YhW phM^#pX5Gd& Te^oplJ,v;nQ@CXc5J gɮ_iDpX5k ˳7IKj Jmkq+cwz6UrbTa`RI%<$ئ4n-Ӫ;T%}TX*j87k#gbt.Quk%FQq0aɯuVDfvNz/˰1_ˇum y=h}}ƾ;~q yV'b;Xu*͸>=i)"se&LPX Sn߂mޕсM` $`]jg+*iz%{ookAe4Y IydƱVgTSTF rYv6MpZ-i@+"mIO1ײHs7-kvٜn[Nj_r~UNS Ԅߑ?ƪ{cr ;S(#߅?,paa䏳M"(0B&\% #q k,WY٦Tw~{\FzPdS$ޯd$'Q%A$ocH=,g%[.7wHrgrGį &_1q^_WSFF󮨕lz⁔z-nV+hkl@cZB *#PNklb #s)s1.drJ`"],̒ -ek L0Fx-lwZQ;Wg]#In? ġU[8 㵅(X"VC1cPhF<:UDΒR 9akp0veS HcQCUEf5Ek-CX2lfnŪ'Wn^.3PK.VR+ G*+$rC|G9jCԴf[iscn{p8өg>uֆ4taG~~mjHM=A&h':'qP'5ď\W<~\vYq3#.VULx8j: yU[Z_-K\94 "QE 6X~?%r)䪂c ~?ݭU) 8@xh5qZ'@;&0Iz%6pqє=rx2dSv MT @-л27!0R5wG{LNrcORc'iTXtXML:com.adobe.xmp H^bKGD pHYs  tIME%mXIDATxKoUyQJĚuĮ4+ ٰ -bIJ(bȆUKkR>@-Q!hӱYf:g9wKWv{=9Nl( iC0 )a:JsF FDi=mbؔ7ƀ|-`C>{c %M5BVE(r=`]VE &œ#vU"J2{ ` 8.$ uDBC%9؆b3'Z8*i[FeO4g؅ncۯ7L4"-qB&bbp ۮ-ƍN %>t5;dh E3R!`jWrI("ˤG9<0N^P0"6+L;d&;Gsϰ6ø Hs?cʚhe>C򋇡{Q!S\M--%m i0C+`J&E^m'zHM(]I1  Cx8zQI gkhV|rL@0v,nCrigW*QMJyZQd/h139ZS$5ܖ 9J2fh(~|ZT?Aұ_r>;ôA ~vT@&/vJ2֪z5m/:nAcvjh [\ 26d1vpwKUj9yZV?z* 4W9 eL56"(Y aMn0_3KV喙}?۰p+;R[ =Iq@^;uK$c[]үD.^>R簷Mu0 ]oIuudA+"x$*ukd5e!@':9)8v$> ڝ}IVFNs|'+PZali:!U (# Q= @bcYMI돓Ee7yC< /`s (ۛ 56q j5v>-w3 mb'vҧON 8nZgu ;y%2|l3& po'q'-6XsK$9^vVG_<WE@`Bư3UVc.b8o8+aLwĸnSyžӨ5UoKsنKD2,|V`?Ք0Z]f|waAOT.IENDB`kylin-nm/res/s/conning-b/4.png0000664000175000017500000001731715167646234015043 0ustar fengfengPNG  IHDR``w8zTXtRaw profile type exifx[& YE$r0 =}.9T5 YL8s?ШdIs9 W,<^bZjyoE H0ukuW끇:^6Ddz$|)mC!Pmmʾ5"0d+ )$q~E "#BZLIlCB^^1$?V=-\\ri,A& ?;;"~0*$}z22wEd \cp)ֶzAXc[<bPu4\sl@Mq&S` " -ek L0Fx=lwzQ;Wg]#In? xġU[8  Q EbFShF<:UDΒR 9<2veS T~,9jhRլh͒S֜yUK̭Xu݋EpjŊRjPV~Ct;(Gm(ܬy+vqLܭ{/Ng:̧~ڐMDYԦs'#>'5ď\W\~\tX#'V: x8S52.8oqV+5ֺ'a(,s X$PPCXѪb"Eqȥ FTBv[01&@Ŷ?.Ьm7O3p0IzE6pq֔=reCv$?MP蛲@-г7!0RuwwwV?^rT'iTXtXML:com.adobe.xmp ,bKGD pHYs  tIME;0v IDATx{\gsf^D&l5qS-IXD ൂ"J QRҨdƘjd7lv73>sv;;3;l9KȜs\\&m:@GN@YG)qyࢎTh.ED@v (sRٝ@sKN[4`yHuP/TSSD@7'&'E\&d/2E@l_yk:"a=mn&9^7di"  fX7bdל6`hZTj j qi ..KUI+xF~  ĺh#Hz ho řE@7BԑKlQ=Vf9h̚B@L]vKv" Igzux^n7+ozj%V B8 KЏcɿa]y8'QIEm4=WVw$ܡQǰ>,߲+"4|ڀ#{cQ ։Q X s5nO \Q{V#yT/)5pfE!wMf֡gN5 Kp9n^vZ.h6$7N;5{w"0G`/xRqjj4C Q|Fgj$kx%p#pF-. R=C&li&1^Pl H@^^P%4O7>7`œ:&D@'a,_^ٵAzF$?d< Ŀ]tQfxzH8@o[#4/Z"+pt&-OP jt9pa M@o^z(5,`;㜼w̶Dzy/ w8 pw-he~5A'>mqˤN7 S <(,1EzƲD޻4b^#nF-潚ΏIExSe.TYBX_BX9Jei0C>)vcKnU~|U 8ӫn]Xfʘ{oyS܏?^':ԙ4,5>PEu9Ofæ:4֝ܣ;gn(=x <V/)XK".{[:$Tl߇Y%-:!+ck]X6d<I}׏R|φZQWj4hzTnɲwjU-f.RGP!+d[n=Ƶ(-8Pkz7s-zS&dwّކTC|G|*oSl}j:>c!U)|_=\gٮ1{ۏ*;.(:/ eL%x71#t{ e(b#MZs# IbCMzgBxH2֡WQɸc>#`ԡAM%Ymj]u%TYG)qWT$ŤTtIENDB`kylin-nm/res/s/conning-b/8.png0000664000175000017500000001723115167646234015042 0ustar fengfengPNG  IHDR``w8zTXtRaw profile type exifx[& YE$r0 v{\rN%/jS,dI'0s?pQsĕJ*\1x^e%<ý F9^rz჎Wyk2D}9HS q\ܞC=.CRܡ\w:^,u#aBwgnQѓ(HHآ1$c zIc޳ޒ[./Z.vώ厈_LJ=svs_WSFFUQ;0)ZF3܊V<؀FIu4iQCFPKb\V&E8X6Abcl;A -N s"~ qkȭZB;vORAiv|`iP-ٜzB_"VC1cPhF<:UDΒR 9<2v^eK HcQCUEf5Ek-CX2lfnŪ'Wn^.3PK.VR+ G*+$rC|G9jCԴf[iscn{uP8)F:ᣌ:QkSf:zS~~]xZzvS4=L:Nt11Ny1N)"Ri4u/q č\X rj}εM܅+QScccccccoH&x?oOCGhiCCPICC profilex}=H@_SKT:A!Cu ~U(BP+`r4iHR\ׂUg]\AIEJ_Rhq?{ܽFiV鶙N&lnU "B0%3˘{zY9ԼH< & ޴ QVUsQ.Hu7E53y(X`YԈ'cSXYXἾuCHbK BA eT`#NN4']D.\e0r, Zq/)/1 wfqy+6Om-vD붦;!+i ~Fߔo5>N u"ewywϴ;rbFu'iTXtXML:com.adobe.xmp nbbKGD pHYs  tIME 2dD mIDATx{\U?sg:nkE(Q V Q)>i">A%>(&FW$L1 J]S,Vlk-.}M{w&'fڝ;=(O;H´x xSAH^\^%%:=}#"Ol3`< zF؀yj`TКX ]N7C[(QNٜ1e)K"wXn cRh,_ _%uGw#-ڗ\"|UʄfA>Gj lNl> 'u?9qOi䫤pc\;a |ݚU;ǀ d|` ꕾM>%ݽS#5~߰ xla3~H'WEXj|T~VࠇqTπTvh !W1ȿVLxtV_6\+OB xH;ܨ)?* 6*I獇H, 1+sql|BuFc pq[!>}GNݿ&"\"ƌ\7mEWz3W.1t!CA3tG[Lmu:A.g=~Y>ZH)RAdFUyÊ0+ pU5r=Gb4᷺n$ 0"`$/3EߓRg`=NZ08'KqI m $.[qO­޶L5JH|ZqG$/ԓ"N NU10H [V"wp6_ L n<> H?䵸F!k}Xo[EWzԊG2߯[;܎ۇyjۘ;Z!;!W^[]]a#q8՟".Ь%ϑefD WQ[!| ?bSanCz~`} YV@() l f|rd7zm)G"zf]4uN,u$8U- hb~?VqoĸEB+nmѨwSP3m،{9)zL*6j}Ϝj]w5V!/rkW6'U' ہ.D3l;L@.vbZT9%-#=ҫE& ._%z7m" 4"#?ʋ`|7$g>" ?X=? :C7wԣ7PSE }V-$PHpF 'NIENDB`kylin-nm/res/s/conning-b/9.png0000664000175000017500000001727315167646234015051 0ustar fengfengPNG  IHDR``w8zTXtRaw profile type exifx[& YE$r0 v{\rN%/jS,dI'0s?pQsĕJ*\1x^e%<ý F9^rz჎Wyk2D}9HS q\ܞC=.CRܡ\w:^,u#aBwgnQѓ(HHV$c zIc޳ޒ[./Z.vώ厈_LJ=svs_WSFFUQ;0)ZF3܊V<؀FTfD*M{lbԒn8hI.GXh-_#NPe1+?lgœm߹B\a,rмN]STAPwXq8jK6gb<@)!@$>@T#HN"8ocuY9ln2)R+%EXrPJԃYrʚsjbԲ.\={Z@-XRJ*UتЯ|ȑ=a RӖ5o]:uAaiÆ2DMiӦ2MM jtQMjM `0A8 8",:ċb cS(#H]lBE  I7/r-7'ra/w;6sFNecDoǏ!Ć8L4oviCCPICC profilex}=H@_[KT:A!C "Z"TB&~A$Qp-8XupqU?@ܜ]%1ݽ;߬2T22˯ WEJD1 u_<ܟO) ijL7, MKOceI!>'3ď\]~\r3cF63O#J],w1+*q\Q5\V8oqVu־'a,sRXDQGUXHЪb"CI%FԠBr[89&E@Ŷ?.jmN3pu&0Izŏ6pq=rx%CrM7[w K]oC`Dwv?r'iTXtXML:com.adobe.xmp z 7"bKGD pHYs  tIME9`5 IDATxilW3ٮ$4@hY(ЅPQR"D)BE EM -BU KղTCw _ZhC4,]>M/,K؊g=s9aHF: @c Q ,z"u$^">N$9FP9 :Zp7㲒( P;<)Pk;xzWIoΑ]ݠ/9 >"S=pˍ3DZ/n'F[LzgW3O\K%䭸&BQwp pFLucv |x& p uڧ|՘f'/Ҩxd~ &N*I{^ [|Z I)..M~JDI}-M̏f4 zS K9.^P46Z|8<۔Go7+л x=r~ajX!p9Gx\n ?@܌M/7|@n( ]BO'(?ЋNߞYC-M'`?P,d4N qC%dk  8ة}Fؐ@o΁Qz>dhJ <.ܪ!yFح5/?/AϾC,ZP­^\GP p 5K궎-ng?Sq\3,#',GԉVߙ:I>QpcZ|ngFߊ"{hP&"`}#<cbXcɳ"`D z'e!6a`YMy>9tdM%>G{xo#ESB+Sv5cu2`fڌͣZm25n{a ޼K=}yTysCV̧ 'INef. ]ԁ펴$N&ݠ\`XҞx#tnpV$fH OU:TJ`0+fe#ކ۔U5bc7j2ނPZ4\,I;mk!)/S и^le7 "mwM!`;n+ָWl #*3ᗤY^en* W6[∬X/WW+^pZ'ʥvOoczDņ<8 k/a+|<Ш}opEzi%#lƕFXيKYQFMhdǺZe9y\ہ"M$כb3Z,/*QYpBSf ˕)IͪǕݏ27dnlU \,q=ΑPh򻨕Aݚu)hUA (`l\i#Ӹ1~~^v"%Sv{[n!v5qk #]ɏjߧ1jߊ+ۦ;CJNiECv5Q$MŗӳliQ!5rB4eiM(P)БY[ЙU4G$lO1jn,Ͱ9:lYd_^hLSt^kQn]dzj V8}YvlմL~?c!.a~~f>exoM rgcq?g2{;Fz^cN\|йK#{A;A 흵& 0n/֛!)I"2YU&I' [żxcC.[:OKi9E1Jf*tdbm#K4#躠k?vxsPZKb)IENDB`kylin-nm/res/s/conning-b/2.png0000664000175000017500000001724415167646234015040 0ustar fengfengPNG  IHDR``w8zTXtRaw profile type exifx[& YE$r0 v{\rN%/jS,dI'0s?pQsĕJ*\1x^e%<ý F9^rz჎Wyk2D}9HS q\ܞC=.CRܡ\w:^,u#aBwgnQѓ(hU<``yD|c9A/I~{[^ryE+`7nٱW'ysjh*j'fx _h[1 ֨ SIcBL<027Z2MM6)" mek L0Fx-lwZQ;WW]#En7 ~ |*Nki*yE^xwwgoi0rDxe'iTXtXML:com.adobe.xmp ;bKGD pHYs  tIME:^Sߋ wIDATx{\u?sg;hAE)X0D!A$b4F ѨQ D#Q|DMU jꣲӖy7v3{;w z,UJ@ UjL>h!C! [ 1󒤙:YQ'FE29y@ xR" A" N,k OI/IPqXC=Ke9ݬ XN>49혤.н0,/0?Q* 0v ?mD:*Tq%tꔀ[΄!+J|m7ZF9/^:]nt 4 4@2K']Onh.ɺI\y>_ 3ri\j ` {*2Bn#o\^LJ)pHxI˝{)Z`8V-5+Ԥfv!`g f#`{E" /drr mxlԌmڠTm;Pyy;pf.~NYmUEr `_ÞI8,Uь4\Y!Mci"ܦʧ/z$YPoE//$MwŦ,"d6p+?Y͂fgk>~qǀ?Oȋpi*"*)NN?Kg#pL%q aO^E ŰMG3~Ex%f?BiLA)e&>[~ b *!Yx%V\ C#/hD w >c?<.wRR1pXILE3`_ M2Kd?f eĦUN}~A ڶPD@0]LmfG[p UCOJV-"'a.sj#*YpY,<BNXjp!A8(hL@զɚ]ePZhIyXNCvߨMFcV':(7/oW2 V(HcjO2]ɢ`Er+~\'aG]ӚPϡ̝Cd/Y +WGWOdHԭ53G7KE掳I|Nn~[,0;KF)^%c 6!vɬ&m-M|" qX@x)햙(g_?iiM0R\!9!`n7± &$,%lӬNGZz-I/ɠ U3C,h>xBc?j.Wf8Ӗeʆ^ȸ,k2&K*x}<0a3rWT\>%l>{MplB/ɕ M帖kpu7Yr\K{z0K6w: Nˀ_w龬ѴE}ĄlNe*Sjϙ0Nx~j6 WJ qyiJ(u[#3ms9X ygWxejҋq+5]&a\&^pH"ط>D' Gk^#u;dP*|I,2| EmU{4MRIX>Bi Gn5m{-kzW׌܃W8]B1ߌ篈}o}j \yH+,El\ZuXpRmu:>ҳtu`zIL)KpY\R͌Em$q=i{HStydY'B5`nQ岱d "!gMWSA*0 cWU=3?*K$ޯd$'Q%D!!/c|NK{|[.oܴ&] }톟.|{>y}]MͻVR.뵌fs[yy-h 1@:UtQCO6 Ÿp|$FMtql|߲5rxU&#~;-f(+ų$7{hMWmORA]iv|`eP-YzBoH|+A'{2Ec6""r*wI瑱w.+gbMM6E*`K*T5-Z5lyrĒe3s+V]ʨ7MhSEjM `0A8 8$,:ēd cS(#HlBI Inv_~[P%nOD_ @-Pw-b.9pLjߎCCCCCCCC2 BiCCPICC profilex}=H@ߦT:A!Cu *U(BP+`r4iHR\ׂ?Ug]\AIEJ.)ง}Ye3hmfRI1_{_Ba29IJw|#׻?W ",3Lx߻ic,c&Hu7%3yXbYԈ㪦SXYYNHA_Y:a%H U'B>!/K!W Awo䄗IzwVqu+5O-~D뎦;!+i "~Fߔn5o}>YU88FKpw=9RrJ'iTXtXML:com.adobe.xmp ?$bKGD pHYs  tIME `e IDATxi]e;wlvMp ( Jq MըQKD%QJ[4**შqbD@h- uڱ]szsg''L;sνy}d* Eӑr@92::*E:x7QJ`@B"0rPuNYW-iy香:QQ]M #29i@8Qj"4bHF0 Y[P֊Մ pێddY8"PMY`,Ŷ0%g;}Vi$Mu;%_D8؉_脀9cUQT2H%I[N܂46j[ H[;n-Լn.Ef$EmVi+em'uWT+[ˁ%e8E :5w[obs 9^?eG} "SJ3DLW~i l|Q6vFStCG#ex/0o.Ί|lƁK5H10 LB ~''ddǁہݓr)}86+gu{Ɓd: Ċplii^~:}qSM)b7#鶨|ƀWvˁXFPު ]!Q{>=P(7|M)xI mo>#Ƿyu?Xc\& nOH> Q#< Z4mx3=Zl8 KhN˄D4HZsx5ppIYs!*?,qv%w_L5nN/<#`CҮS"ԘlQ"畀W*Lڊ_ߕ%7+Ce{AB _U0rl6^2?'*&(m7+ -xj3wT8KZӫ 29 \tK 9ZVR9KiJDSPHjJU<>܄J5elWe.v;Y2TQv\^9Dz+YE7 |gdC7)RI!Yg=#"`@JG@:)nc79m'I#JZcpLΈ*K򏤘Ee F|Pz<ltaEr <(:aS/Z/\fPZQfU4ϑ2*T"q,p7T,G}5%4]vr`e"i )$`mń*M?(G ?ps- X4yH#•ӳ ?{tdܢi\%C?{SDE~ч,taŵ''7Tblfpȸd\_4_[|C |/.ۉ`۵0|T17$Pq +&Z-Gہ(/xq86\Em% q D2n5_~|=,;\qBt>Ԯ+xR&pͺf-Y5 &ZF@ȎeCoy{iu!!?I5hkjLC'b8 W5-).U65\OUw?KӸ5G_Bf; Tcmf.BI[ rE:=wb܋U0}e+"N5 OG;*vqFE ycW\J_ͦ. 1n,[?c _NzPd3J'zż}[͸vy.ʹcR4FN:f$/H.^I"!9eY]#R 9JE]'r۴F{!$dIENDB`kylin-nm/res/s/conning-b/1.png0000664000175000017500000001611215167646234015030 0ustar fengfengPNG  IHDR``w8zTXtRaw profile type exifx[& YE$r0 v{\rN%/j($0s?ШdIs9 W,xv/CtMABΧe+qj9"0d+ G?#uT̊DG{bao<^ yys^X߫sˋVorc# RyOՔ|UN6=@@e? bmt56 Q!(QJƞ5xafnd.ƅ,NiulReD ;~T`{0g[)wF 4/nT?(Uԝf x&ڒYORߊ`H@ fT?elDȣPE, U#cm]Vμ8B%M X))ǒ&UjA,9e9[^\5dj܊UOܽx-\g\x)V*lUWH>HÏrԆii͚j.Dݺ0pR4taGu֦4uigvQ5&i0{ubbm@AbREn1Q(#H]lBE  I7/r-7'ra/w;6+\9:=ÿ?>>>>>>dMDiCCPICC profilex}=H@_SKE* ␡:Y-QP Vh/hҒ8 ?.κ: "ƃ~{*̾I@-#J|Ea@\ff}N_.Ƴ9ՂHZ'ͮ=uWS`.#i "~Fߔn5>N,ue{trF'iTXtXML:com.adobe.xmp JbKGD pHYs  tIME9xIDATxϏE?3LFn&`9IoBxf^\R bWd!4pTD'tgYOY ?xaK Od]C;cr⸤'NУ 0%1 0#oo6"+D8&8pG o()r[IhT ->ƍ 'cL?% >p, ~\px v\cvDp|s]dD+9m6nXv>gEؒvA3Q^EdZe) nfj޷>hxnR\ܴe徦\ `PK+ +6'4X~z}P35*]y~G|tz[V,,2r[+z^k `lKBueD&b"'Sj#]c >/]H{aj恿JD \Ѷަ{ZU VjB|٦|ҫAq,axRQ-d4I.HS%&hZN U[K૒ p`%iF%J# Kswer0NkeM1öM|@2ɠ%zg~.Fou$Lf.+U bX':!ӝ J0 }b']?XT/rի ӯ *ןE><e6,Y.PTv&FbHثYvvV[D/zLҳ"FR*'ĸM8w\wv0-uq{2MR пrPpS+{E` uko5^ʔZ-ޗ +OJJ*IENDB`kylin-nm/res/s/conning-b/11.png0000664000175000017500000001730715167646234015120 0ustar fengfengPNG  IHDR``w8zTXtRaw profile type exifx[& YE$r0 v{\rN%/jS,dI'0s?pQsĕJ*\1x^e%<ý F9^rz჎Wyk2D}9HS q\ܞC=.CRܡ\w:^,u#aBwgnQѓ(HA y1$1 ٿgoz-wHrgrGį &_99ί)#lz⁔~-nv+hkl@cZB *3PN&=6j1`j\ 7Yj4٤H#@w,s'2iaζRD\!.^u0C @h^t'.~P ;͎8MJ_%@O1[Rߊ`H@ fوGY @$'G71ںyq6b7~,9jhRլh͒S֜uUK̭Xu݋EpjŊRjPV~Ct;(Gm(ܬy+vqLܭ{/ 'HCG6|Q'jmLSg6}YojooPoRKnj Zlj.f Ɖ@4/f)%^XBAb:-b@N}%nA? A.ݷܾC߹p4 vt*{#;~ } } } } } } '6 Nb1iCCPICC profilex}=H@_[kT:ACdATQP Vh/hbHR\ׂUg]\AIEJ_Rhq?{ܽS͞1@,#N ŠzEQыL}V3_.ɳ9@ =bKGD pHYs  tIME7* IDATxylW?;^ql'4i !jiK"R@H@ʥRR*D*RZqU(BZ0PIl'N^`-kޛ{8}{oraR]y+ U\`Xҕ/KЫ(lj ,v 0#>몮5J@Y?ӀS~Zr8I͊p5Pre`V"Ae2Yp\"SzՀ9`킀0$VL܁:NrX8wKvTMQ= ܧ}oerMCz*ppkTV-5 W/hq?3)WR d?\.*O<0SOG@N6 Z_ޯ\GxDa#|!hzw:{ ~,7}#LvyG_ǁ$ VP>I8 ]A'W+@NY)q?%b;/$`|)/|n{EQ3 <xŇTD%ݩ ]15e _HG^G{(@̀p"^^M-6n>^; /"d^R P&aKİ0r2hDPӖ V֝nV]w  Kj'\`g;⏸ oH o]#ȅBWU!V ؅i "K\i36lXp}u:\JJkgI&2Wp=猀<3CJM2߀~8f\MK^^bdF%u>iVS qӷz?>L؂QgA5|#ܡl.L{2(O|HE~AL(>g,+1;SΕA,TYOh/ϐk -~gMfH&݊ OìFd\dJh6*nVjlڗ e\Iө< "(f!9=A#l6JzZB6+6l7آj%\O]l2LAShk˶*ކgx,".BLIkۦ4Mv\Nǰkiojv%aRNzT/MoyU]ި'+:@QyœԿʍʇyF}mvd81/i!t^% Z֍]`Oma% XvS"(x?ʋa|2Ps^u38%{?N-)CIƍES$xQ̜zu+ki"!\Ӽ^+GM uU#'ZT.&ѿOI(IENDB`kylin-nm/res/s/conning-b/6.png0000664000175000017500000001725215167646234015043 0ustar fengfengPNG  IHDR``w8zTXtRaw profile type exifx[& YE$r0 v{\rN%/jS,dI'0s?pQsĕJ*\1x^e%<ý F9^rz჎Wyk2D}9HS q\ܞC=.CRܡ\w:^,u#aBwgnQѓ(HPa ys^߳sˋV orc#RyOՔ|UN6=@@e bn456 Q!(QJ5xadnd.ƅ8h4٤H#@w,s'2iaζRD\!.^u0C @h^t'.~P ;͎8MJ_%@O1[Rߊ`H@ fوGY @$'G71ںyq6b7~,9jhRլh͒S֜uUK̭Xu݋EpjŊRjPV~Ct;(Gm(ܬy+vqLܭ{/ 'HCG6|Q'jmLSg6}YojooPoRKnj Zlj.f Ɖ@4/f)%^XBAb:-b@N}%nA? A.ݷܾC߹p4 vt*{#;~ } } } } } } '6 `DbFiCCPICC profilex}=HPOSKT:ءCdATQP VhФ%Iqq\ ,V\uup77'E)" q=Vif8閑I%\~U "B!&3>'Iix=Q%xwߟ5LDYV7, My8ʲJ|N `vbKGD pHYs  tIME)OdG" |IDATx{e3{ݶE\mjmc"j6`!PFhh41ĀFDER $4p1JQjk+ݕn]v=?gifO2ӝy7ARS@.cG;J,0 <" :rx'Q)f^ =IL:OgP&tE楓fj\2d!Ld3E% ࠅ 2pӎD@pBm}+auϙ&].yi~ 0ڎ_h^9Uq*ykf}JN64cj[[~ݑ"C[HF]& >'L)fQ'cAm)p?{62Th{gQa*|&wbobGI6z$d\/[/ep.4\pxg$L*Qk<Ɠ/ޢ֋DZvq\:Fj5[ri~U[cvSZ\=]ɑe<> FcS4HpVf/MRsV `;#LNnV{wIUE@ $1H[wBmqR(HGm xm'pK RJ= qLɘB˭uz=?6B:z e_iZ Le29gH/hB?\ KK SM@Ai5^|F#N ^S){'4&2^!'S1>&ǿW$5nQ$ w%Ο|ZR~d=HV% qUAeہ/5!E%|k">h 9fHxrMr҉b۟lTa0~ܠ$n3pBq[Ө;WW.ޥ2~:/L+3?TԳ p*;sP{2ݝRql*urU^ xqW|e2hMkcη!JiyX`Uv^[%Bx7װ#g:Jο$x7MOTw]z'}V̔42J:2a{Xʓ"&,}EmmiO lA#r^*4" 4@r8%Y^aqMF&bEqS}bWvQ1!br^xUX F|يn&jeeR^atο"94nE/UbEl0&f;p3`5fmE*Y0cep!n~5!~nx p^g);@p5eCⲤ+qK_wX ?pS:<:5I\'ΉQ)l{u~[<~/n ܪ_^k*)fUS9 \\¶0fh7 uKbx(~&@t^&t7l^cU16ϕX#&\Sգ)Gݰ-jr:ic2;1J7[31c >zg+or~i\'+غ %)gG܈'vЄgLtW@q ? P( vb< fpU:E@/NĿWt ̲=5#̒"z=}~E2jiOIhrfs2EVbN5K|Rm~j"vbW{*xb70$ޯd$'Q%ahCB^>1$?f=-\\riL@& ?;;"~]0*$}22wEd?24\kp+ZAXc[<bPu4\cl@Mq&S` " -ek L0Fx-lwZQ;Wg]#In? ġU[8 㵅(X"VJO3elDȣPE, U#c-]V<8B lTJIQ?5TU4jVSZf)k<䪉%SfVxrk"8bK)rpTaBBr!G:ȇ~6OKM[nּV;w8&zֽ^O 'N3zN?YjmHCG6|Qoj77ѦƋԳaqq"I͓YtJ',ƦPF:لNXKȅ [nߡ\[Į]8s:=ݿ?>>>>>>d;ȝG >iCCPICC profilex}=H@ߦT:A!Cu *U(BP+`r4iHR\ׂ?Ug]\AIEJ.)ޗYe3hmfRI1_{_Ba2$) u<˿ѯ,DYf6mp'tAG+q.,̘LjR+]ʦF)RP,gMy`[>^oC`D>wߚv~rnYD'iTXtXML:com.adobe.xmp (NX3bKGD pHYs  tIME K! IDATxkUW̝;ށN(,4Hh5T44ն(1]751Fc_Lm||0#vHPmР6"jی- ̝}a0:gd\nYkNP_aluZlT*0y1T)Z'('IFmPJ@@YE @ I_f^.hU%`TN G"!y2YE$\.Հs6 _ uVfX׷cX@?p"T9ͨN,M؅N(.UiT[nDZ{h-@{4.V{_p%-ql,r^a 7^]v(lEPehjiPxT}5Ļ"lxppZ`'. -\7Hv^ݨFp3} S>M r tm1{u +\0)"X Hψ9Ql2H7w{|.)(u30 l%|x7YFI"WO~NqVہхUPHOK҇2Q7: DgV#އ1m6-:X0/O UǍsa >#uG:|S[d$<_Ƽ,wF+|oGe=72Sr^*y >ť-(9ciܯ'q/wǺ~Z<:.7ghr!vizQ .ݜz\3Jؙ`w'Hఛ2[-tIףx& c|Bg u>F6)9  s,c0ahdufժ(9 e1Y(?՘eU (%F|[PS-Z눕 iVTt$EY 5+UΒ2Og?;Ql!vHOz~X2GpaW^ p{d7}qFH{U(n#\nQAkT4MyiQ\RG ]ЋԌ@Jm𙢝k;{NJ%"ib zĂUKOs'DKxQT4|,. Z4~'!M1Wt@6kWH6M}hTu[`vr ܡ-` fJ3E%733p/'kfK LҿFpH3.b=aewޑ< fWn[02}HހЧ _<c}Jp f뒄;p $ȧ5bYZfqiQ3ގ? %V;+5_&K$AsU~#oe/h~A 5λWhxw(|ؑQcjUA'ը)(N>ۍ:$$iyn3sC7V~YdL:"J]M ^f^Ҏz*Ƥ6 }#} EܙEIDJ C46qRMB4)xgeesWu4Q[ U4SQҍZ;.sj9ݯSti6[Enjg9&40_Wo ZYI6=^LeЬj9.E[czmJ7]ۊqz jڢUf‚nK)v)MԣKrvS D4ߖ{U:?XE{[{a~72x/\e"g/Su)C6M(:YoV;k @Dľ0*]?n=QRDF$0rK8-?ڣɤ'N xP'<$)vtIӀF@MU) /6|`>@Q)JT]Q}r3鿺#0/IENDB`kylin-nm/res/x/0000775000175000017500000000000015167646234012314 5ustar fengfengkylin-nm/res/x/load-up.png0000664000175000017500000000030215167646234014356 0ustar fengfengPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<dIDATxb`WB|Ƨ  P6VC:&lȶ`5 @,&| X43@K#63ĂQ`~F0>IENDB`kylin-nm/res/x/fly-mode-off.svg0000664000175000017500000000225715167646234015327 0ustar fengfeng 画板 1 kylin-nm/res/x/setup.png0000664000175000017500000000415015167646234014162 0ustar fengfengPNG  IHDRrP6 zTXtRaw profile type exifxW[( g$`fiَOܓ1E[ /\K YJ-%5WnXܯ=)IGPyߠ.crv4]GvzCu+^qs.Q(P0iinœ:% )]]d݀|{}òiɝv8m *99͹krD6]̠ZAQ܂nXl{\P:Ub2ehҺN.f^Y!;q%=9O MTH:ħ/[:FL0Fxk|9CDN{\ gΟBhǫAA`6Le7}VxN'00J` JB2+p49  psJw,\؛@`5)CMd)bAJ.RJ\ӤYEVm,X15jrMjqhVCKZ"KYt.#|zKn6xmbFmbX*kYum"fy,S:Cy5:X)'kՋ D30ƙ:hv΢Q9g20& r@a^esOĞb.8u`.G>amxc*tLcCpLj./fiU},Sg e +ӣ2\*|NW_xq0rjl^|Ww/j^dNJ} A_PQmur'/ Ѝ^#V.FGZ 0"cCuVUg73t !*O  -U8@6@g_,m+7kMsxnZpŷ"H`W2-8Dz٬VmoZ5|4ȳ7=qRHߺ,_Z 7 g 6=h(w? $3yxz̰TBKM N-`;%j6iCCPICC profilex}=H@_SE* VqP,8jP! :\!4iHR\ׂUg]\AIEJ_Rhq?{ܽziV鶙N&lnE "~ы,cVR_.γ9ռŀH< &^'ڴ QVUsQ.Hu7E539(XlcYԈ'cSXY+WYuCHb BA(FV iO]D.\`Gd ^R$t805>v |R?Iг \\4e ٔ])HS(3w tz5qd pp){=\rr*bKGD pHYs  tIMED$9IDAT8u]hq?Ye[Jhj^ʝxJF;.\jhqCSre)/yŤp0aiS{?s~tPiڥ*5_,:V/oWjZPuL` 'kAR﩯՛j][l $IHǁ@p1OکTY^mW?cTGejj uO=DO-04G7xT;I`pXF+SECVF_CZ@=89Vnȇj:. etqlW]Wƒ@wchˁV!ڠ dO[N2߭a_i>vS2=k^6dԇjjkLxuo|Dt[0߁z`?PF>CYXt-9uzA=>So Rd wRRuOA ۳+W,r92 8~ 6$ s"  |ARt˹xI ыMg [-Q=Q1GIENDB`kylin-nm/res/x/control.svg0000664000175000017500000000203315167646234014513 0ustar fengfeng 画板 1 kylin-nm/res/x/wifi-list-bg.svg0000664000175000017500000000163715167646234015341 0ustar fengfeng 画板 1 kylin-nm/res/x/fly-mode-on.svg0000664000175000017500000000175515167646234015173 0ustar fengfeng 画板 1 kylin-nm/res/x/net-list-bg.svg0000664000175000017500000000154315167646234015165 0ustar fengfeng kylin-nm/res/x/hot-spot-on.svg0000664000175000017500000000175315167646234015232 0ustar fengfeng kylin-nm/res/x/hot-spot-off.svg0000664000175000017500000000225515167646234015366 0ustar fengfeng kylin-nm/res/x/load-down.png0000664000175000017500000000030015167646234014677 0ustar fengfengPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<bIDATxb`hK"BdBX2QQ`#; pNCB.X?@{hl AbP9aTxH" BH &q_1DIENDB`kylin-nm/translate_generation.sh0000775000175000017500000000056615167651420016023 0ustar fengfeng#!/bin/bash export PATH="/usr/lib/qt6/bin:$PATH" ts_list=(`ls translations/*.ts`) source /etc/os-release version=(`echo $ID`) for ts in "${ts_list[@]}" do printf "\nprocess ${ts}\n" if [ "$version" == "fedora" ] || [ "$version" == "opensuse-leap" ] || [ "$version" == "opensuse-tumbleweed" ];then lrelease-qt5 "${ts}" else lrelease "${ts}" fi done kylin-nm/COPYING0000664000175000017500000010451315167646234012313 0ustar fengfeng GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . kylin-nm/nmqrc.qrc0000664000175000017500000001257515167646234013115 0ustar fengfeng res/g/down_arrow.png res/s/rescan/1.png res/s/rescan/2.png res/s/rescan/3.png res/s/rescan/4.png res/s/rescan/5.png res/s/rescan/6.png res/s/rescan/7.png res/s/rescan/8.png res/s/rescan/9.png res/s/rescan/10.png res/s/rescan/11.png res/s/rescan/12.png res/h/hide-pwd.png res/h/right-pwd.png res/h/show-pwd.png res/h/no-pwd-wifi.png res/x/fly-mode-off.svg res/x/fly-mode-on.svg res/x/hot-spot-off.svg res/x/hot-spot-on.svg res/x/net-list-bg.svg res/x/wifi-list-bg.svg res/x/load-down.png res/x/load-up.png res/l/network-offline.png res/l/network-offline.svg res/l/network-online.png res/l/network-online.svg res/w/wifi-full.png res/w/wifi-full-pwd.png res/w/wifi-high.png res/w/wifi-high-pwd.png res/w/wifi-low.png res/w/wifi-low-pwd.png res/w/wifi-medium.png res/w/wifi-medium-pwd.png res/w/wifi-none.png res/w/wifi-none-pwd.png res/s/conning-a/1.png res/s/conning-a/2.png res/s/conning-a/3.png res/s/conning-a/4.png res/s/conning-a/5.png res/s/conning-a/6.png res/s/conning-a/7.png res/s/conning-a/8.png res/g/close_black.png res/g/close_white.png res/s/conning-s/1.png res/s/conning-s/2.png res/s/conning-s/3.png res/s/conning-s/4.png res/s/conning-s/5.png res/s/conning-s/6.png res/s/conning-s/7.png res/s/conning-s/8.png res/s/conning-s/9.png res/s/conning-s/10.png res/s/conning-s/11.png res/s/conning-s/12.png res/x/setup.png res/x/control.svg res/w/wifi6-full-pwd.png res/w/wifi6-full.png res/w/wifi6-high-pwd.png res/w/wifi6-high.png res/w/wifi6-low-pwd.png res/w/wifi6-low.png res/w/wifi6-medium-pwd.png res/w/wifi6-medium.png res/w/wifi6-none.png res/w/wifi6+-none.png res/w/wifi6+-meidum-pwd.png res/w/wifi6+-medium.png res/w/wifi6+-medium-pwd.png res/w/wifi6+-low.png res/w/wifi6+-low-pwd.png res/w/wifi6+-high.png res/w/wifi6+-high-pwd.png res/w/wifi6+-full.png res/w/wifi6+-full-pwd.png res/w/wifi6-none-pwd.png res/hw/wifi-full-pwd.png res/hw/wifi-full.png res/hw/wifi-high-pwd.png res/hw/wifi-high.png res/hw/wifi-low-pwd.png res/hw/wifi-low.png res/hw/wifi-medium-pwd.png res/hw/wifi-medium.png res/hw/wifi-none-pwd.png res/hw/wifi-none.png res/hw/wifi6-full-pwd.png res/hw/wifi6-full.png res/hw/wifi6-high-pwd.png res/hw/wifi6-high.png res/hw/wifi6-low-pwd.png res/hw/wifi6-low.png res/hw/wifi6-medium-pwd.png res/hw/wifi6-medium.png res/hw/wifi6-none-pwd.png res/hw/wifi6-none.png res/hw/wifi6+-full-pwd.png res/hw/wifi6+-full.png res/hw/wifi6+-high-pwd.png res/hw/wifi6+-high.png res/hw/wifi6+-low-pwd.png res/hw/wifi6+-low.png res/hw/wifi6+-medium-pwd.png res/hw/wifi6+-medium.png res/hw/wifi6+-none-pwd.png res/hw/wifi6+-none.png res/s/conning-b/1.png res/s/conning-b/2.png res/s/conning-b/3.png res/s/conning-b/4.png res/s/conning-b/5.png res/s/conning-b/6.png res/s/conning-b/7.png res/s/conning-b/8.png res/s/conning-b/9.png res/s/conning-b/10.png res/s/conning-b/11.png res/s/conning-b/12.png kylin-nm/sys-dbus-register/0000775000175000017500000000000015167651420014640 5ustar fengfengkylin-nm/sys-dbus-register/kynmsystemdbus.cpp0000664000175000017500000002243315167651420020451 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "kynmsystemdbus.h" #include "kylinipv4arping.h" #include "kylinipv6arping.h" #include "authority-base.h" #define LOG_FLAG "[KynmSystemDbus]" #define KYLIN_NM_WIRED_MAIN_SWITCH "wired_main_switch" #define EXTRA_DNS_CONF_FILE "/etc/nm_enhance/" #define NM_ENHANCE_DNS "-nm_enhance_dns.conf" #define STR_ATTEMPTS "attempts" #define STR_TIMEOUT "timeout" #define STR_TYPE "type" KynmSystemDbus::KynmSystemDbus(QObject *parent) : QObject(parent) { qDBusRegisterMetaType>(); QString switchSettingFile = "/etc/kylin-nm/netSwitch.conf"; m_kylinNmSettings = new QSettings(switchSettingFile, QSettings::IniFormat); QStringList groups = m_kylinNmSettings->childGroups(); if (groups.indexOf("conf") == -1) { qDebug() << Q_FUNC_INFO << __LINE__; m_kylinNmSettings->beginGroup("conf"); initConf(); } else { m_kylinNmSettings->beginGroup("conf"); initConf(); } // 检查开关状态,如果为false则断开有线设备 bool wiredMainSwitch = m_kylinNmSettings->value(KYLIN_NM_WIRED_MAIN_SWITCH).toBool(); if (!wiredMainSwitch) { disconnectWiredDevices(); } } KynmSystemDbus::~KynmSystemDbus() { } void KynmSystemDbus::initConf() { if (!m_kylinNmSettings->contains(KYLIN_NM_WIRED_MAIN_SWITCH)) m_kylinNmSettings->setValue(KYLIN_NM_WIRED_MAIN_SWITCH, true); } void KynmSystemDbus::disconnectWiredDevices() { qDebug() << Q_FUNC_INFO << "Starting wired device disconnection using NetworkManagerQt API"; try { // 获取所有设备 NetworkManager::Device::List devices = NetworkManager::networkInterfaces(); qDebug() << Q_FUNC_INFO << "Found" << devices.size() << "network devices"; for (const NetworkManager::Device::Ptr &device : devices) { // 检查是否为有线设备 if (device->type() == NetworkManager::Device::Ethernet) { NetworkManager::WiredDevice::Ptr wiredDevice = device.staticCast(); if (wiredDevice) { QString interfaceName = wiredDevice->interfaceName(); qDebug() << Q_FUNC_INFO << interfaceName << wiredDevice->state(); // 检查设备状态 if (wiredDevice->state() >= NetworkManager::Device::Preparing && wiredDevice->state() <= NetworkManager::Device::Activated) { qDebug() << Q_FUNC_INFO << "Disconnecting wired device:" << interfaceName; NetworkManager::deactivateConnection(wiredDevice->activeConnection()->path()); } wiredDevice->setAutoconnect(false); } } } qDebug() << Q_FUNC_INFO << "Wired device disconnection process completed"; } catch (const std::exception &e) { qWarning() << Q_FUNC_INFO << "Exception occurred:" << e.what(); } catch (...) { qWarning() << Q_FUNC_INFO << "Unknown exception occurred"; } } bool KynmSystemDbus::checkIpv4IsConflict(const QString devName, const QString ipv4Address, QStringList macList) { #if 0 //这里会让Dbus异常退出,先注释 PEEK_LIMIT_RET(false); #endif bool isConflict = false; KyIpv4Arping* ipv4Arping = new KyIpv4Arping(devName, ipv4Address); if (ipv4Arping->ipv4ConflictCheck() >= 0) { isConflict = ipv4Arping->ipv4IsConflict(); if (isConflict && !macList.isEmpty()) { QString macAddress = ipv4Arping->getMacAddress(); for (const auto &mac : macList) { if (macAddress == mac) { qDebug() << LOG_FLAG << "IPv4 conflict mac" << mac; isConflict = false; break; } } } } else { qWarning() << LOG_FLAG << "checkIpv4Conflict internal error"; } delete ipv4Arping; ipv4Arping = nullptr; qDebug() << "checkIpv4IsConflict : devName = " << devName << "ip = " << ipv4Address << "result = " << isConflict; return isConflict; } bool KynmSystemDbus::checkIpv6IsConflict(const QString devName, const QString ipv6Address) { PEEK_LIMIT_RET(false); bool isConflict = false; KyIpv6Arping* ipv6rping = new KyIpv6Arping(devName, ipv6Address); if (ipv6rping->ipv6ConflictCheck() >= 0) { isConflict = ipv6rping->ipv6IsConflict(); } else { qWarning() << LOG_FLAG << "checkIpv6Conflict internal error"; } delete ipv6rping; ipv6rping = nullptr; return isConflict; } void KynmSystemDbus::setWiredMainSwitch(bool enable) { qDebug() << Q_FUNC_INFO << __LINE__ << enable; message().service(); #if 0 //这里会让Dbus异常退出,先注释 PEEK_LIMIT(); #endif if (enable != getWiredMainSwitch()) { m_kylinNmSettings->setValue(KYLIN_NM_WIRED_MAIN_SWITCH, enable); Q_EMIT sysWiredMainSwitchChanged(enable); } } bool KynmSystemDbus::getWiredMainSwitch() { qDebug() << Q_FUNC_INFO << __LINE__ ; #if 0 //这里会让Dbus异常退出,先注释 PEEK_LIMIT_RET(false); #endif return m_kylinNmSettings->value(KYLIN_NM_WIRED_MAIN_SWITCH).toBool(); } void KynmSystemDbus::setWiredDeviceSwitch(QString devName, bool enable) { qDebug() << Q_FUNC_INFO << __LINE__<< devName << enable; #if 0 //这里会让Dbus异常退出,先注释 PEEK_LIMIT(); #endif QString conf_name = devName+"-switch"; if (m_kylinNmSettings->contains(conf_name) && enable != getWiredDeviceSwitch(conf_name)) { m_kylinNmSettings->setValue(conf_name, enable); Q_EMIT sysWiredDevSwitchChanged(conf_name, enable); } } bool KynmSystemDbus::getWiredDeviceSwitch(QString devName) { qDebug() << Q_FUNC_INFO << __LINE__<< devName; #if 0 //这里会让Dbus异常退出,先注释 PEEK_LIMIT_RET(false); #endif QString conf_name = devName+"-switch"; if (m_kylinNmSettings->contains(conf_name)) return m_kylinNmSettings->value(conf_name).toBool(); else return true;//111 } //移植kylin-network-manager-enhance-dameon包内的dbus内容 //将 策略、超时时间、重试次数 写入nm_enhance_dns.conf文件 bool KynmSystemDbus::setOptionsEnhance(const QString& name, const QString& timeout, const QString& attempts, const QString& type) { QString filePath = EXTRA_DNS_CONF_FILE + name + NM_ENHANCE_DNS; QFile file(filePath); if (!file.open(QIODevice::ReadWrite)) { return false; } QSettings settings(filePath, QSettings::IniFormat); settings.setValue("/options/timeout", timeout); settings.setValue("/options/attempts", attempts); settings.setValue("/options/type", type); settings.sync(); file.close(); return true; } //移植kylin-network-manager-enhance-dameon包内的dbus内容 //读取nm_enhance_dns.conf文件的 策略、超时时间、重试次数 QVariantMap KynmSystemDbus::getExtraDnsEnhance(const QString& name) { QString filePath = EXTRA_DNS_CONF_FILE + name + NM_ENHANCE_DNS; QSettings settings(filePath, QSettings::IniFormat); QVariantMap map; map[STR_ATTEMPTS] = settings.value("/options/attempts").toString(); map[STR_TIMEOUT] = settings.value("/options/timeout").toString(); map[STR_TYPE] = settings.value("/options/type").toString(); return map; } /* * 【较为通用的写配置文件接口】: * * filePath:文件路径 * feature:节点名 * key:键 * value:值 */ bool KynmSystemDbus::writeNmConfig(const QString& filePath, const QString& feature, const QString &key, const QString& value) { QFile file(filePath); if (!file.open(QIODevice::ReadWrite)){ return false; } QSettings settings(filePath, QSettings::IniFormat); QString jointKey = "/" + feature + "/" + key; settings.setValue(jointKey, value); settings.sync(); file.close(); return true; } /* * 【较为通用的读配置文件接口】: * * filePath:文件路径 * feature:节点名 */ QMap KynmSystemDbus::getNmConfig(const QString& filePath, const QString& feature) { QSettings settings(filePath, QSettings::IniFormat); QMap configMap; settings.beginGroup(feature); QStringList keys = settings.childKeys(); for (const QString &key : keys) { QString value = settings.value(key).toString(); configMap.insert(key, value); } settings.endGroup(); return configMap; } /* * devName = 网卡名 * checked = 打开或关闭 */ void KynmSystemDbus::setDeviceSwitch(const QString& devName, bool checked) { if (checked && !devName.isEmpty()) { Q_EMIT sysDeviceSwitchChanged(devName); } } kylin-nm/sys-dbus-register/main.cpp0000664000175000017500000000261315167646234016301 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "kynmsystemdbus.h" #include #include #include #include int main(int argc, char *argv[]){ QCoreApplication app(argc, argv); QDBusConnection systemBus = QDBusConnection::systemBus(); if (!systemBus.registerService("com.kylin.network.qt.systemdbus")){ qCritical() << "QDbus register service failed reason:" << systemBus.lastError(); exit(1); } if (!systemBus.registerObject("/", new KynmSystemDbus(), QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals)){ qCritical() << "QDbus register object failed reason:" << systemBus.lastError(); exit(2); } return app.exec(); } kylin-nm/sys-dbus-register/kynmsystemdbus.h0000664000175000017500000000513715167651420020120 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef KYNMSYSTEMDBUS_H #define KYNMSYSTEMDBUS_H #include #include #include #include #include #include #include #include class KynmSystemDbus : public QObject,protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "com.kylin.network.interface") public: explicit KynmSystemDbus(QObject *parent = nullptr); ~KynmSystemDbus(); public Q_SLOTS: Q_SCRIPTABLE bool checkIpv4IsConflict(const QString devName, const QString ipv4Address, QStringList macList); Q_SCRIPTABLE bool checkIpv6IsConflict(const QString devName, const QString ipv6Address); Q_SCRIPTABLE void setWiredMainSwitch(bool enable); Q_SCRIPTABLE bool getWiredMainSwitch(); Q_SCRIPTABLE void setWiredDeviceSwitch(QString devName, bool enable); Q_SCRIPTABLE bool getWiredDeviceSwitch(QString devName); Q_SCRIPTABLE bool setOptionsEnhance(const QString&, const QString&, const QString&, const QString&); Q_SCRIPTABLE QVariantMap getExtraDnsEnhance(const QString&); Q_SCRIPTABLE bool writeNmConfig(const QString& filePath, const QString& feature, const QString &key, const QString& value); Q_SCRIPTABLE QMap getNmConfig(const QString& filePath, const QString& feature); //开关网卡会被调用 Q_SCRIPTABLE void setDeviceSwitch(const QString& devName, bool checked); Q_SIGNALS: Q_SCRIPTABLE void sysWiredMainSwitchChanged(bool enbale); Q_SCRIPTABLE void sysWiredDevSwitchChanged(QString devName, bool enbale); //网卡打开触发的信号,调用槽函数尝试重连 Q_SCRIPTABLE void sysDeviceSwitchChanged(const QString &devName); private: QSettings *m_kylinNmSettings; void initConf(); // 关闭有线开关保存后断开有线设备 void disconnectWiredDevices(); }; #endif // KYNMSYSTEMDBUS_H kylin-nm/sys-dbus-register/conf/0000775000175000017500000000000015167651420015565 5ustar fengfengkylin-nm/sys-dbus-register/conf/kylin-nm-sysdbus.service0000664000175000017500000000051015167651420022373 0ustar fengfeng[Unit] Description=Kylin Network Manager System D-Bus Service After=network.target dbus.service Wants=network.target Requires=dbus.service [Service] Type=dbus BusName=com.kylin.network.qt.systemdbus ExecStart=/usr/bin/kylin-nm-sysdbus Restart=on-failure RestartSec=5 User=root Group=root [Install] WantedBy=multi-user.target kylin-nm/sys-dbus-register/conf/com.kylin.network.qt.systemdbus.conf0000664000175000017500000000164315167646234024666 0ustar fengfeng kylin-nm/sys-dbus-register/conf/com.kylin.network.qt.systemdbus.service0000664000175000017500000000013615167646234025375 0ustar fengfeng[D-BUS Service] Name=com.kylin.network.qt.systemdbus Exec=/usr/bin/kylin-nm-sysdbus User=root kylin-nm/sys-dbus-register/kyarping/0000775000175000017500000000000015167651420016464 5ustar fengfengkylin-nm/sys-dbus-register/kyarping/kylinipv4arping.cpp0000664000175000017500000002752215167646234022341 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinipv4arping.h" #include #include #include #define FINAL_PACKS 2 __attribute__((const)) static inline size_t sll_len(const size_t halen) { struct sockaddr_ll unused; const size_t len = offsetof(struct sockaddr_ll, sll_addr) + halen; if (len < sizeof(unused)) return sizeof(unused); return len; } KyIpv4Arping::KyIpv4Arping(QString ifaceName, QString ipAddress, int retryCount, int timeout, QObject *parent) : QObject(parent) { m_ifaceName = ifaceName; m_ipv4Address = ipAddress; m_retryCount = retryCount; m_timeout = timeout; memset(&m_srcAddress, 0, sizeof(m_srcAddress)); } KyIpv4Arping::~KyIpv4Arping() { } void KyIpv4Arping::monoGetTime (struct timespec *ts) { #ifdef CLOCK_MONOTONIC if (clock_gettime (CLOCK_MONOTONIC, ts)) #endif { static long freq = 0; if (freq == 0) freq = sysconf (_SC_CLK_TCK); struct tms dummy; clock_t t = times (&dummy); ts->tv_sec = t / freq; ts->tv_nsec = (t % freq) * (1000000000 / freq); } } void KyIpv4Arping::saveMacAddress(const uint8_t *ptr, size_t len) { int index; char macAddress[64] = {0}; for (index = 0; index < len; index++) { snprintf(&macAddress[qstrlen(macAddress)], sizeof(macAddress) - qstrlen(macAddress), "%02X", ptr[index]); if (index != len - 1) { snprintf(&macAddress[qstrlen(macAddress)], sizeof(macAddress) - qstrlen(macAddress), "%s", ":"); } } m_conflictMac = QString(macAddress); return ; } void KyIpv4Arping::setConflictFlag(bool isConflict) { m_ipConflict = isConflict; } int KyIpv4Arping::sendIpv4Packet() { int err; unsigned char buf[256]; struct arphdr *ah = (struct arphdr *)buf; unsigned char *p = (unsigned char *)(ah + 1); struct sockaddr_ll *p_me = (struct sockaddr_ll *)&(m_me); struct sockaddr_ll *p_he = (struct sockaddr_ll *)&(m_he); ah->ar_hrd = htons(p_me->sll_hatype); if (ah->ar_hrd == htons(ARPHRD_FDDI)) ah->ar_hrd = htons(ARPHRD_ETHER); ah->ar_pro = htons(ETH_P_IP); ah->ar_hln = p_me->sll_halen; ah->ar_pln = 4; ah->ar_op = htons(ARPOP_REQUEST); memcpy(p, &p_me->sll_addr, ah->ar_hln); p += p_me->sll_halen; qWarning()<<"[KyIpv4Arping]" <<"m_src address:" << inet_ntoa(m_srcAddress); memcpy(p, &m_srcAddress, 4); p += 4; memcpy(p, &p_he->sll_addr, ah->ar_hln); p += ah->ar_hln; memcpy(p, &m_destAddress, 4); p += 4; err = sendto(m_ipv4Socket, buf, p - buf, 0, (struct sockaddr *)p_he, sll_len(ah->ar_hln)); return err; } int KyIpv4Arping::ipv4PacketProcess(unsigned char *buf, ssize_t len, struct sockaddr_ll *from) { struct arphdr *ah = (struct arphdr *)buf; unsigned char *p = (unsigned char *)(ah + 1); struct in_addr src_ip, dst_ip; /* Filter out wild packets */ if (from->sll_pkttype != PACKET_HOST && from->sll_pkttype != PACKET_BROADCAST && from->sll_pkttype != PACKET_MULTICAST) return 0; /* Only these types are recognised */ if (ah->ar_op != htons(ARPOP_REQUEST) && ah->ar_op != htons(ARPOP_REPLY)) return 0; /* ARPHRD check and this darned FDDI hack here :-( */ if (ah->ar_hrd != htons(from->sll_hatype) && (from->sll_hatype != ARPHRD_FDDI || ah->ar_hrd != htons(ARPHRD_ETHER))) return 0; /* Protocol must be IP. */ if (ah->ar_pro != htons(ETH_P_IP)) return 0; if (ah->ar_pln != 4) return 0; if (ah->ar_hln != ((struct sockaddr_ll *)&m_me)->sll_halen) return 0; if (len < (ssize_t) sizeof(*ah) + 2 * (4 + ah->ar_hln)) return 0; memcpy(&src_ip, p + ah->ar_hln, 4); memcpy(&dst_ip, p + ah->ar_hln + 4 + ah->ar_hln, 4); /* * DAD packet was: * src_ip = 0 (or some src) * src_hw = ME * dst_ip = tested address * dst_hw = * * We fail, if receive request/reply with: * src_ip = tested_address * src_hw != ME * if src_ip in request was not zero, check * also that it matches to dst_ip, otherwise * dst_ip/dst_hw do not matter. */ if (src_ip.s_addr != m_destAddress.s_addr) return 0; if (memcmp(p, ((struct sockaddr_ll *)&m_me)->sll_addr, ((struct sockaddr_ll *)&m_me)->sll_halen) == 0) return 0; saveMacAddress(p, ah->ar_hln); setConflictFlag(true); return FINAL_PACKS; } int KyIpv4Arping::ipv4EventLoop() { int rc = -1; int ret; int index; int exit_loop = 0; ssize_t bytes; int tfd; struct pollfd pfds[POLLFD_COUNT]; struct itimerspec timerfd_vals; timerfd_vals.it_interval.tv_sec = m_timeout, timerfd_vals.it_interval.tv_nsec = 0, timerfd_vals.it_value.tv_sec = m_timeout, timerfd_vals.it_value.tv_nsec = 0; uint64_t exp; uint64_t total_expires = 1; unsigned char packet[4096]; struct sockaddr_storage from = { 0 }; socklen_t addr_len = sizeof(from); /* timerfd */ tfd = timerfd_create(CLOCK_MONOTONIC, 0); if (tfd == -1) { qWarning()<<"[KyIpv4Arping]" << "timerfd_create failed, errno" << errno; return -1; } if (timerfd_settime(tfd, 0, &timerfd_vals, NULL)) { close(tfd); qWarning()<<"[KyIpv4Arping]" << "timerfd_settime failed, errno" << errno; return -1; } pfds[POLLFD_TIMER].fd = tfd; pfds[POLLFD_TIMER].events = POLLIN | POLLERR | POLLHUP; /* socket */ pfds[POLLFD_SOCKET].fd = m_ipv4Socket; pfds[POLLFD_SOCKET].events = POLLIN | POLLERR | POLLHUP; sendIpv4Packet(); while (!exit_loop) { ret = poll(pfds, POLLFD_COUNT, -1); if (ret <= 0) { if (errno == EAGAIN) { continue; } if (errno) { qWarning()<<"[KyIpv4Arping]" <<"poll failed, errno" << errno; } exit_loop = 1; continue; } for (index = 0; index < POLLFD_COUNT; index++) { if (pfds[index].revents == 0) { continue; } switch (index) { case POLLFD_TIMER: bytes = read(tfd, &exp, sizeof(uint64_t)); if (bytes != sizeof(uint64_t)) { qWarning() <<"[KyIpv4Arping]" << "could not read timerfd"; continue; } total_expires += exp; if (0 < m_retryCount && (uint64_t)m_retryCount < total_expires) { exit_loop = 1; rc = 0; continue; } sendIpv4Packet(); break; case POLLFD_SOCKET: bytes = recvfrom(m_ipv4Socket, packet, sizeof(packet), 0, (struct sockaddr *)&from, &addr_len); if (bytes < 0) { qWarning()<<"[KyIpv4Arping]" << "recvfrom function failed, errno" << errno; continue; } if (ipv4PacketProcess(packet, bytes, (struct sockaddr_ll *)&from) == FINAL_PACKS) { exit_loop = 1; rc = 0; } break; default: qWarning()<<"[KyIpv4Arping]" <<"the fd index is undefine" << index; break; } } } close(tfd); freeifaddrs(m_ifa0); return rc; } int KyIpv4Arping::checkIfflags(unsigned int ifflags) { if (!(ifflags & IFF_UP)) { qWarning()<<"[KyIpv4Arping]" <<"the iface" << m_ifaceName <<" is down."; return -1; } if (ifflags & (IFF_NOARP | IFF_LOOPBACK)) { qWarning()<<"[KyIpv4Arping]" << "Interface" << m_ifaceName << "is not ARPable."; return -1; } return 0; } int KyIpv4Arping::checkDevice() { int rc; struct ifaddrs *ifa; int n = 0; rc = getifaddrs(&m_ifa0); if (rc < 0) { qWarning()<<"[KyIpv4Arping]" <<"get iface address failed, erron"<< errno; return -errno; } for (ifa = m_ifa0; ifa; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) { continue; } if (ifa->ifa_addr->sa_family != AF_PACKET) { continue; } if (!m_ifaceName.isEmpty() && (NULL != ifa->ifa_name) && strcmp(ifa->ifa_name, m_ifaceName.toUtf8())) { continue; } if (checkIfflags(ifa->ifa_flags) < 0) { continue; } if (!((struct sockaddr_ll *)ifa->ifa_addr)->sll_halen) { continue; } if (!ifa->ifa_broadaddr) { continue; } m_ifa = ifa; if (n++) break; } if (n == 1 && m_ifa) { m_ifindex = if_nametoindex(m_ifa->ifa_name); if (!m_ifindex) { qWarning()<<"[KyIpv4Arping]" <<"if_nametoindex is invalid"; freeifaddrs(m_ifa0); return -1; } m_ifaceName = m_ifa->ifa_name; return 0; } freeifaddrs(m_ifa0); return -1; } void KyIpv4Arping::findBroadcastAddress() { struct sockaddr_ll *he = (struct sockaddr_ll *)&(m_he); if (m_ifa) { struct sockaddr_ll *sll = (struct sockaddr_ll *)m_ifa->ifa_broadaddr; if (sll->sll_halen == he->sll_halen) { memcpy(he->sll_addr, sll->sll_addr, he->sll_halen); return; } } qWarning()<<"[KyIpv4Arping]" <<"using default broadcast address."; memset(he->sll_addr, -1, he->sll_halen); return; } int KyIpv4Arping::ipv4ConflictCheck() { limit_capabilities(); int ret = checkDevice(); if (ret < 0) { qWarning()<<"[KyIpv4Arping]"<<"the device is invalid" << m_ifaceName; return -1; } enable_capability_raw(); m_ipv4Socket = socket(PF_PACKET, SOCK_DGRAM, 0); disable_capability_raw(); if (m_ipv4Socket < 0) { qWarning()<<"[KyIpv4Arping]" << "create ipv4 socket failed, errno" << errno; return -1; } inet_aton(m_ipv4Address.toUtf8(), &m_destAddress); m_destAddressFamily = AF_INET; ((struct sockaddr_ll *)&m_me)->sll_family = AF_PACKET; ((struct sockaddr_ll *)&m_me)->sll_ifindex = m_ifindex; ((struct sockaddr_ll *)&m_me)->sll_protocol = htons(ETH_P_ARP); ret = bind(m_ipv4Socket, (struct sockaddr *)&m_me, sizeof(m_me)); if (ret < 0) { qWarning()<<"[KyIpv4Arping]" <<"ipv4 socket bind failed, errno"<< errno; close(m_ipv4Socket); return -1; } socklen_t alen = sizeof(m_me); ret = getsockname(m_ipv4Socket, (struct sockaddr *)&m_me, &alen); if (ret < 0) { qWarning()<<"[KyIpv4Arping]" <<"ipv4 get socket name failed, errno" << errno; close(m_ipv4Socket); return -1; } if (((struct sockaddr_ll *)&m_me)->sll_halen == 0) { qWarning()<<"[KyIpv4Arping]" <<"the iface"<< m_ifaceName <<" is not suitable for arp"; close(m_ipv4Socket); return -1; } m_he = m_me; findBroadcastAddress(); drop_capabilities(); ret = ipv4EventLoop(); close(m_ipv4Socket); return ret; } kylin-nm/sys-dbus-register/kyarping/kylinipv4arping.h0000664000175000017500000000524715167646234022006 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLIN_IPV4_ARPING #define KYLIN_IPV4_ARPING #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kylinarping.h" #include #include #include enum { POLLFD_TIMER = 0, POLLFD_SOCKET, POLLFD_COUNT }; class KyIpv4Arping : public QObject { Q_OBJECT public: explicit KyIpv4Arping(QString ifaceName, QString ipAddress, int retryCount=3, int timeout=1, QObject *parent = nullptr); ~KyIpv4Arping(); public: bool ipv4IsConflict() { return m_ipConflict; } QString getMacAddress() { return m_conflictMac; } int ipv4ConflictCheck(); private: void monoGetTime(struct timespec *ts); void saveMacAddress(const uint8_t *ptr, size_t len); void findBroadcastAddress(); int checkDevice(); int checkIfflags(unsigned int ifflags); int sendIpv4Packet(); int ipv4EventLoop(); int ipv4PacketProcess(unsigned char *buf, ssize_t len, struct sockaddr_ll *from); void setConflictFlag(bool isConflict); private: struct in_addr m_srcAddress; struct in_addr m_destAddress; int m_destAddressFamily; struct sockaddr_storage m_me; struct sockaddr_storage m_he; int m_ipv4Socket = 0; QString m_ifaceName; int m_ifindex; struct ifaddrs *m_ifa; struct ifaddrs *m_ifa0; QString m_ipv4Address; int m_retryCount; int m_timeout; bool m_ipConflict = false; QString m_conflictMac = nullptr; }; #endif kylin-nm/sys-dbus-register/kyarping/kylinipv6arping.h0000664000175000017500000000662015167646234022004 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINIPV6ARPING_H #define KYLINIPV6ARPING_H //#include #include #include #include /* div() */ #include /* uint8_t */ #include /* UINT_MAX */ #include #include #include /* EMFILE */ #include #include /* close() */ #include /* clock_gettime() */ #include /* poll() */ #include #include #include //#include "gettime.h" #ifdef HAVE_GETOPT_H # include #endif #include /* getaddrinfo() */ #include /* inet_ntop() */ #include /* if_nametoindex() */ #include #include #ifndef IPV6_RECVHOPLIMIT /* Using obsolete RFC 2292 instead of RFC 3542 */ # define IPV6_RECVHOPLIMIT IPV6_HOPLIMIT #endif /* BSD-like systems define ND_RA_FLAG_HA instead of ND_RA_FLAG_HOME_AGENT */ #ifndef ND_RA_FLAG_HOME_AGENT # ifdef ND_RA_FLAG_HA # define ND_RA_FLAG_HOME_AGENT ND_RA_FLAG_HA # endif #endif #ifndef AI_IDN # define AI_IDN 0 #endif #include #include #include typedef struct { struct nd_neighbor_solicit hdr; struct nd_opt_hdr opt; uint8_t hw_addr[6]; } solicit_packet; class KyIpv6Arping: public QObject { Q_OBJECT public: explicit KyIpv6Arping(QString ifaceName, QString ipAddress, int retryCount=3, int timeout=1000, QObject *parent = nullptr); ~KyIpv6Arping(); public: bool ipv6IsConflict() { return m_ipv6Conflict; } void setIpv6ConflictFlag(bool conflict) { m_ipv6Conflict = conflict; } QString getConflictMacAddress() { return m_conflictMacAddress; } int ipv6ConflictCheck(); private: void monoGetTime (struct timespec *ts); void saveMacAddress (const uint8_t *ptr, size_t len); int getLocalMacAddress(const char *ifname, unsigned char *addr); int getIpv6ByName(struct sockaddr_in6 *addr); int buildSolicitationPacket(solicit_packet *ns, struct sockaddr_in6 *tgt, const char *ifname); int parseIpv6Packet(const uint8_t *buf, size_t len, const struct sockaddr_in6 *tgt); int readIpv6Packet(void *buf, size_t len, int flags, struct sockaddr_in6 *addr); int reciveAndProcessIpv6Packet(const struct sockaddr_in6 *tgt, unsigned wait_ms); private: int m_ipv6Socket = 0; QString m_ifaceName; QString m_ipv6Address; int m_retryCount; int m_timeoutMs; bool m_ipv6Conflict = false; QString m_conflictMacAddress = nullptr; }; #endif // KYLINIPV6ARPING_H kylin-nm/sys-dbus-register/kyarping/kylinarping.h0000664000175000017500000000552415167646234021201 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINARPING_H #define KYLINARPING_H #include #include #include static cap_flag_value_t cap_raw = CAP_CLEAR; static const cap_value_t caps[] = { CAP_NET_RAW }; static void limit_capabilities() { cap_t cap_p; cap_p = cap_get_proc(); if (!cap_p) { qWarning()<<"cap_get_proc failed."; } cap_get_flag(cap_p, CAP_NET_RAW, CAP_PERMITTED, &cap_raw); if (cap_raw != CAP_CLEAR) { if (cap_clear(cap_p) < 0) { qWarning()<<"cap clear failed"< #include #include #include "kylinarping.h" KyIpv6Arping::KyIpv6Arping(QString ifaceName, QString ipAddress, int retryCount, int timeout, QObject *parent) : QObject(parent) { m_ifaceName = ifaceName; m_ipv6Address = ipAddress; m_retryCount = retryCount; m_timeoutMs = timeout; m_ipv6Conflict = false; } KyIpv6Arping::~KyIpv6Arping() { } void KyIpv6Arping::monoGetTime (struct timespec *ts) { #ifdef CLOCK_MONOTONIC if (clock_gettime (CLOCK_MONOTONIC, ts)) #endif { static long freq = 0; if (freq == 0) freq = sysconf (_SC_CLK_TCK); struct tms dummy; clock_t t = times (&dummy); ts->tv_sec = t / freq; ts->tv_nsec = (t % freq) * (1000000000 / freq); } } int KyIpv6Arping::getLocalMacAddress(const char *ifname, unsigned char *addr) { # ifdef SIOCGIFHWADDR struct ifreq req; memset (&req, 0, sizeof (req)); if (((unsigned)qstrlen (ifname)) >= (unsigned)IFNAMSIZ) { return -1; /* buffer overflow = local root */ } memcpy(req.ifr_name, ifname, sizeof(ifname)); int fd = socket (AF_INET6, SOCK_DGRAM, 0); if (fd == -1) { return -1; } if (ioctl (fd, SIOCGIFHWADDR, &req)) { qWarning()<<"[KyIpv6Arping]"<<"get local mac address failed, errno" << errno; close (fd); return -1; } close (fd); memcpy (addr, req.ifr_hwaddr.sa_data, 6); return 0; # else /* No SIOCGIFHWADDR, which seems Linux specific. */ struct ifaddrs *ifa = NULL; struct ifaddrs *ifp = NULL; getifaddrs(&ifa); ifp = ifa; /* preserve the address of ifa to free memory later */ while (ifp != NULL) { if (ifp->ifa_addr->sa_family == AF_LINK && strcmp(ifp->ifa_name, ifname) == 0) { const struct sockaddr_dl* sdl = (const struct sockaddr_dl*) ifp->ifa_addr; memcpy(addr, sdl->sdl_data + sdl->sdl_nlen, 6); freeifaddrs(ifa); return 0; } ifp = ifp->ifa_next; } freeifaddrs(ifa); return -1; # endif } int KyIpv6Arping::getIpv6ByName(struct sockaddr_in6 *addr) { struct addrinfo hints, *res; memset (&hints, 0, sizeof (hints)); hints.ai_family = PF_INET6; hints.ai_socktype = SOCK_DGRAM; /* dummy */ hints.ai_flags = 0; int val = getaddrinfo (m_ipv6Address.toUtf8(), NULL, &hints, &res); if (val) { qWarning()<<"[KyIpv6Arping]" << m_ipv6Address <<"get addrinfo failed, errno" << val; return -1; } memcpy (addr, res->ai_addr, sizeof (struct sockaddr_in6)); freeaddrinfo (res); val = if_nametoindex (m_ifaceName.toUtf8()); if (val == 0) { qWarning()<<"[KyIpv6Arping]" <<"if_nametoindex failed, errno" << errno; return -1; } addr->sin6_scope_id = val; return 0; } int KyIpv6Arping::buildSolicitationPacket(solicit_packet *ns, struct sockaddr_in6 *tgt, const char *ifname) { /* builds ICMPv6 Neighbor Solicitation packet */ ns->hdr.nd_ns_type = ND_NEIGHBOR_SOLICIT; ns->hdr.nd_ns_code = 0; ns->hdr.nd_ns_cksum = 0; /* computed by the kernel */ ns->hdr.nd_ns_reserved = 0; memcpy (&ns->hdr.nd_ns_target, &tgt->sin6_addr, 16); /* determines actual multicast destination address */ memcpy (&tgt->sin6_addr.s6_addr, "\xff\x02\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x01\xff", 13); /* gets our own interface's link-layer address (MAC) */ if (getLocalMacAddress (m_ifaceName.toUtf8().constData(), ns->hw_addr)) { return sizeof (ns->hdr); } ns->opt.nd_opt_type = ND_OPT_SOURCE_LINKADDR; ns->opt.nd_opt_len = 1; /* 8 bytes */ return sizeof (*ns); } void KyIpv6Arping::saveMacAddress (const uint8_t *ptr, size_t len) { int index; char macAddress[64] = {0}; for (index = 0; index < len; index++) { snprintf(&macAddress[qstrlen(macAddress)], sizeof(macAddress) - qstrlen(macAddress), "%02X", ptr[index]); if (index != len - 1) { snprintf(&macAddress[qstrlen(macAddress)], sizeof(macAddress) - qstrlen(macAddress), "%s", ":"); } } m_conflictMacAddress = QString(macAddress); return ; } int KyIpv6Arping::parseIpv6Packet(const uint8_t *buf, size_t len, const struct sockaddr_in6 *tgt) { const struct nd_neighbor_advert *na = (const struct nd_neighbor_advert *)buf; const uint8_t *ptr; /* checks if the packet is a Neighbor Advertisement, and * if the target IPv6 address is the right one */ if ((len < sizeof (struct nd_neighbor_advert)) || (na->nd_na_type != ND_NEIGHBOR_ADVERT) || (na->nd_na_code != 0) || memcmp (&na->nd_na_target, &tgt->sin6_addr, 16)) { return -1; } len -= sizeof (struct nd_neighbor_advert); /* looks for Target Link-layer address option */ ptr = buf + sizeof (struct nd_neighbor_advert); int index; char macAddress[64] = {0}; uint8_t hw_addr[6] = {0}; getLocalMacAddress(m_ifaceName.toUtf8().constData(), hw_addr); for (index = 0; index < 6; index++) { snprintf(&macAddress[qstrlen(macAddress)], sizeof(macAddress) - qstrlen(macAddress), "%02X", hw_addr[index]); if (index != 5) { snprintf(&macAddress[qstrlen(macAddress)], sizeof(macAddress) - qstrlen(macAddress), "%s", ":"); } } QString localAddr(macAddress); while (len >= 8) { uint16_t optlen; optlen = ((uint16_t)(ptr[1])) << 3; if (optlen == 0) break; /* invalid length */ if (len < optlen) /* length > remaining bytes */ break; len -= optlen; /* skips unrecognized option */ if (ptr[0] != ND_OPT_TARGET_LINKADDR) { ptr += optlen; continue; } /* Found! displays link-layer address */ ptr += 2; optlen -= 2; saveMacAddress (ptr, optlen); if (!localAddr.isEmpty() && getConflictMacAddress() == localAddr) { break; } setIpv6ConflictFlag(true); return 0; } return -1; } int KyIpv6Arping::readIpv6Packet(void *buf, size_t len, int flags, struct sockaddr_in6 *addr) { char cbuf[CMSG_SPACE (sizeof (int))]; struct iovec iov = { .iov_base = buf, .iov_len = len }; struct msghdr hdr = { .msg_name = addr, .msg_namelen = sizeof (*addr), .msg_iov = &iov, .msg_iovlen = 1, .msg_control = cbuf, .msg_controllen = sizeof (cbuf) }; ssize_t val = recvmsg (m_ipv6Socket, &hdr, flags); if (val == -1) { return val; } /* ensures the hop limit is 255 */ for (struct cmsghdr *cmsg = CMSG_FIRSTHDR (&hdr); cmsg != NULL; cmsg = CMSG_NXTHDR (&hdr, cmsg)) { if ((cmsg->cmsg_level == IPPROTO_IPV6) && (cmsg->cmsg_type == IPV6_HOPLIMIT)) { if (255 != *(int *)CMSG_DATA (cmsg)) { // pretend to be a spurious wake-up errno = EAGAIN; return -1; } } } return val; } int KyIpv6Arping::reciveAndProcessIpv6Packet(const struct sockaddr_in6 *tgt, unsigned wait_ms) { struct timespec end; struct pollfd fds; /* computes deadline time */ monoGetTime (&end); div_t d; d = div (wait_ms, 1000); end.tv_sec = end.tv_sec + d.quot; end.tv_nsec = end.tv_nsec + (d.rem * 1000000); /* receive loop */ for (;;) { /* waits for reply until deadline */ struct timespec now; int val = 0; monoGetTime (&now); if (end.tv_sec >= now.tv_sec) { val = (end.tv_sec - now.tv_sec) * 1000 + (int)((end.tv_nsec - now.tv_nsec) / 1000000); if (val < 0) { val = 0; } } fds.fd = m_ipv6Socket; fds.events = POLLIN; val = poll (&fds, 1, val); if (val < 0) break; if (val == 0) return 0; /* receives an ICMPv6 packet */ // TODO: use interface MTU as buffer size uint8_t buf[1460]; struct sockaddr_in6 addr; val = readIpv6Packet(buf, sizeof (buf), MSG_DONTWAIT, &addr); if (val < 0) { if (errno != EAGAIN) qWarning()<<"[KyIpv6Arping]"<<"Receiving ICMPv6 packet failed"; continue; } /* ensures the response came through the right interface */ if (addr.sin6_scope_id && (addr.sin6_scope_id != tgt->sin6_scope_id)) continue; if (parseIpv6Packet(buf, val, tgt) == 0) { return 1 /* = responses */; } } return -1; /* error */ } int KyIpv6Arping::ipv6ConflictCheck() { struct sockaddr_in6 tgt; struct icmp6_filter filter; int retry = 0; limit_capabilities(); enable_capability_raw(); m_ipv6Socket = socket (PF_INET6, SOCK_RAW, IPPROTO_ICMPV6); disable_capability_raw(); if (m_ipv6Socket < 0) { qDebug()<<"[KyIpv6Arping]" <<"create ipv6 socket failed:"; return -1; } fcntl (m_ipv6Socket, F_SETFD, FD_CLOEXEC); /* set ICMPv6 filter */ ICMP6_FILTER_SETBLOCKALL (&filter); ICMP6_FILTER_SETPASS (ND_NEIGHBOR_ADVERT, &filter); enable_capability_raw(); setsockopt (m_ipv6Socket, IPPROTO_ICMPV6, ICMP6_FILTER, &filter, sizeof (filter)); int soDontRoute = 1; setsockopt (m_ipv6Socket, SOL_SOCKET, SO_DONTROUTE, &soDontRoute, sizeof(soDontRoute)); /* sets Hop-by-hop limit to 255 */ int multicastHopLimit = 255; setsockopt (m_ipv6Socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &multicastHopLimit, sizeof (multicastHopLimit)); int unicastHops = 255; setsockopt (m_ipv6Socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &unicastHops, sizeof (unicastHops)); int recvHopLimit = 1; setsockopt(m_ipv6Socket, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &recvHopLimit, sizeof (recvHopLimit)); disable_capability_raw(); drop_capabilities(); /* resolves target's IPv6 address */ int ret = getIpv6ByName(&tgt); if (ret < 0) { qWarning()<<"[KyIpv6Arping]"<<"get ipv6 by name failed."; close (m_ipv6Socket); return ret; } solicit_packet packet; struct sockaddr_in6 dst; ssize_t plen; memcpy (&dst, &tgt, sizeof (dst)); plen = buildSolicitationPacket(&packet, &dst, m_ifaceName.toUtf8().constData()); if (plen == -1) { qWarning()<<"[KyIpv6Arping]"<<"build solicit packet failed."; close (m_ipv6Socket); return -1; } while (retry < m_retryCount) { /* sends a Solitication */ if (sendto (m_ipv6Socket, &packet, plen, MSG_DONTROUTE, (const struct sockaddr *)&dst, sizeof (dst)) != plen) { qWarning()<<"[KyIpv6Arping]"<<"Sending ICMPv6 packet failed."; close (m_ipv6Socket); return -1; } retry++; /* receives an Advertisement */ ssize_t val = reciveAndProcessIpv6Packet(&tgt, m_timeoutMs); if (val > 0) { close (m_ipv6Socket); return 0; } else if (val == 0) { continue; } else { close (m_ipv6Socket); return -1; } } close(m_ipv6Socket); if (retry == m_retryCount) { return 0; } else { return -2; } } kylin-nm/sys-dbus-register/kyarping/kyarping.pri0000664000175000017500000000032515167646234021033 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/kylinarping.h \ $$PWD/kylinipv4arping.h \ $$PWD/kylinipv6arping.h \ SOURCES += \ $$PWD/kylinipv4arping.cpp \ $$PWD/kylinipv6arping.cpp \ DISTFILES += kylin-nm/sys-dbus-register/authority-base.h0000664000175000017500000000534215167651420017755 0ustar fengfeng#ifndef AUTHORITYBASE_H #define AUTHORITYBASE_H #include #include #include #include static const QStringList programWhiteList={ "/usr/bin/kylin-nm", "/usr/bin/ukui-control-center", "/usr/bin/kylin-nm-plugin", "/usr/bin/ukui-sidebar", "/usr/bin/ukui-screensaver-dialog", "/usr/bin/ukui-greeter" }; #define checkEnviron(ret,pid) \ do { \ QString filePath = QString("/proc/%1/environ").arg(pid); \ QFile file(filePath); \ if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { \ qDebug() << "file.open failed" << filePath; \ ret = false; break; \ } \ QTextStream in(&file); \ QString data = in.readAll(); \ file.close(); \ data.replace('\0', '\n'); \ QStringList environVars = data.split('\n'); \ for (const QString &var : environVars){ \ if (!var.isEmpty()) { \ int pos = var.indexOf('='); \ if (pos != -1) { \ QString key = var.left(pos); \ if (key == "LD_PRELOAD" || key == "LD_LIBRARY_PATH" || key == "LD_AUDIT"){ \ ret = false;break; \ } \ } \ } \ } \ ret = true; \ }while(0); #define isAllowedCaller(a) \ do { \ bool macroRet = false;\ QString execPath=""; \ QString clientService = message().service(); \ QDBusConnectionInterface *intf = connection().interface(); \ unsigned int pid = intf->servicePid(clientService).value(); \ checkEnviron(macroRet, pid); \ if(!macroRet) { \ sendErrorReply(QDBusError::ErrorType::Failed,QString("[%1] dbus method control,env forbidden").arg((pid))); \ a = false; \ break; \ } \ QFileInfo file(QString("/proc/%1/exe").arg(pid)); \ if (file.exists()) { \ execPath = file.canonicalFilePath(); \ bool hadBreakIntisAllowedCaller = false; \ Q_FOREACH (const QString& whitePath,programWhiteList){ \ if (execPath == whitePath){ \ a = true; hadBreakIntisAllowedCaller = true; break;\ } \ } \ if (hadBreakIntisAllowedCaller) break; \ } \ sendErrorReply(QDBusError::ErrorType::Failed,QString("[%1] dbus method control,operation not permitted").arg((execPath))); \ a = false; \ } while(0); #define PEEK_LIMIT() bool checret; \ isAllowedCaller(checret) \ if (!checret) return; #define PEEK_LIMIT_RET(a) bool checret; \ isAllowedCaller(checret) \ if (!checret) {return a;} #endif // AUTHORITYBASE_H kylin-nm/sys-dbus-register/sys-dbus-register.pro0000664000175000017500000000163315167651420020760 0ustar fengfengQT += dbus network TARGET = kylin-nm-sysdbus TEMPLATE = app CONFIG += c++14 qt warn_on link_pkgconfig no_keywords CONFIG -= app_bundle TARGET = kylin-nm-sysdbus TEMPLATE = app PKGCONFIG +=gio-2.0 glib-2.0 gio-unix-2.0 libcap inst1.files += conf/com.kylin.network.qt.systemdbus.service inst1.path = /usr/share/dbus-1/system-services/ inst2.files += conf/com.kylin.network.qt.systemdbus.conf inst2.path = /usr/share/dbus-1/system.d/ inst3.files += conf/kylin-nm-sysdbus.service inst3.path = /usr/lib/systemd/system/ target.source += $$TARGET target.path = /usr/bin INCLUDEPATH += /usr/include/KF6/NetworkManagerQt /usr/include/libnm LIBS += -L/usr/lib/ -lKF6NetworkManagerQt INSTALLS += \ target \ inst1 \ inst2 \ inst3 include(kyarping/kyarping.pri) SOURCES += \ kynmsystemdbus.cpp \ main.cpp HEADERS += \ authority-base.h \ kynmsystemdbus.h kylin-nm/plugins/0000775000175000017500000000000015167646234012735 5ustar fengfengkylin-nm/plugins/proxy/0000775000175000017500000000000015167651420014107 5ustar fengfengkylin-nm/plugins/proxy/aptproxydialog.cpp0000664000175000017500000001016615167646234017674 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #include "aptproxydialog.h" #include #include #include #include #include #include "proxy.h" AptProxyDialog::AptProxyDialog(QWidget *parent ): QDialog(parent) { initUi(); setupComponent(); initConnect(); } AptProxyDialog::~AptProxyDialog() { } void AptProxyDialog::initUi() { setWindowTitle(tr("Set APT Proxy")); this->setFixedSize(480, 200); QVBoxLayout *mAptProxyLyt = new QVBoxLayout(this); mAptProxyLyt->setContentsMargins(24, 24, 24, 24); mAptProxyLyt->setSpacing(16); QFrame *mHostFrame = new QFrame(this); mHostFrame->setFixedSize(432, 36); mHostFrame->setFrameShape(QFrame::NoFrame); QHBoxLayout *mLyt_1= new QHBoxLayout(mHostFrame); mLyt_1->setContentsMargins(0, 0, 0, 0); mLyt_1->setSpacing(8); KLabel *mSetHostLabel = new KLabel(mHostFrame); mSetHostLabel->setFixedSize(92, 36); mSetHostLabel->setText(tr("Server Address")); mHostEdit = new QLineEdit(mHostFrame); mHostEdit->setAttribute(Qt::WA_InputMethodEnabled, false); //限制中文输入法 mHostEdit->setFixedSize(332, 36); mHostEdit->installEventFilter(this); mLyt_1->addWidget(mSetHostLabel); mLyt_1->addWidget(mHostEdit); QFrame *mPortFrame = new QFrame(this); mPortFrame->setFixedSize(432, 36); mPortFrame->setFrameShape(QFrame::NoFrame); QHBoxLayout *mLyt_2= new QHBoxLayout(mPortFrame); mLyt_2->setContentsMargins(0, 0, 0, 0); mLyt_2->setSpacing(8); QLabel *mSetPortLabel = new QLabel(tr("Port") ,mPortFrame); mSetPortLabel->setFixedSize(92, 36); mPortEdit = new QLineEdit(mPortFrame); mPortEdit->setAttribute(Qt::WA_InputMethodEnabled, false); //限制中文输入法 mPortEdit->setFixedSize(332, 36); mPortEdit->installEventFilter(this); mLyt_2->addWidget(mSetPortLabel); mLyt_2->addWidget(mPortEdit); QFrame *mChooseFrame = new QFrame(this); mChooseFrame->setFixedWidth(432); mChooseFrame->setFrameShape(QFrame::NoFrame); QHBoxLayout *mLyt_3= new QHBoxLayout(mChooseFrame); mLyt_3->setContentsMargins(0, 0, 0, 0); mLyt_3->setSpacing(16); mCancelBtn = new QPushButton(mChooseFrame); mCancelBtn->setMinimumWidth(96); mCancelBtn->setText(tr("Cancel")); mConfirmBtn = new QPushButton(mChooseFrame); mConfirmBtn->setMinimumWidth(96); mConfirmBtn->setText(tr("Confirm")); mLyt_3->addStretch(); mLyt_3->addWidget(mCancelBtn); mLyt_3->addWidget(mConfirmBtn); mAptProxyLyt->addWidget(mHostFrame); mAptProxyLyt->addWidget(mPortFrame); mAptProxyLyt->addSpacing(16); mAptProxyLyt->addWidget(mChooseFrame); } void AptProxyDialog::initConnect() { connect(mHostEdit, &QLineEdit::textEdited, this, [=]() { if (mHostEdit->text().isEmpty()) { mConfirmBtn->setEnabled(false); } else { mConfirmBtn->setEnabled(true); } }); connect(mCancelBtn, &QPushButton::clicked, this, [=]() { this->close(); }); connect(mConfirmBtn, &QPushButton::clicked, this, [=]() { Proxy::setAptProxy(mHostEdit->text() , mPortEdit->text() , true); this->close(); }); } void AptProxyDialog::setupComponent() { QString host = Proxy::getAptProxy()["ip"].toString(); QString port = Proxy::getAptProxy()["port"].toString();; mHostEdit->setText(host); mPortEdit->setText(port); if (host.isEmpty()) { mConfirmBtn->setEnabled(false); } } kylin-nm/plugins/proxy/translations/0000775000175000017500000000000015167654227016640 5ustar fengfengkylin-nm/plugins/proxy/translations/de.ts0000664000175000017500000002004515167646234017600 0ustar fengfeng AptProxyDialog Set APT Proxy APT-Proxy setzen Server Address Server-Adresse Port Hafen Cancel Abbrechen Confirm Bestätigen Proxy Proxy Stellvertreter Start using Beginnen Sie mit der Verwendung Proxy mode Proxy-Modus Auto Auto Manual Manuell Application Proxy Anwendungs-Proxy System Proxy System-Proxy Auto url Automatische URL /Proxy/Auto url Http Proxy HTTP-Proxy /Proxy/Http Proxy Https Proxy HTTPS-Proxy /Proxy/Https Proxy Ftp Proxy FTP-Proxy /Proxy/Ftp Proxy Socks Proxy Socken-Proxy /Proxy/Socks Proxy Port Hafen List of ignored hosts. more than one entry, please separate with english semicolon(;) Liste der ignorierten Hosts. Mehr als ein Eintrag, bitte mit englischem Semikolon trennen (;) App Proxy App-Proxy /Proxy/App Proxy APT Proxy APT-Proxy /Proxy/APT Proxy Open Offen Server Address : Server-Adresse : Port : Hafen: Edit Redigieren The APT proxy has been turned off and needs to be restarted to take effect Der APT-Proxy wurde deaktiviert und muss neu gestartet werden, um wirksam zu werden Reboot Later Später neu starten Reboot Now Jetzt neu starten The system needs to be restarted to set the APT proxy, whether to reboot Das System muss neu gestartet werden, um den APT-Proxy zu setzen, ob ein Neustart durchgeführt werden soll Proxy type Proxy-Typ IP address IP-Adresse Required Erforderlich Invalid IP Address Ungültige IP-Adresse Username Nutzername Optional Wahlfrei Password Passwort Cancel Abbrechen Save Retten The following applications are allowed to use this configuration: Die folgenden Anwendungen dürfen diese Konfiguration verwenden: kylin-nm/plugins/proxy/translations/ky.ts0000664000175000017500000002144215167646234017635 0ustar fengfeng AptProxyDialog Set APT Proxy APT ۋاكىلىن قۇرۇۇ ، اچۇۇ ، باشتوو جاسوو ،اتقارۇۇ Server Address مۇلازىمەتىر دايىن وردۇ Port ووزۇ Cancel ارعادان قالتىرىش Confirm بەكىتۉۉ Proxy Proxy ۋاكالەتەن Start using ىشتەتىشتى باشتوو Proxy mode ۋاكالەتەن تۉرۉ Auto اپتوماتىك Manual قولدونمو Application Proxy 应用代理 System Proxy ۋاكالەتەن سەستىما Auto url URLتەڭشەگى /Proxy/Auto url Http Proxy Http ۋاكالەتەن /Proxy/Http Proxy Https Proxy Https ۋاكالەتەن /Proxy/Https Proxy Ftp Proxy Ftp ۋاكالەتەن /Proxy/Ftp Proxy Socks Proxy SOCKS ۋاكالەتەن /Proxy/Socks Proxy Port ووزۇ List of ignored hosts. more than one entry, please separate with english semicolon(;) سەل قارالعان باش اپارات تىزىمدىگى،انگىلىزچە چەكىتتۉۉ ۉتۉر ىشتەتىڭ (;) App Proxy قولدونۇشچان ۋاكالەتەن /Proxy/App Proxy APT Proxy APT ۅكۅلۅتچۉسۉ /Proxy/APT Proxy Open اچۇۇ Server Address : مۇلازىمەتىر دايىن وردۇ : Port : ووزۇ : Edit تۅپتۅش The APT proxy has been turned off and needs to be restarted to take effect APT ۋاكالەتچىلىكى تاقالدى، قايرا قوزعوتۇشقا تۇۇرا كەلسە اندان كۉچۉنۅ ەە بولموق بولوت Reboot Later سەل تۇرۇپ قايرا قوزعوتۇڭ Reboot Now ازىر ەلە قايرا قوزعوتۇڭ The system needs to be restarted to set the APT proxy, whether to reboot APT ۋاكىلىن قۇرۇۇ ، اچۇۇ ، باشتوو جاسوو ،اتقارۇۇ ۉچۉن سەستىمانى قايرا قوزعوتۇۇ كەرەك، قايرا قوزغىتىلامدۇ جوق Proxy type ۋاكالەتەن تۉرۉ IP address IP دايىن وردۇ Required مۉلدۅ تولتۇرۇ Invalid IP Address ەسەپ ەمەس IP دايىن وردۇ Username ابونت ناامى Optional تانداپ تولتۇرۇ Password جاشىرۇۇن اچقىچ Cancel ارعادان قالتىرىش Save ساقتوو The following applications are allowed to use this configuration: تۅمۅندۅكۉ سەپتەمەلەردى ىشتەتىشكە ۇرۇقسات جاسالات : kylin-nm/plugins/proxy/translations/zh_CN.ts0000664000175000017500000001752615167646234020223 0ustar fengfeng AptProxyDialog Set APT Proxy 设置 APT 代理 Server Address 服务器地址 Port 端口 Cancel 取消 Confirm 确定 Proxy Proxy 代理 Start using 启用 Proxy mode 代理类型 Auto 自动 Manual 手动 Application Proxy 应用代理 System Proxy 系统代理 Auto url 配置 URL /Proxy/Auto url Http Proxy HTTP 代理 /Proxy/Http Proxy Https Proxy HTTPS 代理 /Proxy/Https Proxy Ftp Proxy FTP 代理 /Proxy/Ftp Proxy Socks Proxy SOCKS 代理 /Proxy/Socks Proxy Port 端口 List of ignored hosts. more than one entry, please separate with english semicolon(;) 忽略的主机列表,请使用英文分号(;) App Proxy 应用代理 /Proxy/App Proxy APT Proxy APT 代理 /Proxy/APT Proxy Open 开启 Server Address : 服务器地址: Port : 端口: Edit 编辑 The APT proxy has been turned off and needs to be restarted to take effect APT 代理已关闭,需要重启才能生效 Reboot Later 稍后重启 Reboot Now 立即重启 The system needs to be restarted to set the APT proxy, whether to reboot 设置 APT 代理需要重启系统后生效,是否重启系统 Proxy type 代理类型 IP address IP 地址 Required 必填 Invalid IP Address 无效的 IP 地址 Username 用户名 Optional 选填 Password 密码 Cancel 取消 Save 保存 The following applications are allowed to use this configuration: 允许以下应用使用该配置: kylin-nm/plugins/proxy/translations/kk.ts0000664000175000017500000002135515167646234017622 0ustar fengfeng AptProxyDialog Set APT Proxy APT ۋاكىلدىك ەتۋشى ورنالاسترعان ەتۋ Server Address قىزىمەت وتەۋ اسبابى ٵدىرىسى Port اۋٸزٸ Cancel كۇشىنەن قالدىرۋ Confirm كەسٸم جاساۋ Proxy Proxy ۋاكىلەتىنەن Start using ٸستەتلۋٸن باستاۋ Proxy mode ۋاكىلەتىنەن تيپى Auto اۆتوماتىك Manual قولدانبا Application Proxy 应用代理 System Proxy ۋاكىلەتىنەن سەستەما Auto url URLتەڭگەرگٸش /Proxy/Auto url Http Proxy Http ۋاكىلەتىنەن /Proxy/Http Proxy Https Proxy Https ۋاكىلەتىنەن /Proxy/Https Proxy Ftp Proxy Ftp ۋاكىلەتىنەن /Proxy/Ftp Proxy Socks Proxy SOCKS ۋاكىلەتىنەن /Proxy/Socks Proxy Port اۋٸزٸ List of ignored hosts. more than one entry, please separate with english semicolon(;) سەل قارالعان باس اپپارات تٸزٸمدٸگٸ،ەنگىلششە نۇكتەلىك پاش ٸستەتڭٸز (;) App Proxy قولدانبالى ۋاكىلەتىنەن /Proxy/App Proxy APT Proxy APT ۋاكىلى /Proxy/APT Proxy Open ٸشٸۋ Server Address : قىزىمەت وتەۋ اسبابى ٵدىرىسى : Port : اۋٸزٸ : Edit تالداۋجاساۋ The APT proxy has been turned off and needs to be restarted to take effect APT ۆاكىلى جابٸلدٸ، قاتە قوزعالتۋعا دۇرٸس كەلسە سونان كۇشكە يە بولادٸ Reboot Later سەل تۇرٸپ قاتە قوزعالت Reboot Now ازىر قاتە قوزعالت The system needs to be restarted to set the APT proxy, whether to reboot APT ۋاكىلدىك ەتۋشى ورنالاسترعان ەتۋ ٷشٸن سەستامانى قاتە قوزعالتۋ كەرەك، قاتە قوزغىتىلامدۇ جوق Proxy type ۋاكىلەتىنەن تۇرى IP address IP ٵدىرىسى Required ٴسوزسىز تولدٸرعٸش Invalid IP Address كۇشكە يە ەمەس IP ٵدىرىسى Username ابونىت مى Optional تالداپ تولدٸرعٸش Password قۇپيا كىلت Cancel كۇشىنەن قالدىرۋ Save ساقتاۋ The following applications are allowed to use this configuration: تومەندەگٸ تولىقتامالاردى ٸستٸتۋگە رۇحسات قىلىندى : kylin-nm/plugins/proxy/translations/ms.ts0000664000175000017500000001776315167651420017635 0ustar fengfeng AptProxyDialog Set APT Proxy Server Address Port Cancel Confirm Proxy Proxy Start using Proxy mode Auto Manual Application Proxy 应用代理 System Proxy Auto url /Proxy/Auto url Http Proxy /Proxy/Http Proxy Https Proxy /Proxy/Https Proxy Ftp Proxy /Proxy/Ftp Proxy Socks Proxy /Proxy/Socks Proxy Port List of ignored hosts. more than one entry, please separate with english semicolon(;) App Proxy /Proxy/App Proxy APT Proxy /Proxy/APT Proxy Open Server Address : Port : Edit The APT proxy has been turned off and needs to be restarted to take effect Reboot Later Reboot Now The system needs to be restarted to set the APT proxy, whether to reboot Proxy type IP address Required Invalid IP Address Username Optional Password Cancel Save The following applications are allowed to use this configuration: kylin-nm/plugins/proxy/translations/tr.ts0000664000175000017500000001753515167646234017647 0ustar fengfeng AptProxyDialog Set APT Proxy Server Address Port Cancel Confirm Proxy Proxy Start using Proxy mode Auto Manual System Proxy Auto url /Proxy/Auto url Http Proxy /Proxy/Http Proxy Https Proxy /Proxy/Https Proxy Ftp Proxy /Proxy/Ftp Proxy Socks Proxy /Proxy/Socks Proxy Port List of ignored hosts. more than one entry, please separate with english semicolon(;) App Proxy /Proxy/App Proxy APT Proxy /Proxy/APT Proxy Open Server Address : Port : Edit The APT proxy has been turned off and needs to be restarted to take effect Reboot Later Reboot Now The system needs to be restarted to set the APT proxy, whether to reboot Proxy type IP address Required Invalid IP Address Username Optional Password Cancel Save The following applications are allowed to use this configuration: kylin-nm/plugins/proxy/translations/bo.ts0000664000175000017500000001755315167646234017622 0ustar fengfeng AptProxyDialog Set APT Proxy Server Address Port Cancel Confirm Proxy Proxy Start using Proxy mode Auto Manual System Proxy Auto url /Proxy/Auto url Http Proxy /Proxy/Http Proxy Https Proxy /Proxy/Https Proxy Ftp Proxy /Proxy/Ftp Proxy Socks Proxy /Proxy/Socks Proxy Port List of ignored hosts. more than one entry, please separate with english semicolon(;) App Proxy /Proxy/App Proxy Open Server Address : Port : Edit Reboot Later Reboot Now APT Proxy /Proxy/APT Proxy The APT proxy has been turned off and needs to be restarted to take effect The system needs to be restarted to set the APT proxy, whether to reboot Proxy type IP address Required Invalid IP Address Username Optional Password Cancel Save The following applications are allowed to use this configuration: kylin-nm/plugins/proxy/translations/ug.ts0000664000175000017500000002135215167646234017625 0ustar fengfeng AptProxyDialog Set APT Proxy APT ۋاكالەتچىسىنى تەسىس قىلىش Server Address مۇلازىمىتېر ئادرېسى Port ئېغىزى Cancel ئەمەلدىن قالدۇرۇش Confirm جەزىملەشتۈرۈش Proxy Proxy ۋاكالىتەن Start using ئىشلىتىشنى باشلاش Proxy mode ۋاكالىتەن تىپى Auto ئاپتۇماتىك Manual قوللانما Application Proxy 应用代理 System Proxy ۋاكالىتەن سېستىما Auto url URLتەڭشىكى /Proxy/Auto url Http Proxy Http ۋاكالىتەن /Proxy/Http Proxy Https Proxy Https ۋاكالىتەن /Proxy/Https Proxy Ftp Proxy Ftp ۋاكالىتەن /Proxy/Ftp Proxy Socks Proxy SOCKS ۋاكالىتەن /Proxy/Socks Proxy Port ئېغىزى List of ignored hosts. more than one entry, please separate with english semicolon(;) سەل قارالغان باش ئاپپارات تىزىملىكى،ئىنگىلىزچە چېكىتلىك پەش ئىشلىتىڭ (;) App Proxy قوللىنشچان ۋاكالىتەن /Proxy/App Proxy APT Proxy APT ۋاكالەتچىسى /Proxy/APT Proxy Open ئېچىش Server Address : مۇلازىمىتېر ئادرېسى : Port : ئېغىزى : Edit تەھرىرلەش The APT proxy has been turned off and needs to be restarted to take effect APT ۋاكالەتچىلىكى تاقالدى، قايتا قوزغىتىشقا توغرا كەلسە ئاندىن كۈچكە ئىگە بولىدۇ Reboot Later سەل تۇرۇپ قايتا قوزغىتىڭ Reboot Now ھازىرلا قايتا قوزغىتىڭ The system needs to be restarted to set the APT proxy, whether to reboot APT ۋاكالەتچىسىنى تەسىس قىلىش ئۈچۈن سىستېمىنى قايتا قوزغىتىش كېرەك، قايتا قوزغىتىلامدۇ يوق Proxy type ۋاكالىتەن تۈرى IP address IP ئادرېسى Required مۇقەررەر تولدۇرۇش Invalid IP Address ئىناۋەتسىز IP ئادرېسى Username ئابونىت نامى Optional تاللاپ تولدۇرۇش Password مەخپىي ئاچقۇچ Cancel ئەمەلدىن قالدۇرۇش Save ساقلاش The following applications are allowed to use this configuration: تۆۋەندىكى سەپلىمىلەرنى ئىشلىتىشكە رۇخسەت قىلىنىدۇ : kylin-nm/plugins/proxy/translations/bo_CN.ts0000664000175000017500000002443715167646234020201 0ustar fengfeng AptProxyDialog Set APT Proxy APT ངོ་ཚབ་ བཙུགས་པ། Server Address ཞབས་ཞུའི་ས་གནས། Port གྲུ་ཁ། Cancel ཕྱིར་འཐེན། Confirm གཏན་འཁེལ་བྱ་དགོས། Proxy Proxy ཚབ་བྱེད་མི་སྣ། Start using བཀོལ་སྤྱོད་བྱེད་འགོ་ཚུགས། Proxy mode ཚབ་བྱེད་དཔེ་དབྱིབས། Auto རང་འགུལ་གྱིས་རླངས་ Manual ལག་དེབ། Application Proxy ཉེར་སྤྱོད་ངོ་ཚབ། System Proxy མ་ལག་གི་ཚབ་བྱེད་ Auto url རླངས་འཁོར་གྱི་དྲ་ཚིགས། /Proxy/Auto url Http Proxy HTTP ཚབ་བྱེད་མི་སྣ། /Proxy/Http Proxy Https Proxy HTTPS ཚབ་བྱེད་མི་སྣ། /Proxy/Https Proxy Ftp Proxy FTP ཚབ་བྱེད་མི་སྣ། /Proxy/Ftp Proxy Socks Proxy SOCKS ཚབ་བྱེད་མི་སྣ། /Proxy/Socks Proxy Port གྲུ་ཁ། List of ignored hosts. more than one entry, please separate with english semicolon(;) སྣང་མེད་དུ་བཞག་པའི་བདག་པོའི་མིང་ཐོ། འཇུག་སྒོ་གཅིག་ལས་བརྒལ་ན་དབྱིན་ཡིག་གི་ཕྱེད་ཀ་དང་ཁ་གྱེས་རོགས། (;) App Proxy ཉེར་སྤྱོད་ངོ་ཚབ། /Proxy/App Proxy APT Proxy APT ཚབ་བྱེད་མི་སྣ། /Proxy/APT Proxy Open སྒོ་ཕྱེ་བ། Server Address : ཞབས་ཞུའི་ཡོ་བྱད་ཀྱི་གནས་ཡུལ Port : གྲུ་ཁ། Edit རྩོམ་སྒྲིག The APT proxy has been turned off and needs to be restarted to take effect ངོ་ཚབ་ཀྱི་སྒོ་བརྒྱབ་ཟིན་པས་ཡང་བསྐྱར་ནུས་པ་ཐོན་པར་བྱ་དགོས། Reboot Later རྗེས་སུ་ཡང་བསྐྱར་ཐེངས་གཅིག་ལ་བསྐྱར་ Reboot Now ད་ལྟ་བསྐྱར་དུ་ལས་ཀ་བྱེད་དགོས། The system needs to be restarted to set the APT proxy, whether to reboot མ་ལག་འདི་བསྐྱར་དུ་འགོ་ཚུགས་ནས་APT ཡི་ཚབ་བྱེད་འཕྲུལ་ཆས་གཏན་འཁེལ་བྱེད་དགོས་པ་དང་། བསྐྱར་དུ་འགོ་འཛུགས་དགོས་མིན་ Proxy type ངོ་ཚབ་ཀྱི་རིགས་དབྱིབས། HTTP HTTP socks4 རྐང་འབོབ་4 socks5 རྐང་འབོབ་5 IP address IPས་གནས། Required བླང་བྱ་བཏོན་པ། Invalid IP Address གོ་མི་ཆོད་པའི་IPས་གནས། Username སྤྱོད་མཁན་གྱི་མིང་། Optional བསལ་འདེམས་ཀྱི་རང་བཞིན། Password གསང་གྲངས། Cancel ཕྱིར་འཐེན། Save གྲོན་ཆུང་བྱེད་དགོས། The following applications are allowed to use this configuration: གཤམ་གྱི་ཉེར་སྤྱོད་གོ་རིམ་ཁྲོད་དུ་བཀོད་སྒྲིག་འདི་བཀོལ་ཆོག་པ་སྟེ། kylin-nm/plugins/proxy/translations/vi.ts0000664000175000017500000002040015167651420017612 0ustar fengfeng AptProxyDialog Set APT Proxy Thiết lập proxy cho APT Server Address Địa chỉ máy chủ Port Cổng máy chủ Cancel Hủy Confirm Lưu sửa đổi Proxy Proxy Đại lý Start using Bắt đầu sử dụng Proxy mode Chế độ proxy Auto Theo hệ thống Manual Sách hướng dẫn Application Proxy 应用代理 System Proxy Proxy hệ thống Auto url URL tự động /Proxy/Auto url Http Proxy Http Proxy /Proxy/Http Proxy Https Proxy Https Proxy /Proxy/Https Proxy Ftp Proxy Ftp Proxy /Proxy/Ftp Proxy Socks Proxy Socks Proxy /Proxy/Socks Proxy Port Cổng máy chủ List of ignored hosts. more than one entry, please separate with english semicolon(;) Danh sách các máy chủ bị bỏ qua. nhiều hơn một mục nhập, vui lòng tách bằng dấu chấm phẩy tiếng Anh (;) App Proxy Proxy ứng dụng /Proxy/App Proxy APT Proxy Proxy Apt /Proxy/APT Proxy Open Bật Server Address : Địa chỉ máy chủ: Port : Cổng: Edit biên soạn The APT proxy has been turned off and needs to be restarted to take effect Proxy APT đã bị tắt và cần được khởi động lại để có hiệu lực Reboot Later Khởi động lại sau Reboot Now Khởi động lại ngay The system needs to be restarted to set the APT proxy, whether to reboot Việc thiết lập proxy APT cần khởi động lại hệ thống để có hiệu lực, có muốn khởi động lại hệ thống không Proxy type Loại Proxy IP address Địa chỉ IP Required Bắt buộc điền Invalid IP Address Địa chỉ IP không hợp lệ Username Tên người dùng Optional Tùy chọn Password Mật khẩu Cancel Hủy Save Lưu The following applications are allowed to use this configuration: Cho phép ứng dụng sau sử dụng cấu hình này: kylin-nm/plugins/proxy/translations/mn.ts0000664000175000017500000002311515167646234017623 0ustar fengfeng AptProxyDialog Set APT Proxy APT ᠤᠷᠤᠯᠠᠭᠴᠢ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠬᠤ Server Address ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ ᠤ᠋ᠨ ᠬᠠᠶᠢᠭ Port ᠦᠵᠦᠬᠦᠷ Cancel ᠦᠬᠡᠢᠰᠬᠡᠬᠦ Confirm ᠪᠠᠳᠤᠯᠠᠬᠤ Proxy Proxy ᠤᠷᠤᠯᠠᠭᠴᠢ Start using ᠡᠬᠢᠯᠡᠬᠦᠯᠬᠦ Proxy mode ᠤᠷᠤᠯᠠᠭᠴᠢ ᠵᠢᠨ ᠳᠦᠷᠦᠯ ᠵᠦᠢᠯ Auto ᠠᠦ᠋ᠲ᠋ᠣ᠋ Manual ᠠᠦ᠋ᠲ᠋ᠣ᠋ ᠪᠤᠰᠤ Application Proxy ᠬᠡᠷᠡᠭᠯᠡᠭᠡᠨ ᠤ᠋ ᠤᠷᠤᠯᠠᠭᠴᠢ System Proxy ᠰᠢᠰᠲ᠋ᠧᠮ ᠤ᠋ᠨ ᠤᠷᠤᠯᠠᠭᠴᠢ Auto url URL ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ /Proxy/Auto url Http Proxy HTTP ᠤᠷᠤᠯᠠᠭᠴᠢ /Proxy/Http Proxy Https Proxy HTTPS ᠤᠷᠤᠯᠠᠭᠴᠢ /Proxy/Https Proxy Ftp Proxy FTP ᠤᠷᠤᠯᠠᠭᠴᠢ /Proxy/Ftp Proxy Socks Proxy SOCKS ᠤᠷᠤᠯᠠᠭᠴᠢ /Proxy/Socks Proxy Port ᠦᠵᠦᠬᠦᠷ List of ignored hosts. more than one entry, please separate with english semicolon(;) ᠤᠮᠳᠤᠭᠠᠢᠯᠠᠭᠰᠠᠨ ᠭᠤᠤᠯ ᠮᠠᠰᠢᠨ ᠤ᠋ ᠵᠢᠭᠰᠠᠭᠠᠯᠳᠠ᠂ ᠠᠩᠭ᠌ᠯᠢ ᠬᠡᠯᠡᠨ ᠤ᠋ ᠵᠠᠭᠠᠭᠯᠠᠬᠤ ᠳᠡᠮᠳᠡᠭ ᠢ᠋ ᠬᠡᠷᠡᠭᠯᠡᠬᠡᠷᠡᠢ (;) App Proxy ᠬᠡᠷᠡᠭᠯᠡᠭᠡᠨ ᠤ᠋ ᠤᠷᠤᠯᠠᠭᠴᠢ /Proxy/App Proxy APT Proxy APT ᠤᠷᠤᠯᠠᠭᠴᠢ /Proxy/APT Proxy Open ᠨᠡᠬᠡᠬᠡᠬᠦ Server Address : ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ ᠤ᠋ᠨ ᠬᠠᠶᠢᠭ: Port : ᠫᠤᠷᠲ : Edit ᠨᠠᠢᠷᠠᠭᠤᠯᠬᠤ The APT proxy has been turned off and needs to be restarted to take effect APT ᠤᠷᠤᠯᠠᠭᠴᠢ ᠬᠠᠭᠠᠭᠳᠠᠪᠠ᠂ ᠳᠠᠬᠢᠵᠤ ᠨᠡᠬᠡᠬᠡᠭᠰᠡᠨ ᠤ᠋ ᠳᠠᠷᠠᠭ᠎ᠠ ᠰᠠᠶᠢ ᠬᠦᠴᠦᠨ ᠲᠠᠢ ᠪᠤᠯᠤᠨ᠎ᠠ Reboot Later ᠤᠳᠠᠰᠬᠢᠭᠠᠳ ᠳᠠᠬᠢᠨ ᠡᠬᠢᠯᠡᠬᠦᠯᠬᠦ Reboot Now ᠳᠠᠷᠤᠢ ᠳᠠᠬᠢᠨ ᠡᠬᠢᠯᠡᠬᠦᠯᠬᠦ The system needs to be restarted to set the APT proxy, whether to reboot ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠤᠭᠰᠠᠨ APT ᠤᠷᠤᠯᠠᠭᠴᠢ ᠰᠢᠰᠲ᠋ᠧᠮ ᠢ᠋ ᠳᠠᠬᠢᠨ ᠡᠬᠢᠯᠡᠬᠦᠯᠦᠭᠰᠡᠨ ᠤ᠋ ᠳᠠᠷᠠᠭ᠎ᠠ ᠰᠠᠶᠢ ᠬᠦᠴᠦᠨ ᠲᠠᠢ ᠪᠤᠯᠤᠨ᠎ᠠ᠂ ᠰᠢᠰᠲ᠋ᠧᠮ ᠢ᠋ ᠳᠠᠬᠢᠨ ᠡᠬᠢᠯᠡᠬᠦᠯᠬᠦ ᠤᠤ Proxy type ᠤᠷᠤᠯᠠᠭᠴᠢ ᠵᠢᠨ ᠳᠦᠷᠦᠯ ᠵᠦᠢᠯ IP address IP ᠬᠠᠶᠢᠭ Required ᠡᠷᠬᠡᠪᠰᠢ ᠳᠠᠭᠯᠠᠬᠤ Invalid IP Address ᠬᠦᠴᠦᠨ ᠦᠭᠡᠢ IP ᠬᠠᠶᠢᠭ Username ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠡᠷ᠎ᠡ Optional ᠰᠤᠩᠭᠤᠵᠤ ᠳᠠᠭᠯᠠᠬᠤ Password ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ Cancel ᠦᠬᠡᠢᠰᠬᠡᠬᠦ Save ᠬᠠᠳᠠᠭᠠᠯᠠᠬᠤ The following applications are allowed to use this configuration: ᠳᠤᠤᠷᠠᠬᠢ ᠬᠡᠷᠡᠭᠯᠡᠭᠡ ᠲᠤᠰ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ ᠵᠢ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ ᠵᠢ ᠵᠦᠪᠰᠢᠶᠡᠷᠡᠨ᠎ᠡ: kylin-nm/plugins/proxy/translations/zh_Hant.ts0000664000175000017500000002006715167646234020607 0ustar fengfeng AptProxyDialog Set APT Proxy 設置APT代理 Server Address 伺服器位址 Port Cancel 取消 Confirm 確定 Proxy Proxy 代理 Start using 啟用 Proxy mode 代理類型 Auto 自動 Manual 手動 Application Proxy 應用代理 System Proxy 系統代理 Auto url 配置 URL /Proxy/Auto url Http Proxy HTTP 代理 /Proxy/Http Proxy Https Proxy HTTPS 代理 /Proxy/Https Proxy Ftp Proxy FTP 代理 /Proxy/Ftp Proxy Socks Proxy SOCKS 代理 /Proxy/Socks Proxy Port List of ignored hosts. more than one entry, please separate with english semicolon(;) 忽略的主機清單,請使用英文分號(; ) App Proxy 應用代理 /Proxy/App Proxy APT Proxy APT 代理 /Proxy/APT Proxy Open 開啟 Server Address : 伺服器位址: Port : 埠: Edit 編輯 The APT proxy has been turned off and needs to be restarted to take effect APT代理已關閉,需要重新啟動才能生效 The apt proxy has been turned off and needs to be restarted to take effect apt 代理已關閉,需要重新啟動才能生效 Reboot Later 稍後重啟 Reboot Now 立即重啟 The system needs to be restarted to set the APT proxy, whether to reboot 設置APT代理需要重啟系統後生效,是否重啟系統 Proxy type 代理類型 IP address IP 位址 Required 必填 Invalid IP Address 無效的IP位址 Username 使用者名 Optional 選填 Password 密碼 Cancel 取消 Save 保存 The following applications are allowed to use this configuration: 允許以下應用使用該設定: kylin-nm/plugins/proxy/translations/fr.ts0000664000175000017500000002011215167646234017612 0ustar fengfeng AptProxyDialog Set APT Proxy Définir le proxy APT Server Address Adresse du serveur Port Port Cancel Annuler Confirm Confirmer Proxy Proxy Procuration Start using Commencer à utiliser Proxy mode Mode proxy Auto Auto Manual Manuelle Application Proxy Proxy d’application System Proxy Proxy système Auto url URL automatique /Proxy/Auto url Http Proxy Http Proxy /Proxy/Http Proxy Https Proxy Https Proxy /Proxy/Https Proxy Ftp Proxy Ftp Proxy /Proxy/Ftp Proxy Socks Proxy Chaussettes Proxy /Proxy/Socks Proxy Port Port List of ignored hosts. more than one entry, please separate with english semicolon(;) Liste des hôtes ignorés. plus d’une entrée, veuillez les séparer par un point-virgule anglais (;) App Proxy Proxy d’application /Proxy/App Proxy APT Proxy APT Proxy /Proxy/APT Proxy Open Ouvrir Server Address : Adresse du serveur : Port : Port: Edit Éditer The APT proxy has been turned off and needs to be restarted to take effect Le proxy APT a été désactivé et doit être redémarré pour prendre effet Reboot Later Redémarrer plus tard Reboot Now Redémarrez maintenant The system needs to be restarted to set the APT proxy, whether to reboot Le système doit être redémarré pour définir le proxy APT, s’il faut redémarrer Proxy type Type de proxy IP address Adresse IP Required Obligatoire Invalid IP Address Adresse IP non valide Username Nom d’utilisateur Optional Optionnel Password Mot de passe Cancel Annuler Save Sauvegarder The following applications are allowed to use this configuration: Les applications suivantes sont autorisées à utiliser cette configuration : kylin-nm/plugins/proxy/translations/en_US.ts0000664000175000017500000001753515167646234020233 0ustar fengfeng AptProxyDialog Set APT Proxy Server Address Port Cancel Confirm Proxy Proxy Start using Proxy mode Auto Manual System Proxy Auto url /Proxy/Auto url Http Proxy /Proxy/Http Proxy Https Proxy /Proxy/Https Proxy Ftp Proxy /Proxy/Ftp Proxy Socks Proxy /Proxy/Socks Proxy Port List of ignored hosts. more than one entry, please separate with english semicolon(;) App Proxy /Proxy/App Proxy APT Proxy /Proxy/APT Proxy Open Server Address : Port : Edit The APT proxy has been turned off and needs to be restarted to take effect Reboot Later Reboot Now The system needs to be restarted to set the APT proxy, whether to reboot Proxy type IP address Required Invalid IP Address Username Optional Password Cancel Save The following applications are allowed to use this configuration: kylin-nm/plugins/proxy/translations/es.ts0000664000175000017500000002005615167646234017621 0ustar fengfeng AptProxyDialog Set APT Proxy Establecer proxy APT Server Address Dirección del servidor Port Puerto Cancel Cancelar Confirm Confirmar Proxy Proxy Proxy Start using Comience a usar Proxy mode Modo proxy Auto Automático Manual Manual Application Proxy Proxy de aplicación System Proxy Proxy del sistema Auto url URL automática /Proxy/Auto url Http Proxy Http Proxy /Proxy/Http Proxy Https Proxy Https Proxy /Proxy/Https Proxy Ftp Proxy Ftp Proxy /Proxy/Ftp Proxy Socks Proxy Proxy de calcetines /Proxy/Socks Proxy Port Puerto List of ignored hosts. more than one entry, please separate with english semicolon(;) Lista de hosts ignorados. más de una entrada, por favor sepárela con punto y coma (;) inglés App Proxy Proxy de aplicación /Proxy/App Proxy APT Proxy APT Proxy /Proxy/APT Proxy Open Abrir Server Address : Dirección del servidor : Port : Puerto: Edit Editar The APT proxy has been turned off and needs to be restarted to take effect El proxy APT se ha desactivado y debe reiniciarse para que surta efecto Reboot Later Reiniciar más tarde Reboot Now Reiniciar ahora The system needs to be restarted to set the APT proxy, whether to reboot Es necesario reiniciar el sistema para configurar el proxy APT, ya sea para reiniciar Proxy type Tipo de proxy IP address Dirección IP Required Obligatorio Invalid IP Address Dirección IP no válida Username Nombre de usuario Optional Opcional Password Contraseña Cancel Cancelar Save Salvar The following applications are allowed to use this configuration: Las siguientes aplicaciones pueden utilizar esta configuración: kylin-nm/plugins/proxy/translations/zh_HK.ts0000664000175000017500000002006715167646234020217 0ustar fengfeng AptProxyDialog Set APT Proxy 設置APT代理 Server Address 伺服器位址 Port Cancel 取消 Confirm 確定 Proxy Proxy 代理 Start using 啟用 Proxy mode 代理類型 Auto 自動 Manual 手動 Application Proxy 應用代理 System Proxy 系統代理 Auto url 配置 URL /Proxy/Auto url Http Proxy HTTP 代理 /Proxy/Http Proxy Https Proxy HTTPS 代理 /Proxy/Https Proxy Ftp Proxy FTP 代理 /Proxy/Ftp Proxy Socks Proxy SOCKS 代理 /Proxy/Socks Proxy Port List of ignored hosts. more than one entry, please separate with english semicolon(;) 忽略的主機清單,請使用英文分號(; ) App Proxy 應用代理 /Proxy/App Proxy APT Proxy APT 代理 /Proxy/APT Proxy Open 開啟 Server Address : 伺服器位址: Port : 埠: Edit 編輯 The APT proxy has been turned off and needs to be restarted to take effect APT代理已關閉,需要重新啟動才能生效 The apt proxy has been turned off and needs to be restarted to take effect apt 代理已關閉,需要重新啟動才能生效 Reboot Later 稍後重啟 Reboot Now 立即重啟 The system needs to be restarted to set the APT proxy, whether to reboot 設置APT代理需要重啟系統後生效,是否重啟系統 Proxy type 代理類型 IP address IP 位址 Required 必填 Invalid IP Address 無效的IP位址 Username 使用者名 Optional 選填 Password 密碼 Cancel 取消 Save 保存 The following applications are allowed to use this configuration: 允許以下應用使用該設定: kylin-nm/plugins/proxy/certificationdialog.h0000664000175000017500000000230115167646234020266 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef CERTIFICATIONDIALOG_H #define CERTIFICATIONDIALOG_H #include #define HTTP_PROXY_SCHEMA "org.gnome.system.proxy.http" #define HTTP_AUTH_KEY "use-authentication" #define HTTP_AUTH_USER_KEY "authentication-user" #define HTTP_AUTH_PASSWD_KEY "authentication-password" #endif // CERTIFICATIONDIALOG_H kylin-nm/plugins/proxy/translate_generation.sh0000775000175000017500000000056615167651420020665 0ustar fengfeng#!/bin/bash export PATH="/usr/lib/qt6/bin:$PATH" ts_list=(`ls translations/*.ts`) source /etc/os-release version=(`echo $ID`) for ts in "${ts_list[@]}" do printf "\nprocess ${ts}\n" if [ "$version" == "fedora" ] || [ "$version" == "opensuse-leap" ] || [ "$version" == "opensuse-tumbleweed" ];then lrelease-qt5 "${ts}" else lrelease "${ts}" fi done kylin-nm/plugins/proxy/aptproxydialog.h0000664000175000017500000000275315167646234017344 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #ifndef APTPROXYDIALOG_H #define APTPROXYDIALOG_H #include #include #include #include #include #include #include #include "klabel.h" using namespace kdk; #define APT_PROXY_SCHEMA "org.ukui.control-center.apt.proxy" #define APT_PROXY_ENABLED "enabled" #define APT_PROXY_HOST_KEY "host" #define APT_PROXY_PORT_KEY "port" class AptProxyDialog : public QDialog { Q_OBJECT public: AptProxyDialog(QWidget *parent = nullptr); ~AptProxyDialog(); void initUi(); private: QLineEdit *mHostEdit; QLineEdit *mPortEdit; QPushButton *mCancelBtn; QPushButton *mConfirmBtn; private: void initConnect(); void setupComponent(); }; #endif // APTPROXYDIALOG_H kylin-nm/plugins/proxy/proxy.h0000664000175000017500000001757715167646234015471 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef PROXY_H #define PROXY_H #include #include #include #include #include #include "certificationdialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "interface.h" #include "klabel.h" #include "hoverwidget.h" #include "applistwidget.h" #include "kswitchbutton.h" #include "kpasswordedit.h" #include "ukcccommon.h" using namespace kdk; using namespace ukcc; /* qt会将glib里的signals成员识别为宏,所以取消该宏 * 后面如果用到signals时,使用Q_SIGNALS代替即可 **/ #ifdef signals #undef signals #endif #include #include struct GSData { QString key; QString schema; }; typedef enum{ NONE, MANUAL, AUTO }ProxyMode; //自定义类型使用QVariant需要使用 Q_DECLARE_METATYPE 注册 Q_DECLARE_METATYPE(ProxyMode) Q_DECLARE_METATYPE(GSData) namespace Ui { class Proxy; } class Proxy : public QObject, CommonInterface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.ukcc.CommonInterface") Q_INTERFACES(CommonInterface) public: Proxy(); ~Proxy(); QString plugini18nName() Q_DECL_OVERRIDE; int pluginTypes() Q_DECL_OVERRIDE; QWidget * pluginUi() Q_DECL_OVERRIDE; void plugin_leave()Q_DECL_OVERRIDE; const QString name() const Q_DECL_OVERRIDE; bool isShowOnHomePage() const Q_DECL_OVERRIDE; QIcon icon() const Q_DECL_OVERRIDE; bool isEnable() const Q_DECL_OVERRIDE; QString translationPath() const Q_DECL_OVERRIDE; public: void initUi(QWidget *widget); void initSearchText(); void retranslateUi(); void setupComponent(); void setupConnect(); void initProxyModeStatus(); void initAutoProxyStatus(); void initManualProxyStatus(); void initIgnoreHostStatus(); void initDbus(); void initAppProxyStatus(); void manualProxyTextChanged(QString txt); int _getCurrentProxyMode(); void _setSensitivity(); bool getAptProxyInfo(bool status); static void setAptProxy(QString host ,QString port ,bool status); // apt代理对应的配置文件的写入或删除 static QHash getAptProxy(); void setAptInfo(); void reboot(); // 调用重启接口 void setFrame_Noframe(QFrame *frame); QFrame *setLine(QFrame *frame); bool getAppProxyState(); //获取应用代理开启状态--调用Dbus void setAppProxyState(bool state); //设置应用代理开启状态--调用Dbus static QStringList getAppProxyConf(); //获取应用代理配置信息--调用Dbus void setAppProxyConf(QStringList list); //设置应用代理配置信息--调用Dbus static QMap getAppListProxy(); // bool checkIsChanged(QStringList info); void setUkccProxySettings(); // 设置控制面板代理模块显示/隐藏 private: void setAppProxyFrameUi(QWidget *widget); void setAppListFrameUi(QWidget *widget); void appProxyInfoPadding(); void appListPadding(); bool getipEditState(QString text); void setSystemProxyFrameHidden(bool state); void setAppProxyFrameHidden(bool state); void setAPTProxyFrameHidden(bool state); QFrame *m_sysSpacerFrame; QFrame *m_appListSpacerFrame; QFrame *m_appSpacerFrame; QString pluginName; int pluginType; QWidget * pluginWidget; KLabel *mTitleLabel; KLabel *m_appProxyLabel; KLabel *mAptProxyLabel; QLabel *mUrlLabel; QLabel *mHTTPLabel; QLabel *mHTTPPortLabel; QLabel *mHTTPSLabel; QLabel *mHTTPSPortLabel; QLabel *mFTPLabel; QLabel *mFTPPortLabel; QLabel *mSOCKSLabel; QLabel *mSOCKSPortLabel; QLabel *mIgnoreLabel; QLabel *mAptLabel; QLabel *mAPTHostLabel_1; QLabel *mAPTHostLabel_2; QLabel *mAPTPortLabel_1; QLabel *mAPTPortLabel_2; QLabel *mCertificationLabel; QLabel *mUserNameLabel; QLabel *mPwdLabel; QLabel *m_appEnableLabel; QLabel *m_proxyTypeLabel; QLabel *m_ipAddressLabel; QLabel *m_ipHintsLabel; QLabel *m_portLabel; QLabel *m_userNameLabel; QLabel *m_pwdLabel; QLabel *m_allowAppProxyLabel; QFrame *mProxyFrame; QFrame *mEnableFrame; QFrame *mSelectFrame; QFrame *mUrlFrame; QFrame *mHTTPFrame; QFrame *mHTTPSFrame; QFrame *mFTPFrame; QFrame *mSOCKSFrame; QFrame *mIgnoreFrame; QFrame *mCertificationFrame_1; QFrame *m_appEnableFrame; QFrame *m_appProxyFrame; QFrame *m_proxyTypeFrame; QFrame *m_ipAddressFrame; QFrame *m_portFrame; QFrame *m_userNameFrame; QFrame *m_pwdFrame; // QFrame *m_appBtnFrame; QFrame *m_appListFrame; QFrame *mAPTFrame; QFrame *mAPTFrame_1; QFrame *mAPTFrame_2; QFrame *line_1; QFrame *line_2; QFrame *line_3; QFrame *line_4; QFrame *line_5; QFrame *line_6; QFrame *line_7; QFrame *line_8; QFrame *m_appLine1; QFrame *m_appLine2; QFrame *m_appLine3; QFrame *m_appLine4; QFrame *m_appLine5; QRadioButton *mAutoBtn; QRadioButton *mManualBtn; KSwitchButton *mEnableBtn; KSwitchButton *mAptBtn; QPushButton *mEditBtn; QCheckBox *mCertificationBtn; QButtonGroup *mProxyBtnGroup; QLineEdit *mUrlLineEdit; QLineEdit *mHTTPLineEdit_1; QLineEdit *mHTTPLineEdit_2; QLineEdit *mHTTPSLineEdit_1; QLineEdit *mHTTPSLineEdit_2; QLineEdit *mFTPLineEdit_1; QLineEdit *mFTPLineEdit_2; QLineEdit *mSOCKSLineEdit_1; QLineEdit *mSOCKSLineEdit_2; QLineEdit *mUserNameLineEdit; QLineEdit *mPwdLineEdit; QLineEdit *m_ipAddressLineEdit; QLineEdit *m_portLineEdit; QLineEdit *m_userNameLineEdit; KSwitchButton *m_appEnableBtn; QComboBox *m_proxyTypeComboBox; KPasswordEdit *m_pwdLineEdit = nullptr; // QPushButton *m_cancelBtn; // QPushButton *m_saveBtn; QListWidget *m_appListWidget = nullptr; QWidget *m_appProxyInfoWidget; QTextEdit *mIgnoreLineEdit; QGSettings * proxysettings; QGSettings * httpsettings; QGSettings * securesettings; QGSettings * ftpsettings; QGSettings * sockssettings; QGSettings * aptsettings; QFileSystemWatcher *mfileWatch_1; QFileSystemWatcher *mfileWatch_2; // QDBusInterface *mAptproxyDbus; QDBusInterface *m_appProxyDbus = nullptr; bool isExistSettings = false; bool settingsCreate; bool mFirstLoad; QStringList m_appProxyInfo; QStringList m_appCheckedList; private slots: void setAptProxySlot(); //处理apt代理前端交互逻辑 void setAppProxyUiEnable(bool enable); void onipEditStateChanged(); //IP地址无效提示 void onAppProxyConfChanged(); //应用代理配置信息变化 void onAppProxyConfEditFinished(); void onPaletteChanged(); // void onCancelBtnClicked(); // void onSaveBtnClicked(); // void setBtnEnable(); }; #endif // PROXY_H kylin-nm/plugins/proxy/applistwidget.h0000664000175000017500000000342615167646234017154 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef APPLISTWIDGET_H #define APPLISTWIDGET_H #include #include #include #include #include #include #include #include #include class AppListWidget : public QWidget { Q_OBJECT public: explicit AppListWidget(QString path, QWidget *parent = nullptr); ~AppListWidget(); void setAppChecked(bool flag); void setAppIcon(const QIcon &icon); void setAppName(const QString &text); void onAppCheckStateChanged(); void AddAppProxyConfig(); void RemoveAppProxyConfig(); protected: void mousePressEvent(QMouseEvent *event); private: void initUI(); void initDbus(); QCheckBox *m_checkBox = nullptr; QToolButton *m_iconBtn = nullptr; QLabel *m_nameLabel = nullptr; QString m_path = nullptr; QDBusInterface *m_dbusInterface = nullptr; }; #endif // APPLISTWIDGET_H kylin-nm/plugins/proxy/aptinfo.h0000664000175000017500000000251615167646234015733 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #ifndef APTINFO_H #define APTINFO_H #include #include #include #include struct AptInfo { QString arg; QDBusVariant out; }; QDBusArgument &operator<<(QDBusArgument &argument, const AptInfo &mystruct) { argument.beginStructure(); argument << mystruct.arg << mystruct.out; argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, AptInfo &mystruct) { argument.beginStructure(); argument >> mystruct.arg >> mystruct.out; argument.endStructure(); return argument; } Q_DECLARE_METATYPE(AptInfo) #endif // APTINFO_H kylin-nm/plugins/proxy/certificationdialog.ui0000664000175000017500000002377515167646234020476 0ustar fengfeng CertificationDialog 0 0 500 246 500 246 500 246 UserCertification 0 0 0 0 0 20 20 25 Qt::Vertical QSizePolicy::Fixed 20 10 10 20 0 0 UserCertification true 0 0 0 0 0 0 Qt::Horizontal QSizePolicy::Fixed 60 20 0 0 60 0 60 16777215 User: 180 0 180 16777215 Qt::Horizontal 40 20 0 Qt::Horizontal QSizePolicy::Fixed 60 20 0 0 60 0 60 16777215 Passwd: 180 0 180 16777215 Qt::Horizontal 40 20 Qt::Horizontal 40 20 Close Qt::Horizontal QSizePolicy::Fixed 40 20 Qt::Vertical QSizePolicy::Fixed 20 80 kylin-nm/plugins/proxy/proxy.pro0000664000175000017500000000307715167651420016021 0ustar fengfeng#include(../../../env.pri) QT += widgets dbus TEMPLATE = lib CONFIG += plugin TARGET = $$qtLibraryTarget(proxy) DESTDIR = ../.. CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } target.path = $$[QT_INSTALL_LIBS]/ukui-control-center trans.files = translations/* trans.path = /usr/share/kylin-nm/proxy/ INCLUDEPATH += \ $$PROJECT_COMPONENTSOURCE \ $$PROJECT_ROOTDIR \ /usr/include/ukcc/interface \ /usr/include/ukcc/widgets LIBS += -L$$[QT_INSTALL_LIBS] -lukcc ##加载gio库和gio-unix库,用于获取和设置enum类型的gsettings CONFIG += link_pkgconfig \ C++11 PKGCONFIG += gio-2.0 \ gio-unix-2.0 \ gsettings-qt6 \ kysdk-applications #DEFINES += QT_DEPRECATED_WARNINGS SOURCES += \ applistwidget.cpp \ aptproxydialog.cpp \ proxy.cpp HEADERS += \ applistwidget.h \ aptinfo.h \ aptproxydialog.h \ proxy.h \ certificationdialog.h FORMS += INSTALLS += target \ trans TRANSLATIONS += \ translations/zh_Hant.ts \ translations/zh_HK.ts \ translations/zh_CN.ts \ translations/ug.ts \ translations/tr.ts \ translations/mn.ts \ translations/ky.ts \ translations/kk.ts \ translations/fr.ts \ translations/es.ts \ translations/en_US.ts \ translations/de.ts \ translations/bo.ts\ translations/bo_CN.ts kylin-nm/plugins/proxy/proxy.cpp0000664000175000017500000015146615167651420016011 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "proxy.h" #include "aptproxydialog.h" #include "aptinfo.h" //#include "utils.h" #include #include #include #include #define PROXY_SCHEMA "org.gnome.system.proxy" #define PROXY_MODE_KEY "mode" #define PROXY_AUTOCONFIG_URL_KEY "autoconfig-url" #define IGNORE_HOSTS_KEY "ignore-hosts" #define HTTP_PROXY_SCHEMA "org.gnome.system.proxy.http" #define HTTP_USE_AUTH_KEY "use-authentication" #define HTTP_AUTH_USER_KEY "authentication-user" #define HTTP_AUTH_PASSWD_KEY "authentication-password" #define HTTPS_PROXY_SCHEMA "org.gnome.system.proxy.https" #define FTP_PROXY_SCHEMA "org.gnome.system.proxy.ftp" #define SOCKS_PROXY_SCHEMA "org.gnome.system.proxy.socks" #define PROXY_HOST_KEY "host" #define PROXY_PORT_KEY "port" #define THEME_SCHAME "org.ukui.style" #define FRAME_LAYOUT_MARGINS 16,0,16,0 #define FRAME_LAYOUT_SPACING 8 #define LABEL_WIDTH 136 #define LINE_EDIT_HEIGHT 36 Proxy::Proxy() : mFirstLoad(true) { qDBusRegisterMetaType>(); qDBusRegisterMetaType(); QTranslator* translator = new QTranslator(this); translator->load("/usr/share/kylin-nm/proxy/" + QLocale::system().name()); QApplication::installTranslator(translator); pluginName = tr("Proxy"); pluginType = NETWORK; } Proxy::~Proxy() { if (!mFirstLoad) { plugin_leave(); delete m_appProxyDbus; } } QString Proxy::plugini18nName() { return pluginName; } int Proxy::pluginTypes() { return pluginType; } QWidget *Proxy::pluginUi() { if (mFirstLoad) { mFirstLoad = false; pluginWidget = new QWidget; pluginWidget->setAttribute(Qt::WA_DeleteOnClose); initUi(pluginWidget); retranslateUi(); mfileWatch_1 = new QFileSystemWatcher(this); mfileWatch_2 = new QFileSystemWatcher(this); QString dir_1("/etc/apt/apt.conf.d"); QString dir_2("/etc/profile.d"); mfileWatch_1->addPath(dir_1); mfileWatch_2->addPath(dir_2); const QByteArray id(PROXY_SCHEMA); const QByteArray idd(HTTP_PROXY_SCHEMA); const QByteArray iddd(HTTPS_PROXY_SCHEMA); const QByteArray iid(FTP_PROXY_SCHEMA); const QByteArray iiid(SOCKS_PROXY_SCHEMA); const QByteArray iVd(APT_PROXY_SCHEMA); initSearchText(); setupComponent(); if (QGSettings::isSchemaInstalled(id) && QGSettings::isSchemaInstalled(idd) && QGSettings::isSchemaInstalled(iddd) && QGSettings::isSchemaInstalled(iid) && QGSettings::isSchemaInstalled(iiid) && QGSettings::isSchemaInstalled(iVd)){ isExistSettings = true; proxysettings = new QGSettings(id,QByteArray(),this); httpsettings = new QGSettings(idd,QByteArray(),this); securesettings = new QGSettings(iddd,QByteArray(),this); ftpsettings = new QGSettings(iid,QByteArray(),this); sockssettings = new QGSettings(iiid,QByteArray(),this); setupConnect(); initProxyModeStatus(); initAutoProxyStatus(); initManualProxyStatus(); initIgnoreHostStatus(); initDbus(); // initAppProxyStatus(); } else { qCritical() << "Xml needed by Proxy is not installed"; } setUkccProxySettings(); } return pluginWidget; } void Proxy::plugin_leave() { if (isExistSettings) { if (proxysettings->get(PROXY_MODE_KEY) == "manual") { if ((httpsettings->get(PROXY_HOST_KEY).toString().isEmpty() || httpsettings->get(PROXY_PORT_KEY).toInt() == 0) && (securesettings->get(PROXY_HOST_KEY).toString().isEmpty() || securesettings->get(PROXY_PORT_KEY).toInt() == 0) && (ftpsettings->get(PROXY_HOST_KEY).toString().isEmpty() || ftpsettings->get(PROXY_PORT_KEY).toInt() == 0) && (sockssettings->get(PROXY_HOST_KEY).toString().isEmpty() || sockssettings->get(PROXY_PORT_KEY).toInt() == 0)) { proxysettings->set(PROXY_MODE_KEY,"auto"); mManualBtn->setChecked(false); mAutoBtn->setChecked(true); _setSensitivity(); } } } } const QString Proxy::name() const { return QStringLiteral("Proxy"); } bool Proxy::isShowOnHomePage() const { return true; } QIcon Proxy::icon() const { return QIcon::fromTheme("ukui-network-agent-symbolic"); } QString Proxy::translationPath() const { return "/usr/share/kylin-nm/proxy/%1.ts"; } bool Proxy::isEnable() const { return true; } void Proxy::initUi(QWidget *widget) { QVBoxLayout *mverticalLayout = new QVBoxLayout(widget); mverticalLayout->setSpacing(8); mverticalLayout->setContentsMargins(0, 0, 0, 0); mProxyBtnGroup = new QButtonGroup(this); mProxyBtnGroup->setExclusive (false); // 防止互斥 mTitleLabel = new KLabel(widget); mTitleLabel->setContentsMargins(16, 0, 0, 0); mProxyFrame = new QFrame(widget); mProxyFrame->setMinimumSize(QSize(550, 0)); mProxyFrame->setMaximumSize(QSize(16777215, 16777215)); mProxyFrame->setFrameShape(QFrame::Box); QVBoxLayout *Lyt = new QVBoxLayout(mProxyFrame); Lyt->setContentsMargins(0, 0, 0, 0); Lyt->setSpacing(0); mEnableFrame = new QFrame(mProxyFrame); setFrame_Noframe(mEnableFrame); QHBoxLayout *enableLyt = new QHBoxLayout(mEnableFrame); enableLyt->setContentsMargins(16, 0, 16, 0); QLabel *enableLabel = new QLabel(tr("Start using"), mEnableFrame); mEnableBtn = new KSwitchButton(mEnableFrame); enableLyt->addWidget(enableLabel); enableLyt->addStretch(); enableLyt->addWidget(mEnableBtn); line_8 = setLine(mProxyFrame); mSelectFrame = new QFrame(mProxyFrame); setFrame_Noframe(mSelectFrame); QHBoxLayout *selectLyt = new QHBoxLayout(mSelectFrame); selectLyt->setContentsMargins(16, 0, 16, 0); selectLyt->setSpacing(4); QLabel *selectLabel = new QLabel(tr("Proxy mode"), mSelectFrame); selectLabel->setFixedWidth(148); mAutoBtn = new QRadioButton(mSelectFrame); mProxyBtnGroup->addButton(mAutoBtn); QLabel *autoLabel = new QLabel(tr("Auto"), mSelectFrame); mManualBtn = new QRadioButton(mSelectFrame); mProxyBtnGroup->addButton(mManualBtn); QLabel *manualLabel = new QLabel(tr("Manual"), mSelectFrame); selectLyt->addWidget(selectLabel); selectLyt->addWidget(mAutoBtn); selectLyt->addWidget(autoLabel); selectLyt->addSpacing(100); selectLyt->addWidget(mManualBtn); selectLyt->addWidget(manualLabel); selectLyt->addStretch(); line_1 = setLine(mProxyFrame); mUrlFrame = new QFrame(mProxyFrame); setFrame_Noframe(mUrlFrame); QHBoxLayout *mUrlLayout = new QHBoxLayout(mUrlFrame); mUrlLayout->setContentsMargins(16, 0, 16, 0); mUrlLayout->setSpacing(8); mUrlLabel = new QLabel(mUrlFrame); mUrlLabel->setFixedWidth(136); mUrlLineEdit = new QLineEdit(mUrlFrame); mUrlLineEdit->setFixedHeight(36); mUrlLayout->addWidget(mUrlLabel); mUrlLayout->addWidget(mUrlLineEdit); line_2 = setLine(mProxyFrame); mHTTPFrame = new QFrame(mProxyFrame); setFrame_Noframe(mHTTPFrame); QHBoxLayout *mHTTPLayout_1 = new QHBoxLayout(mHTTPFrame); mHTTPLayout_1->setSpacing(8); mHTTPLayout_1->setContentsMargins(16, 0, 16, 0); mHTTPLabel = new QLabel(mHTTPFrame); mHTTPLabel->setFixedWidth(136); mHTTPPortLabel = new QLabel(mHTTPFrame); mHTTPPortLabel->setFixedWidth(100); mHTTPPortLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); mHTTPLineEdit_1 = new QLineEdit(mHTTPFrame); mHTTPLineEdit_1->resize(300, 36); mHTTPLineEdit_2 = new QLineEdit(mHTTPFrame); mHTTPLineEdit_2->setFixedHeight(36); mHTTPLineEdit_2->setValidator(new QRegularExpressionValidator(QRegularExpression("[0-9]*") , this)); mHTTPLayout_1->addWidget(mHTTPLabel); mHTTPLayout_1->addWidget(mHTTPLineEdit_1); mHTTPLayout_1->addWidget(mHTTPPortLabel); mHTTPLayout_1->addWidget(mHTTPLineEdit_2); line_3 = setLine(mProxyFrame); mHTTPSFrame = new QFrame(mProxyFrame); setFrame_Noframe(mHTTPSFrame); QHBoxLayout *mHTTPSLayout = new QHBoxLayout(mHTTPSFrame); mHTTPSLayout->setSpacing(8); mHTTPSLayout->setContentsMargins(16, 0, 16, 0); mHTTPSLabel = new QLabel(mHTTPSFrame); mHTTPSLabel->setFixedWidth(136); mHTTPSPortLabel = new QLabel(mHTTPSFrame); mHTTPSPortLabel->setFixedWidth(100); mHTTPSPortLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); mHTTPSLineEdit_1 = new QLineEdit(mHTTPSFrame); mHTTPSLineEdit_1->resize(300, 36); mHTTPSLineEdit_2 = new QLineEdit(mHTTPSFrame); mHTTPSLineEdit_2->setFixedHeight(36); mHTTPSLineEdit_2->setValidator(new QRegularExpressionValidator(QRegularExpression("[0-9]*") , this)); mHTTPSLayout->addWidget(mHTTPSLabel); mHTTPSLayout->addWidget(mHTTPSLineEdit_1); mHTTPSLayout->addWidget(mHTTPSPortLabel); mHTTPSLayout->addWidget(mHTTPSLineEdit_2); line_4 = setLine(mProxyFrame); mFTPFrame = new QFrame(mProxyFrame); setFrame_Noframe(mFTPFrame); QHBoxLayout *mFTPLayout = new QHBoxLayout(mFTPFrame); mFTPLayout->setSpacing(8); mFTPLayout->setContentsMargins(16, 0, 16, 0); mFTPLabel = new QLabel(mFTPFrame); mFTPLabel->setFixedWidth(136); mFTPPortLabel = new QLabel(mFTPFrame); mFTPPortLabel->setFixedWidth(100); mFTPPortLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); mFTPLineEdit_1 = new QLineEdit(mFTPFrame); mFTPLineEdit_1->resize(300, 36); mFTPLineEdit_2 = new QLineEdit(mFTPFrame); mFTPLineEdit_2->setFixedHeight(36); mFTPLineEdit_2->setValidator(new QRegularExpressionValidator(QRegularExpression("[0-9]*") , this)); mFTPLayout->addWidget(mFTPLabel); mFTPLayout->addWidget(mFTPLineEdit_1); mFTPLayout->addWidget(mFTPPortLabel); mFTPLayout->addWidget(mFTPLineEdit_2); line_5 = setLine(mProxyFrame); mSOCKSFrame = new QFrame(mProxyFrame); setFrame_Noframe(mSOCKSFrame); QHBoxLayout *mSOCKSLayout = new QHBoxLayout(mSOCKSFrame); mSOCKSLayout->setSpacing(8); mSOCKSLayout->setContentsMargins(16, 0, 16, 0); mSOCKSLabel = new QLabel(mSOCKSFrame); mSOCKSLabel->setFixedWidth(136); mSOCKSPortLabel = new QLabel(mSOCKSFrame); mSOCKSPortLabel->setFixedWidth(100); mSOCKSPortLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); mSOCKSLineEdit_1 = new QLineEdit(mSOCKSFrame); mSOCKSLineEdit_1->resize(300, 36); mSOCKSLineEdit_2 = new QLineEdit(mSOCKSFrame); mSOCKSLineEdit_2->setFixedHeight(36); mSOCKSLineEdit_2->setValidator(new QRegularExpressionValidator(QRegularExpression("[0-9]*") , this)); mSOCKSLayout->addWidget(mSOCKSLabel); mSOCKSLayout->addWidget(mSOCKSLineEdit_1); mSOCKSLayout->addWidget(mSOCKSPortLabel); mSOCKSLayout->addWidget(mSOCKSLineEdit_2); line_6 = setLine(mProxyFrame); mIgnoreFrame = new QFrame(mProxyFrame); mIgnoreFrame->setMinimumSize(QSize(550, 0)); mIgnoreFrame->setMaximumSize(QSize(16777215, 16777215)); mIgnoreFrame->setFrameShape(QFrame::NoFrame); QVBoxLayout *mIgnoreLayout = new QVBoxLayout(mIgnoreFrame); mIgnoreLayout->setSpacing(10); mIgnoreLayout->setContentsMargins(16, 0, 16, 24); mIgnoreLabel = new QLabel(mIgnoreFrame); mIgnoreLabel->setWordWrap(true); mIgnoreLineEdit = new QTextEdit(mIgnoreFrame); mIgnoreLineEdit->setFixedHeight(120); mIgnoreLineEdit->setStyleSheet("border-radius:6px;background-color: palette(button)"); mIgnoreLayout->addWidget(mIgnoreLabel); mIgnoreLayout->addWidget(mIgnoreLineEdit); Lyt->addWidget(mEnableFrame); Lyt->addWidget(line_8); Lyt->addWidget(mSelectFrame); Lyt->addWidget(line_1); Lyt->addWidget(mUrlFrame); Lyt->addWidget(line_2); Lyt->addWidget(mHTTPFrame); Lyt->addWidget(line_3); Lyt->addWidget(mHTTPSFrame); Lyt->addWidget(line_4); Lyt->addWidget(mFTPFrame); Lyt->addWidget(line_5); Lyt->addWidget(mSOCKSFrame); Lyt->addWidget(line_6); Lyt->addWidget(mIgnoreFrame); //应用代理模块 // m_appProxyLabel = new TitleLabel(widget); // m_appProxyLabel->setText(tr("Application Proxy")); //应用代理 // setAppProxyFrameUi(widget); // setAppListFrameUi(widget); //APT代理模块 mAptProxyLabel = new KLabel(widget); mAptProxyLabel->setContentsMargins(16, 0, 0, 0); mAPTFrame = new QFrame(widget); mAPTFrame->setMinimumSize(QSize(550, 0)); mAPTFrame->setMaximumSize(QSize(16777215, 16777215)); mAPTFrame->setFrameShape(QFrame::Box); QVBoxLayout *AptLayout = new QVBoxLayout(mAPTFrame); AptLayout->setContentsMargins(0, 0, 0, 0); AptLayout->setSpacing(0); mAPTFrame_1 = new QFrame(mAPTFrame); setFrame_Noframe(mAPTFrame_1); QHBoxLayout *mAptLayout_1 = new QHBoxLayout(mAPTFrame_1); mAptLayout_1->setContentsMargins(16, 0, 16, 0); mAptLayout_1->setSpacing(8); mAptLabel = new QLabel(mAPTFrame_1); mAptLabel->setFixedWidth(200); mAptBtn = new KSwitchButton(mAPTFrame_1); mAptLayout_1->addWidget(mAptLabel); mAptLayout_1->addStretch(); mAptLayout_1->addWidget(mAptBtn); mAPTFrame_2 = new QFrame(mAPTFrame); setFrame_Noframe(mAPTFrame_2); QHBoxLayout *mAptLayout_2 = new QHBoxLayout(mAPTFrame_2); mAptLayout_2->setContentsMargins(16, 0, 16, 0); mAptLayout_2->setSpacing(8); mAPTHostLabel_1 = new QLabel(mAPTFrame_2); mAPTHostLabel_2 = new QLabel(mAPTFrame_2); mAPTPortLabel_1 = new QLabel(mAPTFrame_2); mAPTPortLabel_2 = new QLabel(mAPTFrame_2); mEditBtn = new QPushButton(mAPTFrame_2); mEditBtn->setFixedWidth(80); mAptLayout_2->addWidget(mAPTHostLabel_1); mAptLayout_2->addWidget(mAPTHostLabel_2); mAptLayout_2->addSpacing(100); mAptLayout_2->addWidget(mAPTPortLabel_1); mAptLayout_2->addWidget(mAPTPortLabel_2); mAptLayout_2->addStretch(); mAptLayout_2->addWidget(mEditBtn,Qt::AlignRight); line_7 = setLine(mAPTFrame); AptLayout->addWidget(mAPTFrame_1); AptLayout->addWidget(line_7); AptLayout->addWidget(mAPTFrame_2); m_sysSpacerFrame = new QFrame(widget); m_sysSpacerFrame->setFixedHeight(32); m_appListSpacerFrame = new QFrame(widget); m_appListSpacerFrame->setFixedHeight(4); m_appSpacerFrame = new QFrame(widget);; m_appSpacerFrame->setFixedHeight(32);; mverticalLayout->addWidget(mTitleLabel); mverticalLayout->addWidget(mProxyFrame); mverticalLayout->addWidget(m_sysSpacerFrame); // mverticalLayout->addWidget(m_appProxyLabel); // mverticalLayout->addWidget(m_appProxyFrame); mverticalLayout->addWidget(m_appListSpacerFrame); // mverticalLayout->addWidget(m_appListFrame); // mverticalLayout->addWidget(m_appSpacerFrame); mverticalLayout->addWidget(mAptProxyLabel); mverticalLayout->addWidget(mAPTFrame); mverticalLayout->addStretch(); } void Proxy::initSearchText() { } void Proxy::retranslateUi() { mTitleLabel->setText(tr("System Proxy")); //~ contents_path /Proxy/Auto url mUrlLabel->setText(tr("Auto url")); //~ contents_path /Proxy/Http Proxy mHTTPLabel->setText(tr("Http Proxy")); //~ contents_path /Proxy/Https Proxy mHTTPSLabel->setText(tr("Https Proxy")); //~ contents_path /Proxy/Ftp Proxy mFTPLabel->setText(tr("Ftp Proxy")); //~ contents_path /Proxy/Socks Proxy mSOCKSLabel->setText(tr("Socks Proxy")); mHTTPPortLabel->setText(tr("Port")); mHTTPSPortLabel->setText(tr("Port")); mFTPPortLabel->setText(tr("Port")); mSOCKSPortLabel->setText(tr("Port")); mIgnoreLabel->setText(tr("List of ignored hosts. more than one entry, please separate with english semicolon(;)")); //~ contents_path /Proxy/App Proxy tr("App Proxy"); //~ contents_path /Proxy/APT Proxy mAptProxyLabel->setText(tr("APT Proxy")); mAptLabel->setText(tr("Open")); mAPTHostLabel_1->setText(tr("Server Address : ")); mAPTPortLabel_1->setText(tr("Port : ")); mEditBtn->setText(tr("Edit")); } void Proxy::setupComponent(){ //QLineEdit 设置数据 GSData httpHostData; httpHostData.schema = HTTP_PROXY_SCHEMA; httpHostData.key = PROXY_HOST_KEY; mHTTPLineEdit_1->setProperty("gData", QVariant::fromValue(httpHostData)); GSData httpsHostData; httpsHostData.schema = HTTPS_PROXY_SCHEMA; httpsHostData.key = PROXY_HOST_KEY; mHTTPSLineEdit_1->setProperty("gData", QVariant::fromValue(httpsHostData)); GSData ftpHostData; ftpHostData.schema = FTP_PROXY_SCHEMA; ftpHostData.key = PROXY_HOST_KEY; mFTPLineEdit_1->setProperty("gData", QVariant::fromValue(ftpHostData)); GSData socksHostData; socksHostData.schema = SOCKS_PROXY_SCHEMA; socksHostData.key = PROXY_HOST_KEY; mSOCKSLineEdit_1->setProperty("gData", QVariant::fromValue(socksHostData)); GSData httpPortData; httpPortData.schema = HTTP_PROXY_SCHEMA; httpPortData.key = PROXY_PORT_KEY; mHTTPLineEdit_2->setProperty("gData", QVariant::fromValue(httpPortData)); GSData httpsPortData; httpsPortData.schema = HTTPS_PROXY_SCHEMA; httpsPortData.key = PROXY_PORT_KEY; mHTTPSLineEdit_2->setProperty("gData", QVariant::fromValue(httpsPortData)); GSData ftpPortData; ftpPortData.schema = FTP_PROXY_SCHEMA; ftpPortData.key = PROXY_PORT_KEY; mFTPLineEdit_2->setProperty("gData", QVariant::fromValue(ftpPortData)); GSData socksPortData; socksPortData.schema = SOCKS_PROXY_SCHEMA; socksPortData.key = PROXY_PORT_KEY; mSOCKSLineEdit_2->setProperty("gData", QVariant::fromValue(socksPortData)); } void Proxy::setupConnect(){ connect(mEnableBtn, &KSwitchButton::stateChanged, this ,[=](bool checked) { UkccCommon::buriedSettings(QString("Proxy"), QString("System Proxy Open"), QString("settings"), checked?"true":"false"); mSelectFrame->setVisible(checked); line_8->setVisible(checked); mAutoBtn->setChecked(checked); mManualBtn->setChecked(false); qDebug()<isChecked(); proxysettings->set(PROXY_MODE_KEY, checked ? "auto" : "none"); _setSensitivity(); }); connect(mEditBtn ,&QPushButton::clicked, this, &Proxy::setAptProxySlot); connect(mProxyBtnGroup, QOverload::of(&QButtonGroup::buttonClicked), [=](QAbstractButton * eBtn){ if (eBtn == mAutoBtn) { UkccCommon::buriedSettings(QString("Proxy"), QString("auto"), QString("clicked")); mManualBtn->setChecked(false); proxysettings->set(PROXY_MODE_KEY,"auto"); } else if (eBtn == mManualBtn){ UkccCommon::buriedSettings(QString("Proxy"), QString("manual"), QString("clicked")); mAutoBtn->setChecked(false); proxysettings->set(PROXY_MODE_KEY,"manual"); } _setSensitivity(); }); connect(mUrlLineEdit, &QLineEdit::textChanged, this, [=](const QString &txt){proxysettings->set(PROXY_AUTOCONFIG_URL_KEY, QVariant(txt));}); connect(mHTTPLineEdit_1, &QLineEdit::textChanged, this, [=](const QString &txt){manualProxyTextChanged(txt);}); connect(mHTTPSLineEdit_1, &QLineEdit::textChanged, this, [=](const QString &txt){manualProxyTextChanged(txt);}); connect(mFTPLineEdit_1, &QLineEdit::textChanged, this, [=](const QString &txt){manualProxyTextChanged(txt);}); connect(mSOCKSLineEdit_1, &QLineEdit::textChanged, this, [=](const QString &txt){manualProxyTextChanged(txt);}); connect(mHTTPLineEdit_2, &QLineEdit::textChanged, this, [=](const QString &txt){manualProxyTextChanged(txt);}); connect(mHTTPSLineEdit_2, &QLineEdit::textChanged, this, [=](const QString &txt){manualProxyTextChanged(txt);}); connect(mFTPLineEdit_2, &QLineEdit::textChanged, this, [=](const QString &txt){manualProxyTextChanged(txt);}); connect(mSOCKSLineEdit_2, &QLineEdit::textChanged, this, [=](const QString &txt){manualProxyTextChanged(txt);}); connect(mIgnoreLineEdit, &QTextEdit::textChanged, this, [=](){ QString text = mIgnoreLineEdit->toPlainText(); QStringList hostStringList = text.split(";"); proxysettings->set(IGNORE_HOSTS_KEY, QVariant(hostStringList)); }); connect(mAptBtn , &KSwitchButton::stateChanged, this ,[=](bool checked){ UkccCommon::buriedSettings(QString("Proxy"), QString("Apt Proxy Open"), QString("settings"), checked?"true":"false"); if (checked) { emit mEditBtn->click(); } else { // 关闭APT代理,删除对应的配置文件 if (QString(qgetenv("http_proxy").data()).isEmpty()) { line_7->hide(); mAPTFrame_2->hide(); setAptProxy("" ,0 ,false); } else { QMessageBox *mReboot = new QMessageBox(pluginWidget->topLevelWidget()); mReboot->setIcon(QMessageBox::Warning); mReboot->setText(tr("The APT proxy has been turned off and needs to be restarted to take effect")); QPushButton *laterbtn = mReboot->addButton(tr("Reboot Later"), QMessageBox::RejectRole); QPushButton *nowbtn = mReboot->addButton(tr("Reboot Now"), QMessageBox::AcceptRole); mReboot->exec(); if (mReboot->clickedButton() == nowbtn) { //选择了立即重启,一秒后系统会重启 line_7->hide(); mAPTFrame_2->hide(); setAptProxy("" ,0 ,false); sleep(1); reboot(); } else { //选择了稍后重启,删掉对应文件,但删不了已生效的环境变量 line_7->hide(); mAPTFrame_2->hide(); setAptProxy("" ,0 ,false); } } } }); } void Proxy::initProxyModeStatus(){ int mode = _getCurrentProxyMode(); QHash mAptinfo = getAptProxy(); mAutoBtn->blockSignals(true); mManualBtn->blockSignals(true); mAptBtn->blockSignals(true); mEnableBtn->blockSignals(true); if (mode == AUTO){ mEnableBtn->setChecked(true); mAutoBtn->setChecked(true); } else if (mode == MANUAL){ mEnableBtn->setChecked(true); mManualBtn->setChecked(true); } else{ mEnableBtn->setChecked(false); mAutoBtn->setChecked(false); mManualBtn->setChecked(false); mSelectFrame->setVisible(false); line_8->setVisible(false); } if (QFile::exists("/etc/apt/ota_version")) { mAPTFrame->hide(); mAptProxyLabel->hide(); } else { if (mAptinfo["open"].toBool()) { mAptBtn->setChecked(true); mAPTHostLabel_2->setText(mAptinfo["ip"].toString()); mAPTPortLabel_2->setText(mAptinfo["port"].toString()); } else { mAptBtn->setChecked(false); line_7->setVisible(false); mAPTFrame_2->setVisible(false); } } mAutoBtn->blockSignals(false); mManualBtn->blockSignals(false); mAptBtn->blockSignals(false); mEnableBtn->blockSignals(false); _setSensitivity(); } void Proxy::initAutoProxyStatus(){ mUrlLineEdit->blockSignals(true); //设置当前url QString urlString = proxysettings->get(PROXY_AUTOCONFIG_URL_KEY).toString(); mUrlLineEdit->setText(urlString); mUrlLineEdit->blockSignals(false); } void Proxy::initManualProxyStatus(){ //信号阻塞 mHTTPLineEdit_1->blockSignals(true); mHTTPSLineEdit_1->blockSignals(true); mFTPLineEdit_1->blockSignals(true); mSOCKSLineEdit_1->blockSignals(true); mHTTPLineEdit_2->blockSignals(true); mHTTPSLineEdit_2->blockSignals(true); mFTPLineEdit_2->blockSignals(true); mSOCKSLineEdit_2->blockSignals(true); //HTTP QString httphost = httpsettings->get(PROXY_HOST_KEY).toString(); mHTTPLineEdit_1->setText(httphost); int httpport = httpsettings->get(PROXY_PORT_KEY).toInt(); mHTTPLineEdit_2->setText(QString::number(httpport)); //HTTPS QString httpshost = securesettings->get(PROXY_HOST_KEY).toString(); mHTTPSLineEdit_1->setText(httpshost); int httpsport = securesettings->get(PROXY_PORT_KEY).toInt(); mHTTPSLineEdit_2->setText(QString::number(httpsport)); //FTP QString ftphost = ftpsettings->get(PROXY_HOST_KEY).toString(); mFTPLineEdit_1->setText(ftphost); int ftppost = ftpsettings->get(PROXY_PORT_KEY).toInt(); mFTPLineEdit_2->setText(QString::number(ftppost)); //SOCKS QString sockshost = sockssettings->get(PROXY_HOST_KEY).toString(); mSOCKSLineEdit_1->setText(sockshost); int socksport = sockssettings->get(PROXY_PORT_KEY).toInt(); mSOCKSLineEdit_2->setText(QString::number(socksport)); //解除信号阻塞 mHTTPLineEdit_1->blockSignals(false); mHTTPSLineEdit_1->blockSignals(false); mFTPLineEdit_1->blockSignals(false); mSOCKSLineEdit_1->blockSignals(false); mHTTPLineEdit_2->blockSignals(false); mHTTPSLineEdit_2->blockSignals(false); mFTPLineEdit_2->blockSignals(false); mSOCKSLineEdit_2->blockSignals(false); } void Proxy::initIgnoreHostStatus(){ mIgnoreLineEdit->blockSignals(true); //设置当前ignore host QStringList ignorehost = proxysettings->get(IGNORE_HOSTS_KEY).toStringList(); mIgnoreLineEdit->setPlainText(ignorehost.join(";")); mIgnoreLineEdit->blockSignals(false); } void Proxy::initDbus() { m_appProxyDbus = new QDBusInterface("org.ukui.SettingsDaemon", "/org/ukui/SettingsDaemon/AppProxy", "org.ukui.SettingsDaemon.AppProxy", QDBusConnection::sessionBus()); if(!m_appProxyDbus->isValid()) { qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } } void Proxy::initAppProxyStatus() { bool state = getAppProxyState(); appProxyInfoPadding(); appListPadding(); m_appEnableBtn->setChecked(state); setAppProxyUiEnable(state); } int Proxy::_getCurrentProxyMode(){ GSettings * proxygsettings; proxygsettings = g_settings_new(PROXY_SCHEMA); int mode = g_settings_get_enum(proxygsettings, PROXY_MODE_KEY); g_object_unref(proxygsettings); return mode; } void Proxy::_setSensitivity(){ //自动配置代理界面敏感性 bool autoChecked = mAutoBtn->isChecked(); mUrlFrame->setVisible(autoChecked); line_1->setVisible(autoChecked); //手动配置代理界面敏感性 bool manualChecked = mManualBtn->isChecked(); mHTTPFrame->setVisible(manualChecked); mHTTPSFrame->setVisible(manualChecked); mFTPFrame->setVisible(manualChecked); mSOCKSFrame->setVisible(manualChecked); mIgnoreFrame->setVisible(manualChecked); line_2->setVisible(manualChecked); line_3->setVisible(manualChecked); line_4->setVisible(manualChecked); line_5->setVisible(manualChecked); line_6->setVisible(manualChecked); } void Proxy::setAptProxy(QString host, QString port, bool status) { QDBusInterface *mAptproxyDbus = new QDBusInterface("com.control.center.qt.systemdbus", "/", "com.control.center.interface", QDBusConnection::systemBus()); if (mAptproxyDbus->isValid()) { QDBusReply reply = mAptproxyDbus->call("setaptproxy", host, port , status); } delete mAptproxyDbus; mAptproxyDbus = nullptr; } QHash Proxy::getAptProxy() { QHash mAptInfo; QDBusInterface *mAptproxyDbus = new QDBusInterface("com.control.center.qt.systemdbus", "/", "com.control.center.interface", QDBusConnection::systemBus()); if (mAptproxyDbus->isValid()) { QDBusMessage result = mAptproxyDbus->call("getaptproxy"); QList outArgs = result.arguments(); QVariant first = outArgs.at(0); QDBusArgument dbvFirst = first.value(); QVariant vFirst = dbvFirst.asVariant(); const QDBusArgument &dbusArgs = vFirst.value(); QVector aptinfo; dbusArgs.beginArray(); while (!dbusArgs.atEnd()) { AptInfo info; dbusArgs >> info; aptinfo.push_back(info); } dbusArgs.endArray(); for (AptInfo it : aptinfo) { mAptInfo.insert(it.arg, it.out.variant()); } } delete mAptproxyDbus; mAptproxyDbus = nullptr; return mAptInfo; } void Proxy::setAptInfo() { QMessageBox *mReboot = new QMessageBox(pluginWidget->topLevelWidget()); mReboot->setIcon(QMessageBox::Warning); mReboot->setText(tr("The system needs to be restarted to set the APT proxy, whether to reboot")); QPushButton *laterbtn = mReboot->addButton(tr("Reboot Later"), QMessageBox::RejectRole); QPushButton *nowbtn = mReboot->addButton(tr("Reboot Now"), QMessageBox::AcceptRole); mReboot->exec(); if (mReboot->clickedButton() == nowbtn) { //选择了立即重启,一秒后系统会重启 sleep(1); reboot(); } else { //选择了稍后重启或点击了关闭按钮,配置文件已写入,但是/etc/profile.d目录下新增的脚本文件未执行 line_7->show(); mAPTFrame_2->show(); mAPTHostLabel_2->setText(getAptProxy()["ip"].toString()); mAPTPortLabel_2->setText(getAptProxy()["port"].toString()); } } void Proxy::reboot() { QDBusInterface *rebootDbus = new QDBusInterface("org.gnome.SessionManager", "/org/gnome/SessionManager", "org.gnome.SessionManager", QDBusConnection::sessionBus()); if (rebootDbus->isValid()) { rebootDbus->call("reboot"); } delete rebootDbus; rebootDbus = nullptr; } void Proxy::setFrame_Noframe(QFrame *frame) { frame->setMinimumSize(QSize(550, 60)); frame->setMaximumSize(QSize(16777215, 60)); frame->setFrameShape(QFrame::NoFrame); } QFrame *Proxy::setLine(QFrame *frame) { QFrame *line = new QFrame(frame); line->setMinimumSize(QSize(0, 1)); line->setMaximumSize(QSize(16777215, 1)); line->setLineWidth(0); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); return line; } bool Proxy::getAppProxyState() { bool state = true; if(m_appProxyDbus == nullptr || !m_appProxyDbus->isValid()) { qWarning ()<< "init AppProxy dbus error"; return false; } //获取应用代理开启状态 qDebug() << "call QDBusInterface getProxyStateDbus"; QDBusReply reply = m_appProxyDbus->call("getProxyStateDbus"); if (!reply.isValid()) { return false; } state = reply; return state; } void Proxy::setAppProxyState(bool state) { if(m_appProxyDbus == nullptr || !m_appProxyDbus->isValid()) { qWarning ()<< "init AppProxy dbus error"; return; } //设置应用代理开启状态 qDebug() << "call QDBusInterface setProxyStateDbus" << state; m_appProxyDbus->call("setProxyStateDbus", state); } QStringList Proxy::getAppProxyConf() { QStringList info; info.clear(); QDBusInterface dbusInterface("org.ukui.SettingsDaemon", "/org/ukui/SettingsDaemon/AppProxy", "org.ukui.SettingsDaemon.AppProxy", QDBusConnection::sessionBus()); if(!dbusInterface.isValid()) { qWarning ()<< "init AppProxy dbus error"; return info; } //获取应用代理配置信息 qDebug() << "call QDBusInterface getProxyConfig"; QDBusReply reply = dbusInterface.call("getProxyConfig"); if (!reply.isValid()) { qWarning ()<< "Return empty app proxy information, getProxyConfig reply is invalid"; return info; } info = reply.value(); if (info.isEmpty()) { qWarning() << "getAppProxyConf reply is empty"; } return info; } void Proxy::setAppProxyConf(QStringList list) { //AppProxyConf 必填项数量为3 if (list.count() < 3) { return; } if(m_appProxyDbus == nullptr || !m_appProxyDbus->isValid()) { qWarning ()<< "init AppProxy dbus error"; return; } //写入应用代理配置信息 qDebug() << "call QDBusInterface setProxyConfig"; m_appProxyDbus->call("setProxyConfig", list); } QMap Proxy::getAppListProxy() { QMap appList; appList.clear(); QDBusInterface dbusInterface("org.ukui.SettingsDaemon", "/org/ukui/SettingsDaemon/AppProxy", "org.ukui.SettingsDaemon.AppProxy", QDBusConnection::sessionBus()); if(!dbusInterface.isValid()) { qWarning ()<< "init AppProxy dbus error"; return appList; } //获取可以配置应用代理的应用信息 qDebug() << "call QDBusInterface getAppProxy"; QDBusReply> reply = dbusInterface.call("getAppProxy"); if (!reply.isValid()) { qWarning ()<< "Return empty app list, getAppProxy reply is invalid"; return appList; } appList = reply.value(); if (appList.isEmpty()) { qWarning() << "getAppProxy reply appList is empty"; } return appList; } void Proxy::setUkccProxySettings() { setSystemProxyFrameHidden(false); // setAppProxyFrameHidden(false); setAPTProxyFrameHidden(false); QDBusInterface ukccDbusInterface("org.ukui.ukcc.session", "/", "org.ukui.ukcc.session.interface", QDBusConnection::sessionBus()); if(!ukccDbusInterface.isValid()) { qWarning() << "ukccDbusInterface is invalid"; return; } QDBusReply > reply = ukccDbusInterface.call("getModuleHideStatus"); if (!reply.isValid()) { qWarning() << "reply of getModuleHideStatus is invalid"; return; } QStringList proxySettingList; if (reply.value().contains("proxySettings")) { QString proxySettings = reply.value()["proxySettings"].toString(); qDebug() << "proxySettings" << proxySettings; if (proxySettings.isEmpty()) { return; } proxySettingList = proxySettings.split(","); } for (const QString setting : proxySettingList) { if (setting.contains("SystemProxyFrame") && setting.contains("false")) { setSystemProxyFrameHidden(true); } else if (setting.contains("AppProxyFrame") && setting.contains("false")) { // setAppProxyFrameHidden(true); } else if (setting.contains("APTProxyFrame") && setting.contains("false")) { setAPTProxyFrameHidden(true); } } } #if 0 bool Proxy::checkIsChanged(QStringList info) { bool isChanged = false; info = getAppProxyConf(); if (info.value(0) != m_proxyTypeComboBox->currentText() || info.value(1) != m_ipAddressLineEdit->text() || info.value(2) != m_portLineEdit->text() || info.value(3) != m_userNameLineEdit->text() || info.value(4) != m_pwdLineEdit->text()) { isChanged = true; //如果在代理界面相关信息已修改,则返回true } return isChanged; } #endif void Proxy::setAppProxyFrameUi(QWidget *widget) { //应用代理模块 m_appProxyFrame = new QFrame(widget); m_appProxyFrame->setMinimumSize(QSize(550, 0)); m_appProxyFrame->setMaximumSize(QSize(16777215, 16777215)); m_appProxyFrame->setFrameShape(QFrame::Box); QVBoxLayout *appProxyLayout = new QVBoxLayout(m_appProxyFrame); appProxyLayout->setContentsMargins(0, 0, 0, 0); appProxyLayout->setSpacing(0); //开启ui布局 m_appEnableFrame = new QFrame(m_appProxyFrame); setFrame_Noframe(m_appEnableFrame); m_appEnableLabel = new QLabel(tr("Open"), m_appEnableFrame); m_appEnableBtn = new KSwitchButton(m_appEnableFrame); m_appEnableBtn->setCheckable(true); QHBoxLayout *appEnableLayout = new QHBoxLayout(m_appEnableFrame); appEnableLayout->setContentsMargins(FRAME_LAYOUT_MARGINS); appEnableLayout->addWidget(m_appEnableLabel); appEnableLayout->addStretch(); appEnableLayout->addWidget(m_appEnableBtn); //代理类型ui布局 m_proxyTypeFrame = new QFrame(m_appProxyFrame); setFrame_Noframe(m_proxyTypeFrame); m_proxyTypeLabel = new QLabel(tr("Proxy type"), m_proxyTypeFrame); m_proxyTypeLabel->setFixedWidth(LABEL_WIDTH); m_proxyTypeComboBox = new QComboBox(m_proxyTypeFrame); QHBoxLayout *proxyTypeLayout = new QHBoxLayout(m_proxyTypeFrame); proxyTypeLayout->setContentsMargins(FRAME_LAYOUT_MARGINS); proxyTypeLayout->setSpacing(FRAME_LAYOUT_SPACING); proxyTypeLayout->addWidget(m_proxyTypeLabel); proxyTypeLayout->addWidget(m_proxyTypeComboBox); m_proxyTypeComboBox->addItem("http"); //http m_proxyTypeComboBox->addItem("socks4"); //socks4 m_proxyTypeComboBox->addItem("socks5"); //socks4 //IP地址ui布局 m_ipAddressFrame = new QFrame(m_appProxyFrame); m_ipAddressFrame->setMinimumSize(QSize(550, 60)); m_ipAddressFrame->setMaximumSize(QSize(16777215, 88)); m_ipAddressFrame->setFrameShape(QFrame::NoFrame); m_ipAddressLabel = new QLabel(tr("IP address"), m_ipAddressFrame); m_ipAddressLabel->setFixedWidth(LABEL_WIDTH); m_ipHintsLabel = new QLabel(m_ipAddressFrame); m_ipHintsLabel->setContentsMargins(8, 0, 0, 0); m_ipAddressLineEdit = new QLineEdit(m_ipAddressFrame); m_ipAddressLineEdit->setFixedHeight(LINE_EDIT_HEIGHT); m_ipAddressLineEdit->setPlaceholderText(tr("Required")); //必填 QWidget *ipInputWidget = new QWidget(m_ipAddressFrame); QVBoxLayout *ipVLayout = new QVBoxLayout(ipInputWidget); ipVLayout->setContentsMargins(0, 0, 0, 0); ipVLayout->setSpacing(3); ipVLayout->addWidget(m_ipAddressLineEdit); ipVLayout->addWidget(m_ipHintsLabel); QFormLayout *ipAddressLayout = new QFormLayout(m_ipAddressFrame); ipAddressLayout->setContentsMargins(16, 12, 16, 12); ipAddressLayout->setSpacing(FRAME_LAYOUT_SPACING); ipAddressLayout->addRow(m_ipAddressLabel, ipInputWidget); // IP的正则格式限制 QRegularExpression rx("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); m_ipAddressLineEdit->setValidator(new QRegularExpressionValidator(rx, this)); //无效的IP地址提示 QPalette hintTextColor; hintTextColor.setColor(QPalette::WindowText, Qt::red); m_ipHintsLabel->setPalette(hintTextColor); m_ipHintsLabel->setText(tr("Invalid IP Address")); m_ipHintsLabel->hide(); //端口ui布局 m_portFrame = new QFrame(m_appProxyFrame); setFrame_Noframe(m_portFrame); m_portLabel = new QLabel(tr("Port"), m_portFrame); m_portLabel->setFixedWidth(LABEL_WIDTH); m_portLineEdit = new QLineEdit(m_portFrame); m_portLineEdit->setPlaceholderText(tr("Required")); //必填 m_portLineEdit->setValidator(new QRegularExpressionValidator(QRegularExpression("[0-9]*") , this)); QHBoxLayout *portLayout = new QHBoxLayout(m_portFrame); portLayout->setContentsMargins(FRAME_LAYOUT_MARGINS); portLayout->setSpacing(FRAME_LAYOUT_SPACING); portLayout->addWidget(m_portLabel); portLayout->addWidget(m_portLineEdit); //用户名ui布局 m_userNameFrame = new QFrame(m_appProxyFrame); setFrame_Noframe(m_userNameFrame); m_userNameLabel = new QLabel(tr("Username"), m_userNameFrame); m_userNameLabel->setFixedWidth(LABEL_WIDTH); m_userNameLineEdit = new QLineEdit(m_userNameFrame); m_userNameLineEdit->setPlaceholderText(tr("Optional")); //选填 QHBoxLayout *userNameLayout = new QHBoxLayout(m_userNameFrame); userNameLayout->setContentsMargins(FRAME_LAYOUT_MARGINS); userNameLayout->setSpacing(FRAME_LAYOUT_SPACING); userNameLayout->addWidget(m_userNameLabel); userNameLayout->addWidget(m_userNameLineEdit); //密码ui布局 m_pwdFrame = new QFrame(m_appProxyFrame); setFrame_Noframe(m_pwdFrame); m_pwdLabel = new QLabel(tr("Password"), m_pwdFrame); m_pwdLabel->setFixedWidth(LABEL_WIDTH); m_pwdLineEdit = new KPasswordEdit(m_pwdFrame); m_pwdLineEdit->setClearButtonEnabled(false); QString str = tr("Optional"); m_pwdLineEdit->setPlaceholderText(str); //选填 QHBoxLayout *pwdLayout = new QHBoxLayout(m_pwdFrame); pwdLayout->setContentsMargins(FRAME_LAYOUT_MARGINS); pwdLayout->setSpacing(FRAME_LAYOUT_SPACING); pwdLayout->addWidget(m_pwdLabel); pwdLayout->addWidget(m_pwdLineEdit); QRegularExpression rxPwd("^[A-Za-z0-9`~!@#$%^&*()_-+=<>,.\\\/]+$"); QRegularExpressionValidator *latitude = new QRegularExpressionValidator(rxPwd, this); m_pwdLineEdit->setValidator(latitude); #if 0 //按钮ui布局 m_appBtnFrame = new QFrame(m_appProxyFrame); setFrame_Noframe(m_appBtnFrame); m_cancelBtn = new QPushButton(m_appBtnFrame); m_saveBtn = new QPushButton(m_appBtnFrame); m_cancelBtn->setText(tr("Cancel")); m_saveBtn->setText(tr("Save")); QHBoxLayout *btnLayout = new QHBoxLayout(m_appBtnFrame); btnLayout->setContentsMargins(FRAME_LAYOUT_MARGINS); btnLayout->setSpacing(16); btnLayout->addStretch(); btnLayout->addWidget(m_cancelBtn); btnLayout->addWidget(m_saveBtn); #endif //分隔线 m_appLine1 = setLine(m_appProxyFrame); m_appLine2 = setLine(m_appProxyFrame); m_appLine3 = setLine(m_appProxyFrame); m_appLine4 = setLine(m_appProxyFrame); m_appLine5 = setLine(m_appProxyFrame); m_appProxyInfoWidget = new QWidget(m_appProxyFrame); QVBoxLayout *widgetHLayout = new QVBoxLayout(m_appProxyInfoWidget); widgetHLayout->setContentsMargins(0, 0, 0, 0); widgetHLayout->setSpacing(0); widgetHLayout->addWidget(m_appLine1); widgetHLayout->addWidget(m_proxyTypeFrame); widgetHLayout->addWidget(m_appLine2); widgetHLayout->addWidget(m_ipAddressFrame); widgetHLayout->addWidget(m_appLine3); widgetHLayout->addWidget(m_portFrame); widgetHLayout->addWidget(m_appLine4); widgetHLayout->addWidget(m_userNameFrame); widgetHLayout->addWidget(m_appLine5); widgetHLayout->addWidget(m_pwdFrame); appProxyLayout->addWidget(m_appEnableFrame); appProxyLayout->addWidget(m_appProxyInfoWidget); // appProxyLayout->addWidget(line5); // appProxyLayout->addWidget(m_appBtnFrame); connect(m_appEnableBtn, &KSwitchButton::stateChanged, this, &Proxy::setAppProxyUiEnable); connect(m_appEnableBtn, &KSwitchButton::stateChanged, this, &Proxy::setAppProxyState); connect(m_appEnableBtn, &KSwitchButton::stateChanged, [=](bool checked) { UkccCommon::buriedSettings(QString("Proxy"), QString("App Proxy Open"), QString("settings"), checked?"true":"false"); }); connect(m_proxyTypeComboBox, SIGNAL(currentTextChanged(QString)), this, SLOT(onAppProxyConfChanged())); connect(m_ipAddressLineEdit, SIGNAL(textChanged(QString)), this, SLOT(onipEditStateChanged())); connect(m_ipAddressLineEdit, SIGNAL(textChanged(QString)), this, SLOT(onAppProxyConfChanged())); connect(m_portLineEdit, SIGNAL(textChanged(QString)), this, SLOT(onAppProxyConfChanged())); connect(m_userNameLineEdit, SIGNAL(textChanged(QString)), this, SLOT(onAppProxyConfChanged())); connect(m_pwdLineEdit, SIGNAL(textChanged(QString)), this, SLOT(onAppProxyConfChanged())); connect(m_ipAddressLineEdit, SIGNAL(textChanged(QString)), this, SLOT(onAppProxyConfChanged())); connect(m_proxyTypeComboBox, SIGNAL(currentTextChanged(QString)), this, SLOT(onAppProxyConfEditFinished())); connect(m_ipAddressLineEdit, SIGNAL(editingFinished()), this, SLOT(onAppProxyConfEditFinished())); connect(m_portLineEdit, SIGNAL(editingFinished()), this, SLOT(onAppProxyConfEditFinished())); connect(m_userNameLineEdit, SIGNAL(editingFinished()), this, SLOT(onAppProxyConfEditFinished())); connect(m_pwdLineEdit, SIGNAL(editingFinished()), this, SLOT(onAppProxyConfEditFinished())); // connect(m_cancelBtn, SIGNAL(clicked()), this, SLOT(onCancelBtnClicked())); // connect(m_saveBtn, SIGNAL(clicked()), this, SLOT(onSaveBtnClicked())); } void Proxy::setAppListFrameUi(QWidget *widget) { //应用列表 m_appListFrame = new QFrame(widget); m_appListFrame->setMinimumSize(QSize(550, 0)); m_appListFrame->setMaximumSize(QSize(16777215, 336)); m_appListFrame->setFrameShape(QFrame::Box); QVBoxLayout *appListLayout = new QVBoxLayout(m_appListFrame); appListLayout->setContentsMargins(16, 23, 16, 16); appListLayout->setSpacing(16); m_allowAppProxyLabel = new QLabel(m_appListFrame); m_allowAppProxyLabel->setText(tr("The following applications are allowed to use this configuration:")); //允许以下应用使用该配置: m_appListWidget = new QListWidget(m_appListFrame); m_appListWidget->setMinimumHeight(240); m_appListWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus); m_appListWidget->setFrameShape(QFrame::Shape::Panel); m_appListWidget->setVerticalScrollMode(QAbstractItemView::ScrollMode::ScrollPerPixel); appListLayout->addWidget(m_allowAppProxyLabel); appListLayout->addWidget(m_appListWidget); onPaletteChanged(); const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { QGSettings * styleGsettings = new QGSettings(style_id, QByteArray(), this); connect(styleGsettings, &QGSettings::changed, this, [=](QString key){ if ("styleName" == key) { onPaletteChanged(); } }); } } void Proxy::appProxyInfoPadding() { QStringList proxyInfo; proxyInfo.clear(); proxyInfo = getAppProxyConf(); m_proxyTypeComboBox->setCurrentText(proxyInfo.value(0)); m_ipAddressLineEdit->setText(proxyInfo.value(1)); m_portLineEdit->setText(proxyInfo.value(2)); m_userNameLineEdit->setText(proxyInfo.value(3)); m_pwdLineEdit->setText(proxyInfo.value(4)); } void Proxy::appListPadding() { QMap appList ; appList.clear(); appList = getAppListProxy(); //获取应用代理配置 //遍历应用列表 for (auto index : appList.keys()) { QStringList appInfo = appList.value(index); QVariant isChecked = appInfo.value(2); bool flag = isChecked.toBool(); AppListWidget *appWidget = new AppListWidget(index, m_appListWidget); appWidget->setAppName(appInfo.value(0)); appWidget->setAppIcon(QIcon::fromTheme(appInfo.value(1))); appWidget->setAppChecked(flag); QListWidgetItem *appListWidgetItem = new QListWidgetItem(m_appListWidget); appListWidgetItem->setSizeHint(QSize(m_appListWidget->width(),36)); appListWidgetItem->setFlags(Qt::NoItemFlags); m_appListWidget->addItem(appListWidgetItem); m_appListWidget->setItemWidget(appListWidgetItem, appWidget); } } bool Proxy::getipEditState(QString text) { if (text.isEmpty()) { return true; } // IP地址正则表达式,包含开始和结束锚点确保完全匹配 QRegularExpression rx("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); // 进行匹配并返回结果 QRegularExpressionMatch match = rx.match(text); return match.hasMatch(); } void Proxy::setSystemProxyFrameHidden(bool state) { mTitleLabel->setHidden(state); mProxyFrame->setHidden(state); m_sysSpacerFrame->setHidden(state); } void Proxy::setAppProxyFrameHidden(bool state) { m_appProxyLabel->setHidden(state); m_appProxyFrame->setHidden(state); if (state) { m_appListFrame->setHidden(state); } else { m_appListFrame->setHidden(!m_appEnableBtn->isChecked()); } m_appListSpacerFrame->setHidden(state); m_appSpacerFrame->setHidden(state); } void Proxy::setAPTProxyFrameHidden(bool state) { mAptProxyLabel->setHidden(state); mAPTFrame->setHidden(state); } void Proxy::onipEditStateChanged() { if (!getipEditState(m_ipAddressLineEdit->text())) { m_ipAddressFrame->setFixedHeight(88); m_ipHintsLabel->show(); } else { m_ipHintsLabel->hide(); m_ipAddressFrame->setFixedHeight(60); } } void Proxy::onAppProxyConfChanged() { if (!getipEditState(m_ipAddressLineEdit->text()) || m_portLineEdit->text().isEmpty()) { return; } if (m_ipAddressLineEdit->text().isEmpty()) { return; } else { m_appProxyInfo.clear(); m_appProxyInfo.append(m_proxyTypeComboBox->currentText()); m_appProxyInfo.append(m_ipAddressLineEdit->text()); m_appProxyInfo.append(m_portLineEdit->text()); if (!m_userNameLineEdit->text().isEmpty() && !m_pwdLineEdit->text().isEmpty()) { m_appProxyInfo.append(m_userNameLineEdit->text()); m_appProxyInfo.append(m_pwdLineEdit->text()); } else { m_appProxyInfo.append(""); m_appProxyInfo.append(""); } } } void Proxy::onAppProxyConfEditFinished() { if (!m_ipAddressLineEdit->hasFocus() && !m_portLineEdit->hasFocus()) { setAppProxyConf(m_appProxyInfo); } } void Proxy::onPaletteChanged() { QPalette mpal(m_appListWidget->palette()); mpal.setColor(QPalette::Base, qApp->palette().base().color()); mpal.setColor(QPalette::AlternateBase, qApp->palette().alternateBase().color()); m_appListWidget->setBackgroundRole(QPalette::Base); m_appListWidget->setAlternatingRowColors(true); m_appListWidget->setPalette(mpal); } void Proxy::setAppProxyUiEnable(bool enable) { if (enable) { m_appProxyInfoWidget->show(); m_appListFrame->show(); } else { m_appProxyInfoWidget->hide(); m_appListFrame->hide(); } } #if 0 void Proxy::onCancelBtnClicked() { appProxyInfoPadding(); } void Proxy::onSaveBtnClicked() { if (!checkIsChanged(m_appProxyInfo)) { return; } else { QStringList conf; conf.clear(); conf.append(m_proxyTypeComboBox->currentText()); conf.append(m_ipAddressLineEdit->text()); conf.append(m_portLineEdit->text()); conf.append(m_userNameLineEdit->text()); conf.append(m_pwdLineEdit->text()); setAppProxyConf(conf); } } void Proxy::setBtnEnable() { m_cancelBtn->setEnabled(true); if (getipEditState(m_ipAddressLineEdit->text()) && !m_portLineEdit->text().isEmpty()) { if (!m_ipAddressLineEdit->text().isEmpty()) { m_saveBtn->setEnabled(true); } } else { m_saveBtn->setEnabled(false); } } #endif void Proxy::setAptProxySlot() { mAptBtn->blockSignals(true); QHash preaptinfo = getAptProxy(); bool prestatus = preaptinfo["open"].toBool(); AptProxyDialog *mwindow = new AptProxyDialog(pluginWidget); mwindow->exec(); if (getAptProxy()["open"].toBool() && !prestatus) { // open值为true,用户点击了确定按钮,进行配置文件的写入,提示用户重启系统 setAptInfo(); } if (getAptProxy()["open"].toBool() && prestatus) { if (getAptProxy()["ip"].toString() == preaptinfo["ip"].toString() && getAptProxy()["port"].toString() == preaptinfo["port"].toString() && prestatus){ //点击了编辑按钮,且在设置IP和端口号的弹窗中,点击了取消或者关闭按钮 line_7->show(); mAPTFrame_2->show(); } else { setAptInfo(); } } if(!getAptProxy()["open"].toBool() && !prestatus){ // 点击了APT开关按钮,但是在设置IP和端口号的弹窗中,点击了取消或者关闭按钮 mAptBtn->setChecked(false); } mAptBtn->blockSignals(false); } void Proxy::manualProxyTextChanged(QString txt){ //获取被修改控件 QObject * pobject = this->sender(); QLineEdit * who = dynamic_cast(pobject); //获取控件保存的用户数据 GSData currentData = who->property("gData").value(); QString schema = currentData.schema; qDebug()<set(key, QVariant(txt)); delete setting; setting = nullptr; } kylin-nm/plugins/proxy/applistwidget.cpp0000664000175000017500000001020015167646234017473 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "applistwidget.h" #include AppListWidget::AppListWidget(QString path, QWidget *parent) : m_path(path), QWidget(parent) { initUI(); initDbus(); } AppListWidget::~AppListWidget() { delete m_dbusInterface; } /** * @brief AppListWidget::setAppChecked * @param flag 是否使用应用代理配置 */ void AppListWidget::setAppChecked(bool flag) { m_checkBox->setChecked(flag); } /** * @brief AppListWidget::setAppIcon * @param icon 应用图标 */ void AppListWidget::setAppIcon(const QIcon &icon) { m_iconBtn->setIcon(icon); } /** * @brief AppListWidget::setAppName * @param text 应用名称 */ void AppListWidget::setAppName(const QString &text) { m_nameLabel->setText(text); } /** * @brief AppListWidget::onAppCheckStateChanged * checkBox是否选中 关联是否配置应用代理 */ void AppListWidget::onAppCheckStateChanged() { if (m_checkBox->isChecked()) { AddAppProxyConfig(); } else { RemoveAppProxyConfig(); } } /** * @brief AppListWidget::AddAppProxyConfig * 将该路径下的应用加入应用代理 */ void AppListWidget::AddAppProxyConfig() { if(m_dbusInterface == nullptr || !m_dbusInterface->isValid()) { qWarning ()<< "init AppProxy dbus error"; return; } qDebug() << "call QDBusInterface addAppIntoProxy"; m_dbusInterface->call("addAppIntoProxy", m_path); } /** * @brief AppListWidget::RemoveAppProxyConfig * 将该路径下的应用移出应用代理 */ void AppListWidget::RemoveAppProxyConfig() { if(m_dbusInterface == nullptr || !m_dbusInterface->isValid()) { qWarning ()<< "init AppProxy dbus error"; return; } qDebug() << "call QDBusInterface delAppIntoProxy"; m_dbusInterface->call("delAppIntoProxy", m_path); } void AppListWidget::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { m_checkBox->setChecked(!m_checkBox->isChecked()); onAppCheckStateChanged(); } return QWidget::mousePressEvent(event); } void AppListWidget::initUI() { QHBoxLayout *mainLayout = new QHBoxLayout(this); mainLayout->setContentsMargins(17, 0, 17, 0); mainLayout->setSpacing(8); m_checkBox = new QCheckBox(this); m_checkBox->setAttribute(Qt::WA_TransparentForMouseEvents, true); //m_checkBox不响应鼠标事件,将其传递给父窗口 m_iconBtn = new QToolButton(this); m_iconBtn->setToolButtonStyle(Qt::ToolButtonStyle::ToolButtonIconOnly); m_iconBtn->setAttribute(Qt::WA_TranslucentBackground, true); //透明 m_iconBtn->setAttribute(Qt::WA_TransparentForMouseEvents, true); m_iconBtn->setAutoRaise(true); m_iconBtn->setFixedSize(24, 24); m_iconBtn->setIconSize(QSize(24, 24)); m_nameLabel = new QLabel(this); mainLayout->addWidget(m_checkBox); mainLayout->addWidget(m_iconBtn); mainLayout->addWidget(m_nameLabel); mainLayout->addStretch(); } void AppListWidget::initDbus() { m_dbusInterface = new QDBusInterface("org.ukui.SettingsDaemon", "/org/ukui/SettingsDaemon/AppProxy", "org.ukui.SettingsDaemon.AppProxy", QDBusConnection::sessionBus()); if(!m_dbusInterface->isValid()) { qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } } kylin-nm/plugins/plugin.pro0000664000175000017500000000015215167646234014753 0ustar fengfengTEMPLATE = subdirs SUBDIRS = \ netconnect \ wlanconnect \ mobilehotspot \ proxy \ vpn kylin-nm/plugins/vpn/0000775000175000017500000000000015167651420013531 5ustar fengfengkylin-nm/plugins/vpn/translations/0000775000175000017500000000000015167654227016262 5ustar fengfengkylin-nm/plugins/vpn/translations/de.ts0000664000175000017500000000536015167646234017225 0ustar fengfeng AddNetBtn Add Others Andere hinzufügen Add WiredNetork WiredNetork hinzufügen ItemFrame Add VPN VPN hinzufügen Vpn VPN import Show on Taskbar In der Taskleiste anzeigen /Vpn/Show on Taskbar Add VPN VPN hinzufügen /Vpn/Add VPN connected verbunden not connected nicht verbunden VpnItem Delete Löschen Disconnect Trennen Connect Verbinden kylin-nm/plugins/vpn/translations/ky.ts0000664000175000017500000000550715167646234017263 0ustar fengfeng AddNetBtn Add Others باشقانى قوشۇۇ Add WiredNetork سىمدۇۇ تور قوشۇۇ ItemFrame Add VPN VPN قوشۇۇ Vpn VPN import Show on Taskbar مىلدەت سابىندا شارتتۇۇ بەلگى كۅرسۅتۉۉ /Vpn/Show on Taskbar Add VPN VPN قوشۇۇ /Vpn/Add VPN connected جالعانعان not connected ۇلانباعان VpnItem Delete ۅچۉرۉۉ Disconnect ۉزۉپ اتۇۇ Connect ۇلانۇۇ kylin-nm/plugins/vpn/translations/zh_CN.ts0000664000175000017500000000527015167646234017636 0ustar fengfeng AddNetBtn Add Others Add WiredNetork ItemFrame Add VPN 添加VPN Vpn VPN import Show on Taskbar 在任务栏显示图标 /Vpn/Show on Taskbar Add VPN 添加 VPN 连接 /Vpn/Add VPN connected 已连接 not connected 未连接 VpnItem Delete 删除 Disconnect 断开 Connect 连接 kylin-nm/plugins/vpn/translations/kk.ts0000664000175000017500000000547615167646234017252 0ustar fengfeng AddNetBtn Add Others باسقانٸ قوسۋ Add WiredNetork سىمدى تور قوسۋ ItemFrame Add VPN VPN قوسۋ Vpn VPN import قوسۋ Show on Taskbar مىندەتتى قاتارىندا اي كۇن كورسەتۋ /Vpn/Show on Taskbar Add VPN VPN قوسۋ /Vpn/Add VPN connected جالعانعان not connected جالعانباعان VpnItem Delete ٴوشىرۋ Disconnect ۇزارتىۋ Connect جالعانۋ kylin-nm/plugins/vpn/translations/ms.ts0000664000175000017500000000535715167651420017253 0ustar fengfeng AddNetBtn Add Others Add WiredNetork ItemFrame Add VPN Vpn VPN import Show on Taskbar /Vpn/Show on Taskbar Add VPN /Vpn/Add VPN connected not connected VpnItem Delete Disconnect Connect kylin-nm/plugins/vpn/translations/tr.ts0000664000175000017500000000535715167646234017270 0ustar fengfeng AddNetBtn Add Others Add WiredNetork ItemFrame Add VPN Vpn VPN import Show on Taskbar /Vpn/Show on Taskbar Add VPN /Vpn/Add VPN connected not connected VpnItem Delete Disconnect Connect kylin-nm/plugins/vpn/translations/bo.ts0000664000175000017500000000535715167646234017243 0ustar fengfeng AddNetBtn Add Others Add WiredNetork ItemFrame Add VPN Vpn VPN import Show on Taskbar /Vpn/Show on Taskbar Add VPN /Vpn/Add VPN connected not connected VpnItem Delete Disconnect Connect kylin-nm/plugins/vpn/translations/ug.ts0000664000175000017500000000541215167646234017246 0ustar fengfeng AddNetBtn Add Others Add WiredNetork ItemFrame Add VPN VPN قوشۇش Vpn VPN import Show on Taskbar ۋەزىپە ستونىدا سىنبەلگە كۆرسىتىش /Vpn/Show on Taskbar Add VPN VPN قوشۇش /Vpn/Add VPN connected ئۇلانغان not connected ئۇلانمىغان VpnItem Delete ئۆچۈرۈش Disconnect ئۈزۈۋېتىش Connect ئۇلىنىش kylin-nm/plugins/vpn/translations/bo_CN.ts0000664000175000017500000000612115167646234017611 0ustar fengfeng AddNetBtn Add Others Add WiredNetork ItemFrame Add VPN ཁ་སྣོན་རྒྱག་པ།VPN Vpn VPN import Show on Taskbar ལས་འགན་གྱི་ངོས་སུ་དཔེ་རིས་གསལ་པོར་མངོན་པ། /Vpn/Show on Taskbar Add VPN ཁ་སྣོན་རྒྱག་པ།VPN /Vpn/Add VPN connected འབྲེལ་མཐུད་བྱུང་ཡོད། not connected འབྲེལ་མཐུད་མ་བྱས་པ། VpnItem Delete སུབ་དགོས། Disconnect བར་མཚམས་ཆད་པ་རེད། Connect འབྲེལ་མཐུད་བཅས་བྱ་དགོས། kylin-nm/plugins/vpn/translations/vi.ts0000664000175000017500000000537315167651420017250 0ustar fengfeng AddNetBtn Add Others Add WiredNetork ItemFrame Add VPN Thêm VPN Vpn VPN import Show on Taskbar Các biểu tượng được hiển thị trên thanh tác vụ /Vpn/Show on Taskbar Add VPN Thêm kết nối VPN /Vpn/Add VPN connected Kết nối not connected Không kết nối VpnItem Delete Xóa Disconnect Ngắt kết nối Connect kết nối kylin-nm/plugins/vpn/translations/mn.ts0000664000175000017500000000604515167646234017250 0ustar fengfeng AddNetBtn Add Others ᠪᠤᠰᠤᠳ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠵᠠᠯᠭᠠᠬᠤ Add WiredNetork ᠤᠲᠠᠰᠤᠲᠤ ᠨᠧᠲ ᠨᠡᠮᠡᠬᠦ ItemFrame Add VPN VPN ᠨᠡᠮᠡᠬᠦ Vpn VPN import Show on Taskbar ᠡᠬᠦᠷᠬᠡ ᠵᠢᠨ ᠪᠠᠭᠠᠷ ᠲᠤ᠌ ᠢᠺᠦᠨ ᠵᠢᠷᠤᠭ ᠢ᠋ ᠢᠯᠡᠷᠡᠬᠦᠯᠬᠦ /Vpn/Show on Taskbar Add VPN VPN ᠨᠡᠮᠡᠬᠦ /Vpn/Add VPN connected ᠴᠦᠷᠬᠡᠯᠡᠪᠡ not connected ᠴᠦᠷᠬᠡᠯᠡᠭᠡ ᠦᠬᠡᠢ VpnItem Delete ᠬᠠᠰᠤᠬᠤ Disconnect ᠳᠠᠰᠤᠯᠬᠤ Connect ᠴᠦᠷᠬᠡᠯᠡᠬᠦ kylin-nm/plugins/vpn/translations/zh_Hant.ts0000664000175000017500000000531515167646234020230 0ustar fengfeng AddNetBtn Add Others 添加其他 Add WiredNetork 添加有線網路 ItemFrame Add VPN 添加 VPN Vpn VPN import Show on Taskbar 在任務列顯示圖示 /Vpn/Show on Taskbar Add VPN 添加 VPN /Vpn/Add VPN connected 已連接 not connected 未連接 VpnItem Delete 刪除 Disconnect 斷開 Connect 連接 kylin-nm/plugins/vpn/translations/fr.ts0000664000175000017500000000536015167646234017244 0ustar fengfeng AddNetBtn Add Others Ajouter d’autres Add WiredNetork Ajouter WiredNetork ItemFrame Add VPN Ajouter un VPN Vpn VPN import Show on Taskbar Afficher dans la barre des tâches /Vpn/Show on Taskbar Add VPN Ajouter un VPN /Vpn/Add VPN connected relié not connected non connecté VpnItem Delete Supprimer Disconnect Déconnecter Connect Relier kylin-nm/plugins/vpn/translations/en_US.ts0000664000175000017500000000542515167646234017650 0ustar fengfeng AddNetBtn Add Others Add WiredNetork ItemFrame Add VPN Vpn VPN import Show on Taskbar /Vpn/Show on Taskbar Add VPN /Vpn/Add VPN connected not connected VpnItem Delete Disconnect Connect kylin-nm/plugins/vpn/translations/es.ts0000664000175000017500000000535115167646234017244 0ustar fengfeng AddNetBtn Add Others Agregar otros Add WiredNetork Añadir WiredNetork ItemFrame Add VPN Añadir VPN Vpn VPN import importación Show on Taskbar Mostrar en la barra de tareas /Vpn/Show on Taskbar Add VPN Añadir VPN /Vpn/Add VPN connected conexo not connected no conectado VpnItem Delete Borrar Disconnect Desconectar Connect Conectar kylin-nm/plugins/vpn/translations/zh_HK.ts0000664000175000017500000000531515167646234017640 0ustar fengfeng AddNetBtn Add Others 添加其他 Add WiredNetork 添加有線網路 ItemFrame Add VPN 添加 VPN Vpn VPN import Show on Taskbar 在任務列顯示圖示 /Vpn/Show on Taskbar Add VPN 添加 VPN /Vpn/Add VPN connected 已連接 not connected 未連接 VpnItem Delete 刪除 Disconnect 斷開 Connect 連接 kylin-nm/plugins/vpn/itemframe.cpp0000664000175000017500000000446315167651420016215 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "itemframe.h" #include #define LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_MARGINS 0,0,0,0 ItemFrame::ItemFrame(QWidget *parent) :QFrame(parent) { m_mainVLayout = new QVBoxLayout(this); m_mainVLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); m_vpnFrame = new QFrame(this); m_vpnFrame->setFrameShape(QFrame::Shape::NoFrame); m_vpnFrame->setContentsMargins(LAYOUT_MARGINS); m_vpnVLayout = new QVBoxLayout(this); m_vpnVLayout->setContentsMargins(LAYOUT_MARGINS); m_vpnVLayout->setSpacing(1); m_addVpnWidget = new AddNetBtn(false, this); m_addVpnWidget->setTextLabel(tr("Add VPN")); m_mainVLayout->setSpacing(1); setLayout(m_mainVLayout); m_vpnFrame->setLayout(m_vpnVLayout); m_mainVLayout->addWidget(m_vpnFrame); m_mainVLayout->addWidget(m_addVpnWidget); // 初始化圆角样式 updateCornerStyle(); } void ItemFrame::updateCornerStyle() { bool hasVpnItems = (m_vpnVLayout->count() > 0); if (hasVpnItems) { m_addVpnWidget->setCornerType(AddNetBtn::BottomRight); } else { m_addVpnWidget->setCornerType(AddNetBtn::All); } } void ItemFrame::filletStyleChange() { for (int i = 0; i < m_vpnVLayout->count(); ++i) { VpnItem *itemFrame = (VpnItem*)(m_vpnVLayout->itemAt(i)->widget()); if (i == 0) { itemFrame->setCornerType(VpnItem::Top); } else { itemFrame->setCornerType(VpnItem::None); } } } kylin-nm/plugins/vpn/vpn.h0000664000175000017500000000613015167646234014514 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef VPN_H #define VPN_H #include #include #include #include #include #include "interface.h" #include "addbtn.h" #include "imageutil.h" #include "kwidget.h" #include "kswitchbutton.h" #include "itemframe.h" #include "ukcccommon.h" using namespace kdk; using namespace ukcc; namespace Ui { class Vpn; } class Vpn : public QObject, CommonInterface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.ukcc.CommonInterface") Q_INTERFACES(CommonInterface) public: Vpn(); ~Vpn(); QString plugini18nName() Q_DECL_OVERRIDE; int pluginTypes() Q_DECL_OVERRIDE; QWidget * pluginUi() Q_DECL_OVERRIDE; const QString name() const Q_DECL_OVERRIDE; bool isShowOnHomePage() const Q_DECL_OVERRIDE; QIcon icon() const Q_DECL_OVERRIDE; bool isEnable() const Q_DECL_OVERRIDE; QString translationPath() const Q_DECL_OVERRIDE; public: void initComponent(); void initConnect(); void runExternalApp(); protected: // bool eventFilter(QObject *watched, QEvent *event); private: Ui::Vpn *ui; QString m_pluginName; int m_pluginType; QWidget * m_pluginWidget; QDBusInterface *m_interface = nullptr; QFrame *m_topFrame; QFrame *m_showFrame; QLabel *m_showLabel; KSwitchButton *m_showBtn; QFrame *m_Line; QFrame *m_timeFrame; QLabel *m_timeLabel; KSwitchButton *m_timeBtn; ItemFrame *m_listFrame; bool m_firstLoad; QGSettings *m_switchGsettings; QFrame* myLine(); int getInsertPos(QString connName); void deleteVpn(QString uuid); void activeConnect(QString uuid); void deActiveConnect(QString uuid); void showDetailPage(QString uuid); //获取设备列表 void initNet(); //增加一项 void addOneVirtualItem(QStringList infoList); //减少一项 void removeOneVirtualItem(QString uuid); //单个lan连接状态变化 void itemActiveConnectionStatusChanged(VpnItem *item, int status); void setShowSwitchStatus(); // 搜索词条 void initSearchText(); private slots: void onVpnAdd(QStringList); void onVpnRemove(QString); void onVpnUpdate(QStringList); void onVpnActiveConnectionStateChanged(QString, int); }; #endif // VPN_H kylin-nm/plugins/vpn/translate_generation.sh0000775000175000017500000000056615167651420020307 0ustar fengfeng#!/bin/bash export PATH="/usr/lib/qt6/bin:$PATH" ts_list=(`ls translations/*.ts`) source /etc/os-release version=(`echo $ID`) for ts in "${ts_list[@]}" do printf "\nprocess ${ts}\n" if [ "$version" == "fedora" ] || [ "$version" == "opensuse-leap" ] || [ "$version" == "opensuse-tumbleweed" ];then lrelease-qt5 "${ts}" else lrelease "${ts}" fi done kylin-nm/plugins/vpn/vpn.pro0000664000175000017500000000274215167651420015063 0ustar fengfeng#------------------------------------------------- # # Project created by QtCreator 2019-06-29T13:53:10 # #------------------------------------------------- QT += widgets dbus TEMPLATE = lib CONFIG += plugin \ c++11 \ link_pkgconfig include(../component/addbtn.pri) PKGCONFIG += gsettings-qt6 \ kysdk-applications \ TARGET = $$qtLibraryTarget(vpn) DESTDIR = ../.. target.path = $$[QT_INSTALL_LIBS]/ukui-control-center trans.files = translations/* trans.path = /usr/share/kylin-nm/vpn/ INCLUDEPATH += \ $$PROJECT_COMPONENTSOURCE \ $$PROJECT_ROOTDIR \ /usr/include/ukcc/interface \ /usr/include/ukcc/widgets LIBS += -L$$[QT_INSTALL_LIBS] -lukcc SOURCES += \ vpn.cpp \ itemframe.cpp \ vpnitem.cpp HEADERS += \ vpn.h \ itemframe.h \ vpnitem.h FORMS += \ vpn.ui INSTALLS += target \ trans TRANSLATIONS += \ translations/zh_Hant.ts \ translations/zh_HK.ts \ translations/zh_CN.ts \ translations/ug.ts \ translations/tr.ts \ translations/mn.ts \ translations/ky.ts \ translations/kk.ts \ translations/fr.ts \ translations/es.ts \ translations/en_US.ts \ translations/de.ts \ translations/bo.ts\ translations/bo_CN.ts CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } kylin-nm/plugins/vpn/vpnitem.cpp0000664000175000017500000001463615167651420015731 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "vpnitem.h" #include #include #include #include "klabel.h" #define FRAME_SPEED 150 #define LIMIT_TIME 60*1000 #define TOTAL_PAGE 8 #define RADIUS 6.0 #define THEME_QT_SCHEMA "org.ukui.style" #define MODE_QT_KEY "style-name" using namespace kdk; VpnItem::VpnItem(bool bAcitve, QWidget *parent) : m_isAcitve(bAcitve), QPushButton(parent) { this->setMinimumSize(550, 58); this->setProperty("useButtonPalette", true); this->setFlat(true); QHBoxLayout *mLanLyt = new QHBoxLayout(this); mLanLyt->setContentsMargins(16,0,16,0); mLanLyt->setSpacing(16); m_iconLabel = new QLabel(this); m_iconLabel->setProperty("useIconHighlightEffect", 0x2); m_titileLabel = new KLabel(this); m_statusLabel = new QLabel(this); m_statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_infoLabel = new GrayInfoButton(this); m_moreButton = new QPushButton(this); m_moreButton->setProperty("useButtonPalette", true); m_moreButton->setFlat(true); m_moreButton->setFixedSize(36, 36); m_moreButton->setIcon(QIcon::fromTheme("view-more-horizontal-symbolic")); m_moreMenu = new QMenu(m_moreButton); m_connectAction = new QAction(m_moreMenu); m_deleteAction = new QAction(tr("Delete"), m_moreMenu); setConnectActionText(m_isAcitve); m_moreMenu->addAction(m_connectAction); m_moreMenu->addAction(m_deleteAction); mLanLyt->addWidget(m_iconLabel); mLanLyt->addWidget(m_titileLabel,Qt::AlignLeft); mLanLyt->addStretch(); mLanLyt->addWidget(m_statusLabel); mLanLyt->addWidget(m_infoLabel); mLanLyt->addWidget(m_moreButton); m_loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); m_waitTimer = new QTimer(this); connect(m_waitTimer, &QTimer::timeout, this, &VpnItem::updateIcon); m_iconLabel->setAttribute(Qt::WA_TransparentForMouseEvents, true); m_titileLabel->setAttribute(Qt::WA_TransparentForMouseEvents, true); m_statusLabel->setAttribute(Qt::WA_TransparentForMouseEvents, true); connect(m_connectAction, &QAction::triggered, this, &VpnItem::onConnectTriggered); connect(m_deleteAction, &QAction::triggered, this, &VpnItem::onDeletetTriggered); connect(m_moreButton, &QPushButton::clicked, this, &VpnItem::onMoreButtonClicked); m_moreMenu->installEventFilter(this); } void VpnItem::updateIcon() { if (m_currentIconIndex > 6) { m_currentIconIndex = 0; } m_statusLabel->setPixmap(m_loadIcons.at(m_currentIconIndex).pixmap(16,16)); m_currentIconIndex ++; } void VpnItem::startLoading() { m_waitTimer->start(FRAME_SPEED); m_loading = true; } void VpnItem::stopLoading(){ m_waitTimer->stop(); m_loading = false; } void VpnItem::setConnectActionText(bool isAcitve) { if (isAcitve) { m_connectAction->setText(tr("Disconnect")); } else { m_connectAction->setText(tr("Connect")); } } void VpnItem::onConnectTriggered() { if (!m_connectAction) { return; } if (m_connectAction->text() == tr("Connect")) { Q_EMIT connectActionTriggered(); } else if (m_connectAction->text() == tr("Disconnect")) { Q_EMIT disconnectActionTriggered(); } } void VpnItem::onDeletetTriggered() { if (!m_deleteAction) { return; } Q_EMIT deleteActionTriggered(); } void VpnItem::onMoreButtonClicked() { if (!m_moreMenu || !m_moreButton) { return; } // 计算菜单显示位置,使菜单右边界与按钮右边界对齐 QPoint buttonPos = m_moreButton->mapToGlobal(QPoint(0, 0)); int menuWidth = m_moreMenu->sizeHint().width(); int buttonWidth = m_moreButton->width(); int buttonHeight = m_moreButton->height(); QPoint menuPos = QPoint(buttonPos.x() + buttonWidth - menuWidth, buttonPos.y() + buttonHeight); m_moreMenu->popup(menuPos); } void VpnItem::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); painter.setBrush(this->palette().base().color()); QPalette pal = qApp->palette(); QColor color = pal.color(QPalette::Button); color.setAlphaF(0.5); pal.setColor(QPalette::Button, color); this->setPalette(pal); QRect rect = this->rect(); QPainterPath path; const qreal radius = 8.0; if (m_cornerType == Top) { // 左上右上圆角 path.moveTo(rect.left() + radius, rect.top()); path.lineTo(rect.right() - radius, rect.top()); path.quadTo(rect.right(), rect.top(), rect.right(), rect.top() + radius); path.lineTo(rect.right(), rect.bottom()); path.lineTo(rect.left(), rect.bottom()); path.lineTo(rect.left(), rect.top() + radius); path.quadTo(rect.left(), rect.top(), rect.left() + radius, rect.top()); } else { path.addRect(rect); } painter.fillPath(path, this->palette().base().color()); QPushButton::paintEvent(event); } bool VpnItem::eventFilter(QObject *watched, QEvent *event) { Q_UNUSED(watched) Q_UNUSED(event) return false; } void VpnItem::setCornerType(CornerType type) { m_cornerType = type; update(); }kylin-nm/plugins/vpn/vpn.ui0000664000175000017500000000512715167646234014707 0ustar fengfeng Vpn 0 0 800 710 0 0 16777215 16777215 Vpn 8 0 0 0 0 0 0 VPN import Qt::Horizontal 40 20 Qt::Vertical 20 40 TitleLabel QLabel
titlelabel.h
kylin-nm/plugins/vpn/itemframe.h0000664000175000017500000000303215167651420015651 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef ITEMFRAME_H #define ITEMFRAME_H #include #include #include "../component/AddBtn/addnetbtn.h" #include "vpnitem.h" class ItemFrame : public QFrame { Q_OBJECT public: ItemFrame(QWidget *parent = nullptr); //VPN整体layout QVBoxLayout * m_mainVLayout = nullptr; //vpn列表Frame QFrame * m_vpnFrame = nullptr; //单设备列表layout QVBoxLayout * m_vpnVLayout = nullptr; //item列表 QMap m_itemMap; // //已激活uuid // QString uuid = ""; //新建无线连接 AddNetBtn * m_addVpnWidget = nullptr; void filletStyleChange(); void updateCornerStyle(); }; #endif // ITEMFRAME_H kylin-nm/plugins/vpn/vpn.cpp0000664000175000017500000004063415167651420015047 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "vpn.h" #include "ui_vpn.h" #include #include #include #include #include #define ACTIVATING 1 #define ACTIVATED 2 #define DEACTIVATING 3 #define DEACTIVATED 4 #define LABEL_RECT 17, 0, 105, 23 #define CONTENTS_MARGINS 0, 0, 0, 0 #define ITEM_MARGINS 16, 0, 16, 0 #define FRAME_MIN_SIZE 550, 60 #define FRAME_MAX_SIZE 16777215, 16777215 #define CONTECT_FRAME_MAX_SIZE 16777215, 60 #define HINT_TEXT_MARGINS 8, 0, 0, 0 #define FRAME_MIN_SIZE 550, 60 #define LABLE_MIN_WIDTH 188 #define COMBOBOX_MIN_WIDTH 200 #define LINE_MAX_SIZE 16777215, 1 #define LINE_MIN_SIZE 0, 1 #define ICON_SIZE 24,24 #define PASSWORD_FRAME_MIN_HIGHT 60 #define PASSWORD_FRAME_FIX_HIGHT 80 #define PASSWORD_FRAME_MIN_SIZE 550, 60 #define PASSWORD_FRAME_MAX_SIZE 16777215, 86 #define PASSWORD_ITEM_MARGINS 16, 12, 16, 14 #define KVpnSymbolic "ukui-vpn-symbolic" #define KYLIN_APP_MANAGER_NAME "com.kylin.AppManager" #define KYLIN_APP_MANAGER_PATH "/com/kylin/AppManager" #define KYLIN_APP_MANAGER_INTERFACE "com.kylin.AppManager" const QString VISIBLE = "visible"; const QByteArray GSETTINGS_SCHEMA = "org.ukui.kylin-nm.vpnicon"; Vpn::Vpn() : m_firstLoad(true) { QTranslator* translator = new QTranslator(this); translator->load("/usr/share/kylin-nm/vpn/" + QLocale::system().name()); QApplication::installTranslator(translator); m_pluginName = tr("VPN"); m_pluginType = NETWORK; } Vpn::~Vpn() { if (!m_firstLoad) { delete ui; ui = nullptr; delete m_interface; delete m_switchGsettings; } } QString Vpn::plugini18nName(){ return m_pluginName; } int Vpn::pluginTypes(){ return m_pluginType; } QWidget *Vpn::pluginUi(){ if (m_firstLoad) { m_firstLoad = false; ui = new Ui::Vpn; m_pluginWidget = new QWidget; m_pluginWidget->setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(m_pluginWidget); qDBusRegisterMetaType>(); m_interface = new QDBusInterface("com.kylin.kylinvpn", "/com/kylin/kylinvpn", "com.kylin.kylinvpn", QDBusConnection::sessionBus()); if(!m_interface->isValid()) { qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } initComponent(); initConnect(); initNet(); initSearchText(); } return m_pluginWidget; } const QString Vpn::name() const { return QStringLiteral("Vpn"); } bool Vpn::isShowOnHomePage() const { return true; } QIcon Vpn::icon() const { return QIcon::fromTheme("ukui-vpn-symbolic"); } bool Vpn::isEnable() const { return true; } QString Vpn::translationPath() const { return "/usr/share/kylin-nm/vpn/%1.ts"; } void Vpn::initComponent(){ //在任务栏上显示图标 //显示已连接时间 m_topFrame = new QFrame(m_pluginWidget); m_topFrame->setMinimumSize(FRAME_MIN_SIZE); m_topFrame->setMaximumSize(FRAME_MAX_SIZE); m_topFrame->setFrameShape(QFrame::Box); QVBoxLayout *hotspotLyt = new QVBoxLayout(m_pluginWidget); hotspotLyt->setContentsMargins(0, 0, 0, 0); m_topFrame->setLayout(hotspotLyt); m_showFrame = new QFrame(m_topFrame); m_showFrame->setFrameShape(QFrame::Shape::NoFrame); m_showFrame->setMinimumSize(FRAME_MIN_SIZE); m_showFrame->setMaximumSize(CONTECT_FRAME_MAX_SIZE); QHBoxLayout *showLayout = new QHBoxLayout(m_showFrame); m_showLabel = new QLabel(tr("Show on Taskbar"), m_showFrame); m_showLabel->setMinimumWidth(LABLE_MIN_WIDTH); m_showBtn = new KSwitchButton(m_showFrame); showLayout->setContentsMargins(ITEM_MARGINS); showLayout->addWidget(m_showLabel); showLayout->addStretch(); showLayout->addWidget(m_showBtn); m_showFrame->setLayout(showLayout); // m_Line = myLine(); // m_timeFrame = new QFrame(m_topFrame); // m_timeFrame->setFrameShape(QFrame::Shape::NoFrame); // m_timeFrame->setMinimumSize(FRAME_MIN_SIZE); // m_timeFrame->setMaximumSize(CONTECT_FRAME_MAX_SIZE); // QHBoxLayout *timeLayout = new QHBoxLayout(m_timeFrame); // m_timeLabel = new QLabel(tr("Open"), m_timeFrame); // m_timeLabel->setMinimumWidth(LABLE_MIN_WIDTH); // m_timeBtn = new KSwitchButton(m_timeFrame); // timeLayout->setContentsMargins(ITEM_MARGINS); // timeLayout->addWidget(m_timeLabel); // timeLayout->addStretch(); // timeLayout->addWidget(m_timeBtn); // m_timeFrame->setLayout(timeLayout); hotspotLyt->addWidget(m_showFrame); // hotspotLyt->addWidget(m_Line); // hotspotLyt->addWidget(m_timeFrame); hotspotLyt->setSpacing(0); //列表 m_listFrame = new ItemFrame(m_pluginWidget); ui->verticalLayout_4->addWidget(m_topFrame); ui->verticalLayout_3->addWidget(m_listFrame); connect(m_listFrame->m_addVpnWidget, &AddNetBtn::clicked, this, [=]() { UkccCommon::buriedSettings(QString("VPN"), QString("Add VPN"), QString("clicked")); runExternalApp(); }); if (QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA)) { m_switchGsettings = new QGSettings(GSETTINGS_SCHEMA); setShowSwitchStatus(); connect(m_switchGsettings, &QGSettings::changed, this, [=] (const QString &key) { if (key == VISIBLE) { setShowSwitchStatus(); } }); } else { m_showBtn->setChecked(false); m_showBtn->setCheckable(false); qDebug()<<"[Vpn] org.ukui.kylin-nm.visible is not installed!"; } connect(m_showBtn, &KSwitchButton::stateChanged, this, [=](bool state){ if (m_switchGsettings != nullptr) { m_switchGsettings->set(VISIBLE, state); } }); connect(m_showBtn, &KSwitchButton::clicked, this, [=](bool checked){ UkccCommon::buriedSettings(QString("VPN"), QString("Show on Taskbar"), QString("settings"), checked ? "true":"false"); }); // connect(m_timeBtn, &KSwitchButton::stateChanged, this, [=](bool state){ // if (m_switchGsettings != nullptr) { // m_switchGsettings->set(VISIBLE, state); // } // }); ui->pushButton->hide(); } void Vpn::initConnect() { connect(m_interface, SIGNAL(vpnAdd(QStringList)), this, SLOT(onVpnAdd(QStringList))); connect(m_interface, SIGNAL(vpnRemove(QString)), this, SLOT(onVpnRemove(QString))); connect(m_interface, SIGNAL(vpnUpdate(QStringList)), this, SLOT(onVpnUpdate(QStringList))); connect(m_interface, SIGNAL(vpnActiveConnectionStateChanged(QString, int)), this, SLOT(onVpnActiveConnectionStateChanged(QString, int))); } //初始化列表 void Vpn::initNet() { qDebug() << "[Vpn]initNet"; if (!m_interface->isValid()) { return; } QDBusMessage result = m_interface->call(QStringLiteral("getVirtualList")); if(result.type() == QDBusMessage::ErrorMessage) { qWarning() << "getVirtualList error:" << result.errorMessage(); return; } auto dbusArg = result.arguments().at(0).value(); QVector variantList; dbusArg >> variantList; if (variantList.size() == 0) { qDebug() << "[Vpn]initNet list empty"; return; } for (int i = 0; i < variantList.size(); ++i) { QStringList vpnInfo = variantList.at(i); addOneVirtualItem(vpnInfo); } // 初始化完成后更新圆角样式 m_listFrame->filletStyleChange(); m_listFrame->updateCornerStyle(); return; } void Vpn::setShowSwitchStatus() { if (QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA)) { bool status = m_switchGsettings->get(VISIBLE).toBool(); m_showBtn->setChecked(status); } else { qDebug()<<"[Vpn] org.ukui.kylin-nm.switch is not installed!"; } } void Vpn::initSearchText() { //~ contents_path /Vpn/Show on Taskbar tr("Show on Taskbar"); //~ contents_path /Vpn/Add VPN tr("Add VPN"); } void Vpn::runExternalApp(){ // QString cmd = "nm-connection-editor"; // QProcess process(this); // process.startDetached(cmd); if (m_interface->isValid()) { m_interface->call(QStringLiteral("showVpnAddWidget")); } } QFrame* Vpn::myLine() { QFrame *line = new QFrame(m_pluginWidget); line->setMinimumSize(QSize(LINE_MIN_SIZE)); line->setMaximumSize(QSize(LINE_MAX_SIZE)); line->setLineWidth(0); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); return line; } //刪除 void Vpn::deleteVpn(QString uuid) { m_interface->call(QStringLiteral("deleteVpn"), uuid); } //激活 void Vpn::activeConnect(QString uuid) { m_interface->call(QStringLiteral("activateVpn"), uuid); } //详情页 void Vpn::showDetailPage(QString uuid) { m_interface->call(QStringLiteral("showDetailPage"), uuid); } //断开 void Vpn::deActiveConnect(QString uuid) { m_interface->call(QStringLiteral("deactivateVpn"), uuid); } //增加一项 void Vpn::addOneVirtualItem(QStringList infoList) { if (infoList.size() < 4) { qDebug() << "[Vpn]QStringList size less"; return; } if (m_listFrame->m_itemMap.contains(infoList.at(1))) { qDebug() << "[Vpn]Already exist a virtual " << infoList.at(1); return; } qDebug() << "[Vpn]addOneVitualItem" << infoList.at(0) << infoList.at(3) ; QString connName = infoList.at(0); QString connUuid = infoList.at(1); QString connDbusPath = infoList.at(2); int status = infoList.at(3).toInt(); //1-连接中 2-已连接 3-断开中 4-已断开 VpnItem * item = new VpnItem(m_pluginWidget); QIcon searchIcon = QIcon::fromTheme(KVpnSymbolic); item->m_iconLabel->setPixmap(searchIcon.pixmap(searchIcon.actualSize(QSize(ICON_SIZE)))); item->m_titileLabel->setText(connName); item->m_uuid = connUuid; item->m_dbusPath = connDbusPath; if (status == 1 || status == 3) { item->startLoading(); } connect(item->m_infoLabel, &GrayInfoButton::clicked, this, [=]{ showDetailPage(item->m_uuid); }); item->m_isAcitve = (status == 2); item->setConnectActionText(item->m_isAcitve); if (item->m_isAcitve) { item->m_statusLabel->setText(tr("connected")); } else { item->m_statusLabel->setText(tr("not connected")); } connect(item, &QPushButton::clicked, this, [=] { if (item->m_isAcitve || item->m_loading) { deActiveConnect(item->m_uuid); } else { activeConnect(item->m_uuid); } }); connect(item, &VpnItem::connectActionTriggered, this, [=] { activeConnect(item->m_uuid); }); connect(item, &VpnItem::disconnectActionTriggered, this, [=] { deActiveConnect(item->m_uuid); }); connect(item, &VpnItem::deleteActionTriggered, this, [=] { deleteVpn(item->m_uuid); }); //记录到deviceFrame的m_itemMap中 m_listFrame->m_itemMap.insert(connUuid, item); int index = getInsertPos(connName); qDebug()<<"[Vpn]addOneVirtualItem " << connName << " at pos:" << index; m_listFrame->m_vpnVLayout->insertWidget(index, item); // 只在这里调用filletStyleChange m_listFrame->filletStyleChange(); // 每次都调用updateCornerStyle,确保圆角正确 m_listFrame->updateCornerStyle(); } void Vpn::removeOneVirtualItem(QString dbusPath) { qDebug()<<"[Vpn]vpn remove dbus path:" << dbusPath; QMap::iterator itemIter; for (itemIter = m_listFrame->m_itemMap.begin(); itemIter != m_listFrame->m_itemMap.end(); itemIter++) { if (itemIter.value()->m_dbusPath == dbusPath) { qDebug()<<"[Vpn]vpn remove " << dbusPath << " find in " << itemIter.value()->m_titileLabel->text(); QString key = itemIter.key(); m_listFrame->m_vpnVLayout->removeWidget(itemIter.value()); delete itemIter.value(); m_listFrame->m_itemMap.remove(key); break; } } // 只在这里调用filletStyleChange m_listFrame->filletStyleChange(); // 每次都调用updateCornerStyle,确保圆角正确 m_listFrame->updateCornerStyle(); } //增加 void Vpn::onVpnAdd(QStringList infoList) { addOneVirtualItem(infoList); } //移出 void Vpn::onVpnRemove(QString path) { removeOneVirtualItem(path); } //名称变化 void Vpn::onVpnUpdate(QStringList info) { if (m_listFrame->m_itemMap.contains(info.at(1))) { qDebug() << "[Vpn]" << m_listFrame->m_itemMap[info.at(1)]->m_titileLabel->text() << "change to" << info.at(0); if (m_listFrame->m_itemMap[info.at(1)]->m_titileLabel->text() != info.at(0)) { m_listFrame->m_itemMap[info.at(1)]->m_titileLabel->setText(info.at(0)); } } } void Vpn::onVpnActiveConnectionStateChanged(QString uuid, int status) { if (uuid.isEmpty()) { qDebug() << "[Vpn]onActiveConnectionChanged but uuid is empty"; return; } qDebug() << "[Vpn]onActiveConnectionChanged " << uuid << status; VpnItem * item= nullptr; if (m_listFrame->m_itemMap.contains(uuid)) { item = m_listFrame->m_itemMap[uuid]; if (status == ACTIVATED) { //为已连接则放到第一个 m_listFrame->m_vpnVLayout->removeWidget(item); m_listFrame->m_vpnVLayout->insertWidget(0,item); } else if (status == DEACTIVATED) { //为断开则重新插入 int index = getInsertPos(item->m_titileLabel->text()); qDebug() << "[Vpn]reinsert" << item->m_titileLabel->text() << "pos" << index << "because status changes to deactive"; m_listFrame->m_vpnVLayout->removeWidget(item); m_listFrame->m_vpnVLayout->insertWidget(index,item); } itemActiveConnectionStatusChanged(item, status); } } void Vpn::itemActiveConnectionStatusChanged(VpnItem *item, int status) { // QString iconPath = NoNetSymbolic; if (status == ACTIVATING) { item->startLoading(); } else if (status == ACTIVATED) { item->stopLoading(); // iconPath = KLanSymbolic; item->m_statusLabel->clear(); item->m_statusLabel->setMinimumSize(36,36); item->m_statusLabel->setMaximumSize(16777215,16777215); item->m_statusLabel->setText(tr("connected")); item->m_isAcitve = true; } else if (status == DEACTIVATING) { item->startLoading(); } else { item->stopLoading(); item->m_statusLabel->setMinimumSize(36,36); item->m_statusLabel->setMaximumSize(16777215,16777215); item->m_statusLabel->clear(); item->m_isAcitve = false; item->m_statusLabel->setText(tr("not connected")); } item->setConnectActionText(item->m_isAcitve); } int Vpn::getInsertPos(QString connName) { qDebug() << "[Vpn]getInsertPos" << connName; int index = 0; if(!m_interface->isValid()) { index = 0; } else { QDBusMessage result = m_interface->call(QStringLiteral("getVirtualList")); if(result.type() == QDBusMessage::ErrorMessage) { qWarning() << "getVirtualList error:" << result.errorMessage(); return 0; } auto dbusArg = result.arguments().at(0).value(); QVector variantList; dbusArg >> variantList; if (variantList.isEmpty()) { qDebug() << "[Vpn] virtualList is empty, getInsertPos return 0"; return 0; } for (int i = 0; i < variantList.size(); ++i ) { if (variantList.at(i).at(0) == connName) { qDebug() << "pos in kylin-nm is " << i; index = i; break; } } if (variantList.at(0).size() == 1) { index--; } } return index; } kylin-nm/plugins/vpn/vpnitem.h0000664000175000017500000000507215167651420015370 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef VPNITEM_H #define VPNITEM_H #include #include #include #include #include #include #include #include #include #include #include #include #include "klabel.h" #include "../component/AddBtn/grayinfobutton.h" using namespace kdk; class VpnItem : public QPushButton { Q_OBJECT public: VpnItem(bool bAcitve, QWidget *parent = nullptr); public: QLabel * m_iconLabel = nullptr; GrayInfoButton * m_infoLabel = nullptr; KLabel * m_titileLabel = nullptr; QLabel * m_statusLabel = nullptr; QPushButton* m_moreButton = nullptr; QMenu* m_moreMenu = nullptr; QAction* m_connectAction = nullptr; QAction* m_deleteAction = nullptr; QString m_uuid = ""; QString m_dbusPath = ""; void setHalfFillet(bool flag) {m_useHalfFillet = flag; repaint();} public: void startLoading(); void stopLoading(); void setConnectActionText(bool isAcitve); bool m_isAcitve = false; bool m_loading = false; enum CornerType { None, Top }; void setCornerType(CornerType type); private: CornerType m_cornerType = None; protected: void paintEvent(QPaintEvent *event); bool eventFilter(QObject *watched, QEvent *event); private: QTimer *m_waitTimer = nullptr; bool m_useHalfFillet = false; QList m_loadIcons; int m_currentIconIndex=0; private slots: void updateIcon(); void onConnectTriggered(); void onDeletetTriggered(); void onMoreButtonClicked(); Q_SIGNALS: void connectActionTriggered(); void disconnectActionTriggered(); void deleteActionTriggered(); }; #endif // VPNITEM_H kylin-nm/plugins/wlanconnect/0000775000175000017500000000000015167651420015241 5ustar fengfengkylin-nm/plugins/wlanconnect/translations/0000775000175000017500000000000015167654227017772 5ustar fengfengkylin-nm/plugins/wlanconnect/translations/de.ts0000664000175000017500000000603515167646234020735 0ustar fengfeng AddNetBtn Add Others Andere hinzufügen Add WiredNetork WiredNetork hinzufügen WlanConnect WlanConnect WlanConnect WLAN WLAN open offen /wlanconnect/open Advanced settings Erweiterte Einstellungen /wlanconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 Settings Einstellungen Settings desktop message Desktop-Meldung für Einstellungen No wireless network card detected Keine Wireless-Netzwerkkarte erkannt connected verbunden card Karte kylin-nm/plugins/wlanconnect/translations/ky.ts0000664000175000017500000000630315167646234020766 0ustar fengfeng AddNetBtn Add Others باشقانى قوشۇۇ Add WiredNetork سىمدۇۇ تور قوشۇۇ WlanConnect WlanConnect تار گۅۅلۅمدۉ سەمىز تور WLAN تار گۅۅلۅمدۉ سەمىز تور open اچۇۇ /wlanconnect/open Advanced settings جوعورۇ تەڭشەكتەر /wlanconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 Settings تەڭشەكتەر Settings desktop message شىرە بەتى ۇچۇرۇ تەڭشەگى No wireless network card detected سەمىز تور كارتوچكاسى بايقالبادى connected جالعانعان card تور كارتوچكاسى kylin-nm/plugins/wlanconnect/translations/zh_CN.ts0000664000175000017500000000640315167651420021336 0ustar fengfeng AddNetBtn Add Others 加入其它网络 Add WiredNetwork 添加有线网络 WlanConnect WlanConnect 无线局域网 WLAN 无线局域网 /wlanconnect/WLAN open 开启 Advanced settings 高级设置 /wlanconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 Settings 设置 Settings desktop message 设置 桌面通知 Add Others 加入其它网络 /wlanconnect/Add Others" No wireless network card detected 未检测到无线网卡 connected 已连接 card 网卡 kylin-nm/plugins/wlanconnect/translations/kk.ts0000664000175000017500000000630215167646234020747 0ustar fengfeng AddNetBtn Add Others باسقانٸ قوسۋ Add WiredNetork سىمدى تور قوسۋ WlanConnect WlanConnect سۇيىر كولەمدىك سىمسىز تور WLAN سۇيىر كولەمدىك سىمسىز تور open ٸشٸۋ /wlanconnect/open Advanced settings جوعارعى تەڭشەۋلەر /wlanconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 Settings تەڭشەۋلەر Settings desktop message ۇستەل بەتى حابارى تەڭگەرگٸش No wireless network card detected سىمسىز تور كارتاسى بايقالمادٸ connected جالعانعان card تور كارتاسى kylin-nm/plugins/wlanconnect/translations/ms.ts0000664000175000017500000000646215167651420020761 0ustar fengfeng AddNetBtn Add Others Add WiredNetwork WlanConnect WlanConnect WLAN /wlanconnect/WLAN open Advanced settings /wlanconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 Settings Settings desktop message Add Others /wlanconnect/Add Others" No wireless network card detected connected card kylin-nm/plugins/wlanconnect/translations/tr.ts0000664000175000017500000000576415167651420020773 0ustar fengfeng AddNetBtn Add Others Add WiredNetwork WlanConnect WlanConnect WLAN /wlanconnect/WLAN open Advanced settings /wlanconnect/Advanced settings" Settings Settings desktop message Add Others /wlanconnect/Add Others" No wireless network card detected connected card kylin-nm/plugins/wlanconnect/translations/bo.ts0000664000175000017500000000576415167651420020746 0ustar fengfeng AddNetBtn Add Others Add WiredNetwork WlanConnect WlanConnect WLAN /wlanconnect/WLAN open Advanced settings /wlanconnect/Advanced settings" Settings Settings desktop message Add Others /wlanconnect/Add Others" No wireless network card detected connected card kylin-nm/plugins/wlanconnect/translations/ug.ts0000664000175000017500000000645615167646234020767 0ustar fengfeng AddNetBtn Add Others باشقىلار قوشۇش Add WiredNetork سىملىق تور قوشۇش WlanConnect WlanConnect تار دائىرىلىك سىمسىز تور WLAN تار دائىرىلىك سىمسىز تور open ئېچىش /wlanconnect/open Advanced settings يۇقىرى تەڭشەكلەر /wlanconnect/Advanced settings" ukui control center كونترول قىلىش ئېكرانى ukui control center desktop message كونترول قىلىش ئېكرانى ئۈستەل ئۈستىدە ئۇقتۇرۇش قىلىنىدۇ Settings تەڭشەكلەر Settings desktop message ئۈستەل يۈزى ئۇچۇرى تەڭشىكى No wireless network card detected سىمسىز تور كارتىسى بايقالمىدى connected ئۇلانغان card تور كارتىسى kylin-nm/plugins/wlanconnect/translations/bo_CN.ts0000664000175000017500000001016615167651420021316 0ustar fengfeng AddNetBtn Add Others དྲ་རྒྱ་གཞན་དག་ནང་ཞུགས་དགོས། Add WiredNetwork སྐུད་ཡོད་དྲ་རྒྱ་སྣོན་པ། WlanConnect WlanConnect ཝུའུ་ལན་འབྲེལ་མཐུད། WLAN སྐུད་མེད་ཅུས་ཁོངས་ཀྱི་དྲ་བ། /wlanconnect/WLAN open སྒོ་ཕྱེ་བ། Advanced settings སྔོན་ཐོན་གྱི་སྒྲིག་བཀོད། /wlanconnect/Advanced settings" ukui control center ཝུའུ་ཁི་ལན་གྱི་ཚོད་འཛིན་ལྟེ་གནས། ukui control center desktop message ངོས་ལེབ་ངོས་ཀྱི་བརྡ་ཐོ་ཚོད་འཛིན་བྱ་དགོས། Settings བཀོད་སྒྲིག་བཅས་བྱ་དགོས། Settings desktop message བཀོད་སྒྲིག་བཅས་བྱ་དགོས། ཅོག་ངོས་ལ་བརྡ་ཐོ་གཏོང་དགོས། Add Others དྲ་རྒྱ་གཞན་དག་ནང་ཞུགས་དགོས། /wlanconnect/Add Others" No wireless network card detected སྐུད་མེད་དྲ་རྒྱའི་བྱང་བུ་མ་རྙེད་པ། connected འབྲེལ་མཐུད་བྱེད་པ། card བྱང་བུ། kylin-nm/plugins/wlanconnect/translations/vi.ts0000664000175000017500000000612315167651420020752 0ustar fengfeng AddNetBtn Add Others Thêm mạng khác Add WiredNetork Thêm WiredNetork WlanConnect WlanConnect Kết nối Wlan WLAN Mạng cục bộ không dây open Mở /wlanconnect/open Advanced settings Cài đặt cao cấp /wlanconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 Settings Mục cài đặt Settings desktop message Cài đặt thông báo trên màn hình No wireless network card detected Không phát hiện thẻ mạng không dây connected Đã kết nối card Card âm thanh kylin-nm/plugins/wlanconnect/translations/mn.ts0000664000175000017500000000733115167646234020757 0ustar fengfeng AddNetBtn Add Others ᠪᠤᠰᠤᠳ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠵᠠᠯᠭᠠᠬᠤ Add WiredNetork ᠤᠲᠠᠰᠤᠲᠤ ᠨᠧᠲ ᠨᠡᠮᠡᠬᠦ WlanConnect WlanConnect ᠤᠳᠠᠰᠤ ᠦᠬᠡᠢ ᠬᠡᠰᠡᠭ ᠰᠦᠯᠵᠢᠶ᠎ᠡ WLAN ᠤᠳᠠᠰᠤ ᠦᠬᠡᠢ ᠬᠡᠰᠡᠭ ᠰᠦᠯᠵᠢᠶ᠎ᠡ open ᠨᠡᠭᠡᠭᠡᠬᠦ /wlanconnect/open Advanced settings ᠦᠨᠳᠦᠷ ᠵᠡᠷᠬᠡ ᠵᠢᠨ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠤᠯᠳᠠ /wlanconnect/Advanced settings" ukui control center ᠡᠵᠡᠮᠰᠢᠯ ᠤ᠋ᠨ ᠬᠠᠪᠳᠠᠰᠤ ukui control center desktop message ᠡᠵᠡᠮᠰᠢᠯ ᠤ᠋ᠨ ᠬᠠᠪᠳᠠᠰᠤᠨ ᠤ᠋ ᠰᠢᠷᠡᠭᠡᠨ ᠨᠢᠭᠤᠷ ᠤ᠋ᠨ ᠮᠡᠳᠡᠭᠳᠡᠯ Settings ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Settings desktop message ᠰᠢᠷᠡᠭᠡᠨ ᠨᠢᠭᠤᠷ᠎ᠤ᠋ᠨ ᠵᠠᠩᠭᠢ᠎ᠶ᠋ᠢ ᠵᠣᠬᠢᠷᠠᠭᠤᠯᠬᠤ No wireless network card detected ᠤᠳᠠᠰᠤ ᠦᠬᠡᠢ ᠨᠧᠲ ᠺᠠᠷᠲ᠎ᠢ ᠬᠢᠨᠠᠨ ᠬᠡᠮᠵᠢᠵᠤ ᠤᠯᠤᠭᠰᠠᠨ ᠦᠬᠡᠢ connected ᠨᠢᠬᠡᠨᠳᠡ ᠴᠦᠷᠬᠡᠯᠡᠪᠡ card ᠨᠧᠲ ᠺᠠᠷᠲ kylin-nm/plugins/wlanconnect/translations/zh_Hant.ts0000664000175000017500000000577715167646234021754 0ustar fengfeng AddNetBtn Add Others 添加其他 Add WiredNetork 添加有線網路 WlanConnect WlanConnect 無線局域網 WLAN 無線局域網 open 開啟 /wlanconnect/open Advanced settings 高級設置 /wlanconnect/Advanced settings" ukui control center 烏奎控制中心 ukui control center desktop message UKUI 控制中心桌面消息 Settings 設定 Settings desktop message 設定案頭消息 No wireless network card detected 未檢測到無線網卡 connected 已連接 card 網卡 kylin-nm/plugins/wlanconnect/translations/fr.ts0000664000175000017500000000612415167646234020753 0ustar fengfeng AddNetBtn Add Others Ajouter d’autres Add WiredNetork Ajouter WiredNetork WlanConnect WlanConnect WlanConnect (en anglais seulement) WLAN Réseau local sans fil (WLAN) open ouvrir /wlanconnect/open Advanced settings Paramètres avancés /wlanconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 Settings Paramètres Settings desktop message Message sur le bureau des paramètres No wireless network card detected Aucune carte réseau sans fil n’a été détectée connected relié card carte kylin-nm/plugins/wlanconnect/translations/en_US.ts0000664000175000017500000000662415167651420021353 0ustar fengfeng AddNetBtn Add Others Add Others Add WiredNetwork Add WiredNetork Add WiredNetork WlanConnect WlanConnect WlanConnect WLAN WLAN /wlanconnect/WLAN open open Advanced settings Advanced settings /wlanconnect/Advanced settings" ukui control center ukui control center ukui control center desktop message ukui control center desktop message Settings Settings desktop message Add Others Add Others /wlanconnect/Add Others" No wireless network card detected No wireless network card detected connected connected card card kylin-nm/plugins/wlanconnect/translations/es.ts0000664000175000017500000000604415167646234020754 0ustar fengfeng AddNetBtn Add Others Agregar otros Add WiredNetork Añadir WiredNetork WlanConnect WlanConnect WlanConnect WLAN WLAN open abrir /wlanconnect/open Advanced settings Ajustes avanzados /wlanconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 Settings Configuración Settings desktop message Mensaje de escritorio de configuración No wireless network card detected No se ha detectado ninguna tarjeta de red inalámbrica connected conexo card tarjeta kylin-nm/plugins/wlanconnect/translations/zh_HK.ts0000664000175000017500000000640715167651420021344 0ustar fengfeng AddNetBtn Add Others 加入其它網絡 Add WiredNetwork 添加有線網絡 WlanConnect WlanConnect 無線連接 WLAN 無線局域網 /wlanconnect/WLAN open 打開 Advanced settings 高級設置 /wlanconnect/Advanced settings" ukui control center 烏奎控制中心 ukui control center desktop message UKUI 控制中心桌面消息 Settings 設置 Settings desktop message 設置桌面通知 Add Others 加入其它網絡 /wlanconnect/Add Others" No wireless network card detected 未檢測到無線網卡 connected 已連接 card 網卡 kylin-nm/plugins/wlanconnect/wlanconnect.pro0000664000175000017500000000253115167651420020277 0ustar fengfengQT += widgets network dbus gui core TEMPLATE = lib CONFIG += plugin include(../component/drownlabel.pri) include(../component/addbtn.pri) TARGET = $$qtLibraryTarget(wlanconnect) DESTDIR = ../.. CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } target.path = $$[QT_INSTALL_LIBS]/ukui-control-center trans.files = translations/* trans.path = /usr/share/kylin-nm/wlanconnect/ INCLUDEPATH += \ $$PROJECT_COMPONENTSOURCE \ $$PROJECT_ROOTDIR \ /usr/include/ukcc/interface \ /usr/include/ukcc/widgets LIBS += -L$$[QT_INSTALL_LIBS] -lukcc CONFIG += c++11 \ link_pkgconfig \ PKGCONFIG += gsettings-qt6 \ kysdk-applications \ #DEFINES += QT_DEPRECATED_WARNINGS SOURCES += \ deviceframe.cpp \ # drownlabel.cpp \ itemframe.cpp \ wlanconnect.cpp \ wlanitem.cpp HEADERS += \ deviceframe.h \ # drownlabel.h \ itemframe.h \ wlanconnect.h \ wlanitem.h FORMS += \ wlanconnect.ui INSTALLS += target \ trans TRANSLATIONS += \ translations/zh_HK.ts \ translations/zh_CN.ts \ translations/tr.ts \ translations/bo.ts \ translations/bo_CN.ts \ translations/en_US.ts \ translations/mn_MN.ts kylin-nm/plugins/wlanconnect/itemframe.cpp0000664000175000017500000000521115167651420017715 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "itemframe.h" #include #define LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_MARGINS 0,0,0,0 ItemFrame::ItemFrame(QString devName, QWidget *parent) { deviceLanLayout = new QVBoxLayout(this); deviceLanLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); lanItemFrame = new QFrame(this); lanItemFrame->setFrameShape(QFrame::Shape::NoFrame); lanItemFrame->setContentsMargins(LAYOUT_MARGINS); lanItemLayout = new QVBoxLayout(this); lanItemLayout->setContentsMargins(LAYOUT_MARGINS); lanItemLayout->setSpacing(1); addWlanWidget = new AddNetBtn(true, this); deviceLanLayout->setSpacing(0); setLayout(deviceLanLayout); lanItemFrame->setLayout(lanItemLayout); deviceFrame = new DeviceFrame(devName, this); deviceLanLayout->addWidget(deviceFrame); deviceLanLayout->addWidget(lanItemFrame); deviceLanLayout->addSpacing(1); deviceLanLayout->addWidget(addWlanWidget); //下拉按钮 connect(deviceFrame->dropDownLabel, &DrownLabel::labelClicked, this, &ItemFrame::onDrownLabelClicked); } ItemFrame::~ItemFrame() { } void ItemFrame::onDrownLabelClicked() { if (!deviceFrame->dropDownLabel->isChecked) { lanItemFrame->show(); deviceFrame->dropDownLabel->setDropDownStatus(true); } else { lanItemFrame->hide(); deviceFrame->dropDownLabel->setDropDownStatus(false); } } void ItemFrame::filletStyleChange() { if (lanItemLayout->isEmpty()) { return; } for (int i = 0; i < lanItemLayout->count(); ++i) { QLayoutItem *it = lanItemLayout->itemAt(i); WlanItem *itemFrame = (WlanItem*)(it->widget()); if (i != lanItemLayout->count()-1) { itemFrame->setHalfFillet(false); } else { itemFrame->setHalfFillet(true); } } } kylin-nm/plugins/wlanconnect/deviceframe.cpp0000664000175000017500000000477015167651420020227 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "deviceframe.h" #include #include #define LAYOUT_MARGINS 18,0,8,0 #define FRAME_HEIGHT 58 #define LAYOUT_SPACING 16 #define RADIUS 6.0 DeviceFrame::DeviceFrame(QString devName, QWidget *parent) : QFrame(parent) { this->setFrameShape(QFrame::Box); this->setFixedHeight(FRAME_HEIGHT); QHBoxLayout *deviceLayout = new QHBoxLayout(this); deviceLayout->setContentsMargins(LAYOUT_MARGINS); setLayout(deviceLayout); deviceLayout->setSpacing(LAYOUT_SPACING); deviceLabel = new QLabel(this); dropDownLabel = new DrownLabel(devName, this); deviceLayout->addWidget(deviceLabel); deviceLayout->addStretch(); deviceLayout->addWidget(dropDownLabel); } DeviceFrame::~DeviceFrame() { } void DeviceFrame::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true); QRect rect = this->rect(); const int radius = RADIUS; // 创建单一路径实现上圆角下直角 QPainterPath path; path.moveTo(rect.topLeft() + QPointF(0, radius)); path.arcTo(rect.left(), rect.top(), radius * 2, radius * 2, 180, -90); path.lineTo(rect.right() - radius, rect.top()); path.arcTo(rect.right() - radius * 2, rect.top(), radius * 2, radius * 2, 90, -90); path.lineTo(rect.right(), rect.bottom()); path.lineTo(rect.left(), rect.bottom()); path.lineTo(rect.left(), rect.top() + radius); // 绘制背景 painter.setPen(Qt::NoPen); painter.setBrush(pal.color(QPalette::Base)); painter.drawPath(path); // 保持基类绘制 QFrame::paintEvent(event); } kylin-nm/plugins/wlanconnect/translate_generation.sh0000775000175000017500000000056615167651420022017 0ustar fengfeng#!/bin/bash export PATH="/usr/lib/qt6/bin:$PATH" ts_list=(`ls translations/*.ts`) source /etc/os-release version=(`echo $ID`) for ts in "${ts_list[@]}" do printf "\nprocess ${ts}\n" if [ "$version" == "fedora" ] || [ "$version" == "opensuse-leap" ] || [ "$version" == "opensuse-tumbleweed" ];then lrelease-qt5 "${ts}" else lrelease "${ts}" fi done kylin-nm/plugins/wlanconnect/wlanconnect.ui0000664000175000017500000001160515167646234020125 0ustar fengfeng WlanConnect 0 0 885 700 WlanConnect 0 0 0 0 0 WLAN true 1 0 0 60 16777215 50 QFrame::Box 18 0 9 0 16 118 0 open Qt::Horizontal 523 20 1 8 120 36 16777215 36 Advanced settings Qt::Horizontal 40 20 Qt::Vertical 20 40 TitleLabel QLabel
titlelabel.h
kylin-nm/plugins/wlanconnect/wlanitem.cpp0000664000175000017500000000723015167651420017567 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "wlanitem.h" #include #include #include #define FRAME_SPEED 150 #define LIMIT_TIME 60*1000 #define TOTAL_PAGE 8 #define RADIUS 6.0 #define THEME_QT_SCHEMA "org.ukui.style" #define MODE_QT_KEY "style-name" WlanItem::WlanItem(bool bAcitve, bool isLock, QWidget *parent) : isAcitve(bAcitve), isLock(isLock), QPushButton(parent) { this->setMinimumSize(550, 58); this->setProperty("useButtonPalette", true); this->setFlat(true); QHBoxLayout *mLanLyt = new QHBoxLayout(this); mLanLyt->setContentsMargins(16,0,16,0); mLanLyt->setSpacing(16); iconLabel = new QLabel(this); iconLabel->setProperty("useIconHighlightEffect", 0x2); titileLabel = new KLabel(this); statusLabel = new QLabel(this); statusLabel->setProperty("useIconHighlightEffect", 0x2); statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); infoLabel = new GrayInfoButton(this); iconLabel->setAttribute(Qt::WA_TransparentForMouseEvents, true); titileLabel->setAttribute(Qt::WA_TransparentForMouseEvents, true); statusLabel->setAttribute(Qt::WA_TransparentForMouseEvents, true); mLanLyt->addWidget(iconLabel); mLanLyt->addWidget(titileLabel,Qt::AlignLeft); mLanLyt->addStretch(); mLanLyt->addWidget(statusLabel); mLanLyt->addWidget(infoLabel); loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); waitTimer = new QTimer(this); connect(waitTimer, &QTimer::timeout, this, &WlanItem::updateIcon); } WlanItem::~WlanItem() { } void WlanItem::updateIcon() { if (currentIconIndex > 6) { currentIconIndex = 0; } statusLabel->setPixmap(loadIcons.at(currentIconIndex).pixmap(16,16)); currentIconIndex ++; } void WlanItem::startLoading() { waitTimer->start(FRAME_SPEED); loading = true; } void WlanItem::stopLoading(){ waitTimer->stop(); loading = false; } void WlanItem::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); painter.setBrush(this->palette().base().color()); QPalette pal = qApp->palette(); QColor color = pal.color(QPalette::Button); color.setAlphaF(0.5); pal.setColor(QPalette::Button, color); this->setPalette(pal); QRect rect = this->rect(); painter.drawRect(rect); return QPushButton::paintEvent(event); } kylin-nm/plugins/wlanconnect/wlanconnect.h0000664000175000017500000001276215167651420017735 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef WLANCONNECT_H #define WLANCONNECT_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "itemframe.h" #include "wlanitem.h" #include "kwidget.h" #include "kswitchbutton.h" #include "ukcccommon.h" using namespace kdk; using namespace ukcc; namespace Ui { class WlanConnect; } class WlanConnect : public QObject, CommonInterface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.kycc.CommonInterface") Q_INTERFACES(CommonInterface) public: WlanConnect(); ~WlanConnect(); QString plugini18nName() Q_DECL_OVERRIDE; int pluginTypes() Q_DECL_OVERRIDE; QWidget * pluginUi() Q_DECL_OVERRIDE; const QString name() const Q_DECL_OVERRIDE; bool isShowOnHomePage() const Q_DECL_OVERRIDE; QIcon icon() const Q_DECL_OVERRIDE; bool isEnable() const Q_DECL_OVERRIDE; QString translationPath() const Q_DECL_OVERRIDE; private: void initComponent(); void runExternalApp(); void initSearchText(); void showDesktopNotify(const QString &message); //点击item 连接/断开 void activeConnect(QString netName, QString deviceName, int type); void deActiveConnect(QString netName, QString deviceName, int type); int sortWlanNet(QString deviceName, QString name, QString signal); void updateIcon(WlanItem *item, QString signalStrength, QString security, QString isApConnection, int category); void resortWifiList(ItemFrame *frame, QList list); //单wifi图标 int setSignal(QString lv); QString wifiIcon(bool isLock, int strength, int category); //开关相关 void hideLayout(QVBoxLayout * layout); void showLayout(QVBoxLayout * layout); //获取设备列表 void getDeviceList(QStringList &list); //初始化设备wifi列表 void initNet(); void initNetListFromDevice(QString deviceName); //处理列表 已连接 void addActiveItem(ItemFrame *frame, QString devName, QStringList infoList); //处理列表 未连接 void addCustomItem(ItemFrame *frame, QString devName, QStringList infoList); //增加设备 void addDeviceFrame(QString devName); //减少设备 void removeDeviceFrame(QString devName); //增加ap void addOneWlanFrame(ItemFrame *frame, QString deviceName, QString name, QString signal, QString uuid, bool isLock, bool status, int type, QString isApConnection, int category, int activeStatus); //减少ap void removeOneWlanFrame(ItemFrame *frame, QString deviceName, QString ssid); //单个wifi连接状态变化 void itemActiveConnectionStatusChanged(WlanItem *item, int status); // 打卡托盘网络窗口,后续需要跳转到指定密码框 void openKylinm(); void initSwtichState(); void setSwitchBtnEnable(bool state); bool getSwitchBtnEnable(); void setSwitchBtnState(bool state); bool getSwitchBtnState(); bool LaunchApp(QString desktopFile); void showNoDeiceInfo(bool visible,QString text); bool getWirelessSwitchBtnState(); void setSwitchStatus(); QMap getModuleHideStatus(); void wlanComponnetSettings(); protected: bool eventFilter(QObject *w,QEvent *e); private: Ui::WlanConnect *ui; QString pluginName; int pluginType; QWidget *pluginWidget; QDBusInterface *m_interface = nullptr; //设备列表 QStringList deviceList; //设备名 + 单设备frame QMap deviceFrameMap; //QVector wlanSignalList; // DeviceWlanlistInfo deviceWlanlistInfo; QTimer * m_scanTimer = nullptr; // QTimer * m_updateTimer = nullptr; QMap> getWirelessList(); QLabel *m_wirelessNoDeviceLabel=nullptr; QLabel *m_wirelessNoDeviceIconLabel=nullptr; private: KSwitchButton *m_wifiSwitch; bool m_firstLoad; private slots: void onNetworkAdd(QString deviceName, QStringList wlanInfo); void onNetworkRemove(QString deviceName, QString wlannName); void onActiveConnectionChanged(QString deviceName, QString ssid, QString uuid, int status); void updateList(); void onDeviceStatusChanged(); void onDeviceNameChanged(QString, QString, int); void onSwitchBtnChanged(bool); void reScan(); void switchStatusChanged(bool status); }; #endif // WLANCONNECT_H kylin-nm/plugins/wlanconnect/itemframe.h0000664000175000017500000000331615167646234017375 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef ITEMFRAME_H #define ITEMFRAME_H #include #include #include "deviceframe.h" #include "../component/AddBtn/addnetbtn.h" #include "wlanitem.h" class ItemFrame : public QFrame { Q_OBJECT public: ItemFrame(QString devName, QWidget *parent = nullptr); ~ItemFrame(); //单设备整体layout QVBoxLayout * deviceLanLayout = nullptr; //单设备名称+下拉按钮Frame DeviceFrame * deviceFrame = nullptr; //单设备列表Frame QFrame * lanItemFrame = nullptr; //单设备列表layout QVBoxLayout * lanItemLayout = nullptr; //单设备item列表 QMap itemMap; //已激活uuid QString uuid = ""; //新建无线连接 AddNetBtn * addWlanWidget = nullptr; void filletStyleChange(); private slots: void onDrownLabelClicked(); }; #endif // ITEMFRAME_H kylin-nm/plugins/wlanconnect/deviceframe.h0000664000175000017500000000264015167646234017675 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef DEVICEFRAME_H #define DEVICEFRAME_H #include #include #include #include #include #include #include "../component/DrownLabel/drownlabel.h" class DeviceFrame : public QFrame { public: DeviceFrame(QString devName, QWidget *parent = nullptr); ~DeviceFrame(); public: //仅设备名称+下拉label QLabel * deviceLabel = nullptr; DrownLabel *dropDownLabel = nullptr; protected: void paintEvent(QPaintEvent *event); private: int frameSize; }; #endif // DEVICEFRAME_H kylin-nm/plugins/wlanconnect/wlanitem.h0000664000175000017500000000374115167646234017246 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef WLANITEM_H #define WLANITEM_H #include #include #include #include #include #include #include #include #include #include "klabel.h" //#include "infobutton.h" #include "../component/AddBtn/grayinfobutton.h" using namespace kdk; class WlanItem : public QPushButton { public: WlanItem(bool bAcitve, bool isLock, QWidget *parent = nullptr); ~WlanItem(); public: QLabel * iconLabel = nullptr; GrayInfoButton * infoLabel = nullptr; KLabel * titileLabel = nullptr; QLabel * statusLabel = nullptr; QString uuid = ""; void setHalfFillet(bool flag) {useHalfFillet = flag; repaint();} public: void startLoading(); void stopLoading(); bool isAcitve = false; bool loading = false; bool isLock = false; protected: void paintEvent(QPaintEvent *event); private: QTimer *waitTimer = nullptr; QGSettings *themeGsettings = nullptr; bool useHalfFillet = false; QList loadIcons; int currentIconIndex=0; private slots: void updateIcon(); }; #endif // WLANITEM_H kylin-nm/plugins/wlanconnect/wlanconnect.cpp0000664000175000017500000012767615167651420020303 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "wlanconnect.h" #include "ui_wlanconnect.h" #include #include #include #include #include #include #include #define WIRELESS_TYPE 1 #define SCANTIMER 20 * 1000 #define UPDATETIMER 5 * 1000 #define SPACING 8 #define EXCELLENT_SIGNAL 80 #define GOOD_SIGNAL 55 #define OK_SIGNAL 30 #define LOW_SIGNAL 5 #define NONE_SIGNAL 0 #define SIGNAL_EXCELLENT 1 #define SIGNAL_GOOD 2 #define SIGNAL_OK 3 #define SIGNAL_LOW 4 #define SIGNAL_NONE 5 #define ICON_SIZE 16,16 #define KYLIN_APP_MANAGER_NAME "com.kylin.AppManager" #define KYLIN_APP_MANAGER_PATH "/com/kylin/AppManager" #define KYLIN_APP_MANAGER_INTERFACE "com.kylin.AppManager" #define DBUSSERVICE_UKCC "org.ukui.ukcc.session" #define DBUSPATH_UKCC "/" #define DBUSINTERFACE_UKCC "org.ukui.ukcc.session.interface" #define ACTIVATING 1 #define ACTIVATED 2 #define DEACTIVATING 3 #define DEACTIVATED 4 #define NO_MARGINS 0,0,0,0 #define MAIN_LAYOUT_MARGINS 0,0,0,8 const QString WIRELESS_SWITCH = "wirelessswitch"; const QByteArray GSETTINGS_SCHEMA = "org.ukui.kylin-nm.switch"; const QString KWifiSymbolic = "network-wireless-signal-excellent"; const QString KWifiLockSymbolic = "network-wireless-secure-signal-excellent"; const QString KWifiGood = "network-wireless-signal-good"; const QString KWifiLockGood = "network-wireless-secure-signal-good"; const QString KWifiOK = "network-wireless-signal-ok"; const QString KWifiLockOK = "network-wireless-secure-signal-ok"; const QString KWifiLow = "network-wireless-signal-low"; const QString KWifiLockLow = "network-wireless-secure-signal-low"; const QString KWifiNone = "network-wireless-signal-none"; const QString KWifiLockNone = "network-wireless-secure-signal-none"; const QString KWifi6Symbolic = "ukui-wifi6-full-symbolic"; const QString KWifi6PlusSymbolic = "ukui-wifi6+-full-symbolic"; const QString KWifi7Symbolic = "ukui-wifi7-full-symbolic"; const QString KWifi6LockSymbolic = "ukui-wifi6-full-pwd-symbolic"; const QString KWifi6PlusLockSymbolic= "ukui-wifi6+-full-pwd-symbolic"; const QString KWifi7LockSymbolic = "ukui-wifi7-full-pwd-symbolic"; const QString KWifi6Good = "ukui-wifi6-high-symbolic"; const QString KWifi6PlusGood = "ukui-wifi6+-high-symbolic"; const QString KWifi7Good = "ukui-wifi7-high-symbolic"; const QString KWifi6LockGood = "ukui-wifi6-high-pwd-symbolic"; const QString KWifi6PlusLockGood = "ukui-wifi6+-high-pwd-symbolic"; const QString KWifi7LockGood = "ukui-wifi7-high-pwd-symbolic"; const QString KWifi6OK = "ukui-wifi6-medium-symbolic"; const QString KWifi6PlusOK = "ukui-wifi6+-high-medium-symbolic"; const QString KWifi7OK = "ukui-wifi7-medium-symbolic"; const QString KWifi6LockOK = "ukui-wifi6-medium-pwd-symbolic"; const QString KWifi6PlusLockOK = "ukui-wifi6+-medium-pwd-symbolic"; const QString KWifi7LockOK = "ukui-wifi7-medium-pwd-symbolic"; const QString KWifi6Low = "ukui-wifi6-low-symbolic"; const QString KWifi6PlusLow = "ukui-wifi6+-low-symbolic"; const QString KWifi7Low = "ukui-wifi7-low-symbolic"; const QString KWifi6LockLow = "ukui-wifi6-low-pwd-symbolic"; const QString KWifi6PlusLockLow = "ukui-wifi6+-low-pwd-symbolic"; const QString KWifi7LockLow = "ukui-wifi7-low-pwd-symbolic"; const QString KWifi6None = "ukui-wifi6-none-symbolic"; const QString KWifi6PlusNone = "ukui-wifi6+-none-symbolic"; const QString KWifi7None = "ukui-wifi7-none-symbolic"; const QString KWifi6LockNone = "ukui-wifi6-none-pwd-symbolic"; const QString KWifi6PlusLockNone = "ukui-wifi6+-none-pwd-symbolic"; const QString KWifi7LockNone = "ukui-wifi7-none-pwd-symbolic"; const QString KLanSymbolic = ":/img/plugins/netconnect/eth.svg"; const QString NoNetSymbolic = ":/img/plugins/netconnect/nonet.svg"; const QString KApSymbolic = "network-wireless-hotspot-symbolic"; const QString IsApConnection = "1"; const QString WarningIconName = "dialog-warning"; void WlanConnect::showDesktopNotify(const QString &message) { QDBusInterface iface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus()); QList args; args<<(tr("Settings")) <<((unsigned int) 0) <load("/usr/share/kylin-nm/wlanconnect/" + QLocale::system().name()); QApplication::installTranslator(translator); pluginName = tr("WLAN"); pluginType = NETWORK; } WlanConnect::~WlanConnect() { if (!m_firstLoad) { delete ui; ui = nullptr; } delete m_interface; } QString WlanConnect::plugini18nName() { return pluginName; } int WlanConnect::pluginTypes() { return pluginType; } QWidget *WlanConnect::pluginUi() { if (m_firstLoad) { m_firstLoad = false; ui = new Ui::WlanConnect; pluginWidget = new QWidget; pluginWidget->setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(pluginWidget); qDBusRegisterMetaType>(); qDBusRegisterMetaType(); m_interface = new QDBusInterface("com.kylin.network", "/com/kylin/network", "com.kylin.network", QDBusConnection::sessionBus()); if(!m_interface->isValid()) { qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } initSearchText(); initComponent(); } return pluginWidget; } const QString WlanConnect::name() const { return QStringLiteral("wlanconnect"); } bool WlanConnect::isEnable() const { return true; } bool WlanConnect::isShowOnHomePage() const { return true; } QIcon WlanConnect::icon() const { return QIcon::fromTheme("network-wireless-signal-excellent-symbolic"); } QString WlanConnect::translationPath() const { return "/usr/share/kylin-nm/wlanconnect/%1.ts"; } void WlanConnect::initSearchText() { //~ contents_path /wlanconnect/Add Others" tr("Add Others"); //~ contents_path /wlanconnect/Advanced settings" ui->detailBtn->setText(tr("Advanced settings")); ui->titleLabel->setText(tr("WLAN")); //~ contents_path /wlanconnect/WLAN ui->openLabel->setText(tr("WLAN")); } bool WlanConnect::eventFilter(QObject *w, QEvent *e) { if (e->type() == QEvent::Enter) { if (w->findChild()) w->findChild()->setStyleSheet("QWidget{background: palette(button);border-radius:4px;}"); } else if (e->type() == QEvent::Leave) { if (w->findChild()) w->findChild()->setStyleSheet("QWidget{background: palette(base);border-radius:4px;}"); } if (w == m_wifiSwitch && m_wifiSwitch->isEnabled()) { if (e->type() == QMouseEvent::MouseButtonRelease) { m_wifiSwitch->clearFocus();//放if外会崩溃,如果按住鼠标不松,按空格依旧存在问题 if (!getSwitchBtnEnable()) { showDesktopNotify(tr("No wireless network card detected")); } else { UkccCommon::buriedSettings(QString("wlanconnect"), QString("Open"), QString("settings"),!getSwitchBtnState()?"true":"false"); if (m_interface != nullptr && m_interface->isValid()) { m_interface->call(QStringLiteral("setWirelessSwitchEnable"), !getSwitchBtnState()); } return true; } } } return QObject::eventFilter(w,e); } void WlanConnect::initComponent() { m_wifiSwitch = new KSwitchButton(pluginWidget); ui->openWIifLayout->setSpacing(5); m_wirelessNoDeviceIconLabel=new QLabel(ui->openWifiFrame); ui->openWIifLayout->addWidget(m_wirelessNoDeviceIconLabel); m_wirelessNoDeviceLabel=new QLabel(ui->openWifiFrame); ui->openWIifLayout->addWidget(m_wirelessNoDeviceLabel); ui->openWIifLayout->addWidget(m_wifiSwitch); ui->openWIifLayout->setContentsMargins(0,0,8,0); ui->detailLayOut_3->setContentsMargins(MAIN_LAYOUT_MARGINS); ui->verticalLayout_3->setContentsMargins(NO_MARGINS); ui->verticalLayout_3->setSpacing(8); ui->availableLayout->setSpacing(SPACING); m_wifiSwitch->installEventFilter(this); //开关 initSwtichState(); //获取设备列表 getDeviceList(deviceList); setSwitchStatus(); initNet(); wlanComponnetSettings(); if (!getSwitchBtnState() || deviceList.isEmpty() || !m_interface->isValid()) { hideLayout(ui->availableLayout); } // 有线网络断开或连接时刷新可用网络列表 connect(m_interface, SIGNAL(wlanactiveConnectionStateChanged(QString, QString, QString, int)), this, SLOT(onActiveConnectionChanged(QString, QString, QString, int)), Qt::QueuedConnection); // 无线网络新增时添加网络 connect(m_interface, SIGNAL(wlanAdd(QString, QStringList)), this, SLOT(onNetworkAdd(QString, QStringList)), Qt::QueuedConnection); // 删除无线网络 connect(m_interface, SIGNAL(wlanRemove(QString, QString)), this, SLOT(onNetworkRemove(QString, QString)), Qt::QueuedConnection); // 网卡插拔处理 connect(m_interface, SIGNAL(wirelessDeviceStatusChanged()), this, SLOT(onDeviceStatusChanged()), Qt::QueuedConnection); // 网卡name处理 connect(m_interface, SIGNAL(deviceNameChanged(QString, QString, int)), this, SLOT(onDeviceNameChanged(QString, QString, int)), Qt::QueuedConnection); connect(m_interface, SIGNAL(wirelessSwitchBtnChanged(bool)), this, SLOT(onSwitchBtnChanged(bool)), Qt::QueuedConnection); connect(m_interface, SIGNAL(timeToUpdate()), this, SLOT(updateList()), Qt::QueuedConnection); // 无线网络开关(使用空格) connect(m_wifiSwitch, SIGNAL(stateChanged(bool)), this, SLOT(switchStatusChanged(bool)),Qt::QueuedConnection); // 高级设置 connect(ui->detailBtn, &QPushButton::clicked, this, [=](bool checked) { Q_UNUSED(checked) UkccCommon::buriedSettings(QString("wlanconnect"), QString("Advanced settings"), QString("clicked")); runExternalApp(); }); //定时20s扫描 m_scanTimer = new QTimer(this); m_scanTimer->start(SCANTIMER); connect(m_scanTimer, &QTimer::timeout, this, &WlanConnect::reScan, Qt::QueuedConnection); reScan(); } void WlanConnect::switchStatusChanged(bool status) { m_interface->call(QStringLiteral("setWirelessSwitchEnable"), status); } void WlanConnect::reScan() { qDebug() << "time to rescan wifi"; if (m_interface != nullptr && m_interface->isValid()) { qDebug() << "[WlanConnect]call reScan" << __LINE__; m_interface->call("reScan"); qDebug() << "[WlanConnect]call reScan respond" << __LINE__; } } //更新列表顺序 void WlanConnect::updateList() { if (!getSwitchBtnState()) { return; } qDebug() << "update list"; if(m_interface != nullptr && m_interface->isValid()) { QMap> variantList = getWirelessList(); if (variantList.size() == 0) { qDebug() << "[WlanConnect]updateList " << " list empty"; return; } QMap>::iterator iter; for (iter = variantList.begin(); iter != variantList.end(); iter++) { if (deviceFrameMap.contains(iter.key())) { QList wifiList = iter.value(); resortWifiList(deviceFrameMap[iter.key()], wifiList); deviceFrameMap[iter.key()]->filletStyleChange(); } } } } void WlanConnect::resortWifiList(ItemFrame *frame, QList list) { if(nullptr == frame || frame->lanItemLayout->count() <= 0 || list.isEmpty()) { return; } qDebug() << "begin resort" << frame->deviceFrame->deviceLabel->text(); int frameIndex = 0; int listIndex = 1; if (list.at(0).size() > 1) { if (frame->itemMap.contains(list.at(0).at(0))) { frame->lanItemLayout->removeWidget(frame->itemMap[list.at(0).at(0)]); frame->lanItemLayout->insertWidget(0, frame->itemMap[list.at(0).at(0)]); qDebug() << "active resort insert position 0" << list.at(0).at(0); frame->itemMap[list.at(0).at(0)]->isAcitve = true; frame->itemMap[list.at(0).at(0)]->uuid = list.at(0).at(3); frame->uuid = list.at(0).at(3); frame->itemMap[list.at(0).at(0)]->statusLabel->setText(tr("connected")); if (list.at(0).size() > 5) { updateIcon(frame->itemMap[list.at(0).at(0)], list.at(0).at(1), list.at(0).at(2), list.at(0).at(4), list.at(0).at(5).toInt()); } frameIndex ++; } } else { qDebug() << " no active connection when resort"; if (!frame->uuid.isEmpty()) { QMap::iterator itemIter; for (itemIter = frame->itemMap.begin(); itemIter != frame->itemMap.end(); itemIter++) { if (itemIter.value()->uuid == frame->uuid ) { WlanItem * item= nullptr; item = itemIter.value(); qDebug() << "a active connect missing when resort"; itemIter.value()->uuid.clear(); itemActiveConnectionStatusChanged(item, DEACTIVATED); break; } } } frame->uuid.clear(); } for ( ; listIndex < list.size(); listIndex++) { if (frameIndex > frame->lanItemLayout->count() - 1) { return; } if (frame->itemMap.contains(list.at(listIndex).at(0))) { frame->lanItemLayout->removeWidget(frame->itemMap[list.at(listIndex).at(0)]); frame->lanItemLayout->insertWidget(frameIndex, frame->itemMap[list.at(listIndex).at(0)]); qDebug() << "custom resort " << list.at(listIndex).at(0) <<" insert position" << frameIndex; if (frame->itemMap[list.at(listIndex).at(0)]->isAcitve) { frame->itemMap[list.at(listIndex).at(0)]->isAcitve = false; frame->itemMap[list.at(listIndex).at(0)]->uuid.clear(); frame->itemMap[list.at(listIndex).at(0)]->statusLabel->setText(""); } if (list.at(listIndex).size() > 4) { updateIcon(frame->itemMap[list.at(listIndex).at(0)], list.at(listIndex).at(1), list.at(listIndex).at(2), list.at(listIndex).at(3), list.at(listIndex).at(4).toInt()); } frameIndex++; } else { qDebug() << "not find " << list.at(listIndex).at(0) << " in current list, ignore"; } } qDebug() << "resort finish"; } void WlanConnect::updateIcon(WlanItem *item, QString signalStrength, QString security, QString isApConnection, int category) { qDebug() << "updateIcon" << item->titileLabel->text()<<" security:"<isAcitve) { iconamePath = KApSymbolic; } else { iconamePath = wifiIcon(isLock, sign, category); } QIcon searchIcon = QIcon::fromTheme(iconamePath); item->iconLabel->setPixmap(searchIcon.pixmap(searchIcon.actualSize(QSize(ICON_SIZE)))); qDebug() << "updateIcon" << item->titileLabel->text() << " finish"; } //device add or remove void WlanConnect::onDeviceStatusChanged() { qDebug()<<"[WlanConnect]onDeviceStatusChanged"; QEventLoop eventloop; QTimer::singleShot(300, &eventloop, SLOT(quit())); eventloop.exec(); QStringList list; getDeviceList(list); QStringList removeList,addList; //remove的设备 for (int i = 0; i< deviceList.size(); ++i) { if (!list.contains(deviceList.at(i))) { qDebug() << "[WlanConnect]onDeviceStatusChanged " << deviceList.at(i) << "was removed"; removeList << deviceList.at(i); } } //add的设备 for (int i = 0; i< list.size(); ++i) { if (!deviceList.contains(list.at(i))) { qDebug() << "[WlanConnect]onDeviceStatusChanged " << list.at(i) << "was add"; addList << list.at(i); } } for (int i = 0; i < removeList.size(); ++i) { removeDeviceFrame(removeList.at(i)); } deviceList = list; setSwitchStatus(); for (int i = 0; i < addList.size(); ++i) { addDeviceFrame(addList.at(i)); initNetListFromDevice(addList.at(i)); } } void WlanConnect::onDeviceNameChanged(QString oldName, QString newName, int type) { if (WIRELESS_TYPE != type || !deviceFrameMap.contains(oldName) || !deviceList.contains(oldName)) { qDebug() << "[WlanConnect]onDeviceNameChanged no such device " << oldName; return; } if (deviceFrameMap.contains(newName) && deviceList.contains(newName)) { qDebug() << "[WlanConnect]onDeviceNameChanged already has device " << newName; return; } qDebug() << "[WlanConnect]onDeviceNameChanged " << oldName << "change to" << newName; removeDeviceFrame(oldName); removeDeviceFrame(newName); getDeviceList(deviceList); if (deviceList.contains(newName)) { addDeviceFrame(newName); initNetListFromDevice(newName); } } void WlanConnect::onSwitchBtnChanged(bool state) { if (getSwitchBtnState() == state) { return; } setSwitchBtnEnable(true); setSwitchBtnState(state); if (!getSwitchBtnState()) { hideLayout(ui->availableLayout); } else { showLayout(ui->availableLayout); } setSwitchStatus(); } //activeconnect status change void WlanConnect::onActiveConnectionChanged(QString deviceName, QString ssid, QString uuid, int status) { if (!getSwitchBtnState()) { return; } if (uuid.isEmpty()) { return; } WlanItem * item= nullptr; //device ssid 有可能均为空 if (deviceName.isEmpty() || ssid.isEmpty()) { if (status == ACTIVATING || status == ACTIVATED) { return; } QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if (uuid == iter.value()->uuid) { QMap::iterator itemIter; for (itemIter = iter.value()->itemMap.begin(); itemIter != iter.value()->itemMap.end(); itemIter++) { if (itemIter.value()->uuid == uuid) { item = itemIter.value(); if (status == DEACTIVATED) { itemIter.value()->uuid.clear(); } break; } } break; } else if (uuid != iter.value()->uuid && status == DEACTIVATED) { if (!ssid.isEmpty()) { QMap::iterator itemIter; for (itemIter = iter.value()->itemMap.begin(); itemIter != iter.value()->itemMap.end(); itemIter++) { if (itemIter.value()->titileLabel->text() == ssid && itemIter.value()->uuid == uuid) { itemActiveConnectionStatusChanged(itemIter.value(), status); break; } } } } } } else { if (!deviceFrameMap.contains(deviceName)) { return; } if (deviceFrameMap[deviceName]->itemMap.contains(ssid)) { item = deviceFrameMap[deviceName]->itemMap[ssid]; if (status == ACTIVATED || status == ACTIVATING) { deviceFrameMap[deviceName]->itemMap[ssid]->uuid = uuid; deviceFrameMap[deviceName]->uuid = uuid; if (status == ACTIVATED) { deviceFrameMap[deviceName]->lanItemLayout->removeWidget(item); deviceFrameMap[deviceName]->lanItemLayout->insertWidget(0,item); deviceFrameMap[deviceName]->filletStyleChange(); } } else if (status == DEACTIVATED) { deviceFrameMap[deviceName]->itemMap[ssid]->uuid.clear(); deviceFrameMap[deviceName]->uuid.clear(); //todo 断开后排序 现在等下次更新列表 自动排序 } } else { if (uuid == deviceFrameMap[deviceName]->uuid) { QMap::iterator itemIter; for (itemIter = deviceFrameMap[deviceName]->itemMap.begin(); itemIter != deviceFrameMap[deviceName]->itemMap.end(); itemIter++) { if (itemIter.value()->uuid == uuid) { item = itemIter.value(); if (status == DEACTIVATED) { itemIter.value()->uuid.clear(); deviceFrameMap[deviceName]->uuid.clear(); } break; } } } } } if (nullptr != item) { itemActiveConnectionStatusChanged(item, status); } } // wifi add void WlanConnect::onNetworkAdd(QString deviceName, QStringList wlanInfo) { qDebug()<<"[WlanConnect]onNetworkAdd "<< deviceName << " " << wlanInfo; if(!getSwitchBtnState() || deviceName.isEmpty()) { return; } if (!deviceList.contains(deviceName)) { qDebug() << "[WlanConnect]onNetworkAdd not contain " << deviceName << "then add"; deviceList.append(deviceName); addDeviceFrame(deviceName); onNetworkAdd(deviceName, wlanInfo); return; } bool isLock = true; if (wlanInfo.at(2) == "") { isLock = false; } else { isLock = true; } QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if (deviceName == iter.key()) { addOneWlanFrame(iter.value(), deviceName, wlanInfo.at(0), wlanInfo.at(1), "", isLock, false, WIRELESS_TYPE, wlanInfo.at(3), wlanInfo.at(3).toInt(), DEACTIVATED); } } } // wifi remove void WlanConnect::onNetworkRemove(QString deviceName, QString wlannName) { //当前无此设备 忽略 if (deviceName.isEmpty() || !deviceFrameMap.contains(deviceName)) { qDebug() << "[WlanConnect]recieve network remove,but no such device:" << deviceName; return; } qDebug()<<"[WlanConnect]Wifi remove device:" << deviceName << ",wlan name:" << wlannName; QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if (deviceName == iter.key()) { removeOneWlanFrame(iter.value(), deviceName, wlannName); } } } // 获取设备列表 void WlanConnect::getDeviceList(QStringList &list) { if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[WlanConnect]call getDeviceListAndEnabled" << __LINE__; QDBusReply reply = m_interface->call(QStringLiteral("getDeviceListAndEnabled"),1); qDebug() << "[WlanConnect]call getDeviceListAndEnabled respond" << __LINE__; if(!reply.isValid()) { qWarning() << "[WlanConnect]getWirelessDeviceList error:" << reply.error().message(); return; } QMap map; QVariantMap::const_iterator item = reply.value().cbegin(); while (item != reply.value().cend()) { map.insert(item.key(), item.value().toBool()); item ++; } //筛选已托管(managed)网卡 QMap::iterator iters; for (iters = map.begin(); iters != map.end(); ++iters) { if (iters.value() == true) { list << iters.key(); } } } void WlanConnect::initSwtichState() { if (m_interface == nullptr || !m_interface->isValid()) { return; } QDBusMessage result = m_interface->call("getWirelessSwitchBtnState"); qDebug() << "[WlanConnect]call getWirelessSwitchBtnState respond" << __LINE__; if(result.type() == QDBusMessage::ErrorMessage) { qWarning() << "[WlanConnect]getWirelessSwitchBtnState error:" << result.errorMessage(); return; } bool state = result.arguments().at(0).toBool(); setSwitchBtnEnable(true); setSwitchBtnState(state); } void WlanConnect::setSwitchBtnEnable(bool state) { if (m_wifiSwitch != nullptr) { m_wifiSwitch->setEnabled(state); } } bool WlanConnect::getSwitchBtnEnable() { if (m_wifiSwitch != nullptr) { return m_wifiSwitch->isEnabled(); } } void WlanConnect::setSwitchBtnState(bool state) { if (m_wifiSwitch != nullptr) { m_wifiSwitch->blockSignals(true); m_wifiSwitch->setChecked(state); m_wifiSwitch->blockSignals(false); } } bool WlanConnect::getSwitchBtnState() { if (m_wifiSwitch != nullptr) { return m_wifiSwitch->isChecked(); } } bool WlanConnect::LaunchApp(QString desktopFile) { QDBusInterface m_appManagerDbusInterface(KYLIN_APP_MANAGER_NAME, KYLIN_APP_MANAGER_PATH, KYLIN_APP_MANAGER_INTERFACE, QDBusConnection::sessionBus());//局部变量 if (!m_appManagerDbusInterface.isValid()) { qWarning()<<"m_appManagerDbusInterface init error"; return false; } else { QDBusReply reply =m_appManagerDbusInterface.call("LaunchApp",desktopFile); return reply; } } //初始化整体列表和单设备列表 void WlanConnect::initNet() { //先构建每个设备的列表头 for (int i = 0; i < deviceList.size(); ++i) { addDeviceFrame(deviceList.at(i)); } //再填充每个设备的列表 for (int i = 0; i < deviceList.size(); ++i) { initNetListFromDevice(deviceList.at(i)); } } //初始化设备列表 网卡标号问题? void WlanConnect::initNetListFromDevice(QString deviceName) { qDebug() << "[WlanConnect]initNetListFromDevice " << deviceName; if (!getSwitchBtnState()) { qDebug() << "[WlanConnect]initNetListFromDevice " << deviceName << " switch off"; return; } if (!deviceFrameMap.contains(deviceName)) { qDebug() << "[WlanConnect]initNetListFromDevice " << deviceName << " not exist"; return; } if (m_interface == nullptr || !m_interface->isValid()) { return; } QMap> variantList = getWirelessList(); if (variantList.size() == 0) { qDebug() << "[WlanConnect]initNetListFromDevice " << deviceName << " list empty"; return; } QMap>::iterator iter; for (iter = variantList.begin(); iter != variantList.end(); iter++) { if (deviceName == iter.key()) { QList wlanListInfo = iter.value(); if (wlanListInfo.size() <= 0) { break; } //处理列表 已连接 qDebug() << "[WlanConnect]initNetListFromDevice " << deviceName << " acitved wifi " << wlanListInfo.at(0); addActiveItem(deviceFrameMap[deviceName], deviceName, wlanListInfo.at(0)); //处理列表 未连接 for (int i = 1; i < wlanListInfo.length(); i++) { qDebug() << "[WlanConnect]initNetListFromDevice " << deviceName << " deacitved wifi " << wlanListInfo.at(i); addCustomItem(deviceFrameMap[deviceName], deviceName, wlanListInfo.at(i)); } } } return; } //高级设置 void WlanConnect::runExternalApp() { if (!LaunchApp("nm-connection-editor.desktop")){ QString cmd = "nm-connection-editor"; QProcess process(this); process.startDetached(cmd); } } //根据信号强度分级+安全性分图标 QString WlanConnect::wifiIcon(bool isLock, int strength, int category) { if (category == 0) { switch (strength) { case SIGNAL_EXCELLENT: return isLock ? KWifiLockSymbolic : KWifiSymbolic; case SIGNAL_GOOD: return isLock ? KWifiLockGood : KWifiGood; case SIGNAL_OK: return isLock ? KWifiLockOK : KWifiOK; case SIGNAL_LOW: return isLock ? KWifiLockLow : KWifiLow; case SIGNAL_NONE: return isLock ? KWifiLockNone : KWifiNone; default: return ""; } } else if (category == 1) { switch (strength) { case SIGNAL_EXCELLENT: return isLock ? KWifi6LockSymbolic : KWifi6Symbolic; case SIGNAL_GOOD: return isLock ? KWifi6LockGood : KWifi6Good; case SIGNAL_OK: return isLock ? KWifi6LockOK : KWifi6OK; case SIGNAL_LOW: return isLock ? KWifi6LockLow : KWifi6Low; case SIGNAL_NONE: return isLock ? KWifi6LockNone : KWifi6None; default: return ""; } } else if (category == 3) {//显示wifi7图标 switch (strength) { case SIGNAL_EXCELLENT: return isLock ? KWifi7LockSymbolic : KWifi7Symbolic; case SIGNAL_GOOD: return isLock ? KWifi7LockGood : KWifi7Good; case SIGNAL_OK: return isLock ? KWifi7LockOK : KWifi7OK; case SIGNAL_LOW: return isLock ? KWifi7LockLow : KWifi7Low; case SIGNAL_NONE: return isLock ? KWifi7LockNone : KWifi7None; default: return ""; } } else { switch (strength) { case SIGNAL_EXCELLENT: return isLock ? KWifi6PlusLockSymbolic : KWifi6PlusSymbolic; case SIGNAL_GOOD: return isLock ? KWifi6PlusLockGood : KWifi6PlusGood; case SIGNAL_OK: return isLock ? KWifi6PlusLockOK : KWifi6PlusOK; case SIGNAL_LOW: return isLock ? KWifi6PlusLockLow : KWifi6PlusLow; case SIGNAL_NONE: return isLock ? KWifi6PlusLockNone : KWifi6PlusNone; default: return ""; } } } //根据信号强度分级 int WlanConnect::setSignal(QString lv) { int signal = lv.toInt(); int signalLv = 0; if (signal > EXCELLENT_SIGNAL) { signalLv = 1; } else if (signal > GOOD_SIGNAL) { signalLv = 2; } else if (signal > OK_SIGNAL) { signalLv = 3; } else if (signal > LOW_SIGNAL) { signalLv = 4; } else { signalLv = 5; } return signalLv; } //隐藏 void WlanConnect::hideLayout(QVBoxLayout * layout) { for (int i = layout->layout()->count()-1; i >= 0; --i) { QLayoutItem *it = layout->layout()->itemAt(i); ItemFrame *itemFrame = qobject_cast(it->widget()); itemFrame->hide(); } } //显示 void WlanConnect::showLayout(QVBoxLayout * layout) { for (int i = layout->layout()->count()-1; i >= 0; --i) { QLayoutItem *it = layout->layout()->itemAt(i); ItemFrame *itemFrame = qobject_cast(it->widget()); itemFrame->show(); } } //获取应该插入哪个位置 int WlanConnect::sortWlanNet(QString deviceName, QString name, QString signal) { if (m_interface == nullptr || !m_interface->isValid()) { return 0; } QMap> variantList = getWirelessList(); QMap>::iterator iter; for (iter = variantList.begin(); iter != variantList.end(); iter++) { if (deviceName == iter.key()) { QList wlanListInfo = iter.value(); for (int i = 0; i < wlanListInfo.size(); i++) { if (name == wlanListInfo.at(i).at(0)) { return i; } } } } return 0; } void WlanConnect::activeConnect(QString netName, QString deviceName, int type) { if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[WlanConnect]call activateConnect" << __LINE__; m_interface->call("activateConnect",type, deviceName, netName); qDebug() << "[WlanConnect]call activateConnect respond" << __LINE__; } void WlanConnect::deActiveConnect(QString netName, QString deviceName, int type) { if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[WlanConnect]call deActivateConnect" << __LINE__; m_interface->call("deActivateConnect",type, deviceName, netName); qDebug() << "[WlanConnect]call deActivateConnect respond" << __LINE__; } //处理列表 已连接 void WlanConnect::addActiveItem(ItemFrame *frame, QString devName, QStringList infoList) { if (frame == nullptr) { return; } if (infoList.size() == 1) { return; } bool isLock = true; if (infoList.at(2) == "") { isLock = false; } else { isLock = true; } addOneWlanFrame(frame, devName, infoList.at(0), infoList.at(1), infoList.at(3), isLock, true, WIRELESS_TYPE, infoList.at(4), infoList.at(5).toInt(), ACTIVATED); } //处理列表 未连接 void WlanConnect::addCustomItem(ItemFrame *frame, QString devName, QStringList infoList) { if (frame == nullptr) { return; } bool isLock = true; if (infoList.at(2) == "") { isLock = false; } else { isLock = true; } addOneWlanFrame(frame, devName, infoList.at(0), infoList.at(1), "", isLock, false, WIRELESS_TYPE, infoList.at(3), infoList.at(4).toInt(), infoList.at(5).toInt()); } //增加设备 void WlanConnect::addDeviceFrame(QString devName) { qDebug() << "[WlanConnect]addDeviceFrame " << devName; ItemFrame *itemFrame = new ItemFrame(devName, pluginWidget); ui->availableLayout->addWidget(itemFrame); itemFrame->deviceFrame->deviceLabel->setText(tr("card")+/*QString("%1").arg(count)+*/":"+devName); deviceFrameMap.insert(devName, itemFrame); connect(itemFrame->addWlanWidget, &AddNetBtn::clicked, this, [=](){ UkccCommon::buriedSettings(QString("wlanconnect"), QString("Add wlan"), QString("clicked")); if (m_interface != nullptr && m_interface->isValid()) { qDebug() << "[NetConnect]call showAddOtherWlanWidget" << devName << __LINE__; m_interface->call(QStringLiteral("showAddOtherWlanWidget"), devName); qDebug() << "[NetConnect]call setDeviceEnable Respond" << __LINE__; } }); } //减少设备 void WlanConnect::removeDeviceFrame(QString devName) { qDebug() << "[WlanConnect]removeDeviceFrame " << devName; if (deviceFrameMap.contains(devName)) { ItemFrame *item = deviceFrameMap[devName]; if (item->lanItemFrame->layout() != NULL) { QLayoutItem* layoutItem; while ((layoutItem = item->lanItemFrame->layout()->takeAt(0)) != NULL) { delete layoutItem->widget(); delete layoutItem; layoutItem = nullptr; } item->itemMap.clear(); } delete item; item = nullptr; deviceFrameMap.remove(devName); } } //增加ap void WlanConnect::addOneWlanFrame(ItemFrame *frame, QString deviceName, QString name, QString signal, QString uuid, bool isLock, bool status, int type, QString isApConnection, int category, int activeStatus) { if (nullptr == frame) { return; } bool bApConnection = (isApConnection == IsApConnection); if (frame->itemMap.contains(name)) { qDebug() << "[WlanConnect]Already exist a wifi " << name << " in " << deviceName; return; } //设置单项的信息 int sign = setSignal(signal); WlanItem * wlanItem = new WlanItem(status, isLock, pluginWidget); QString iconamePath; if (bApConnection) { iconamePath = KApSymbolic; } else { iconamePath = wifiIcon(isLock, sign, category); } QIcon searchIcon = QIcon::fromTheme(iconamePath); wlanItem->iconLabel->setPixmap(searchIcon.pixmap(searchIcon.actualSize(QSize(ICON_SIZE)))); wlanItem->titileLabel->setText(name); if (status) { wlanItem->statusLabel->setText(tr("connected")); frame->uuid = uuid; wlanItem->uuid = uuid; } else { wlanItem->statusLabel->setText(""); } connect(wlanItem->infoLabel, &GrayInfoButton::clicked, this, [=]{ if (m_interface == nullptr || !m_interface->isValid()) { return; } UkccCommon::buriedSettings(QString("wlanconnect"), QString("info"), QString("clicked")); qDebug() << "[WlanConnect]call showPropertyWidget" << __LINE__; m_interface->call(QStringLiteral("showPropertyWidget"), deviceName, name); qDebug() << "[WlanConnect]call showPropertyWidget respond" << __LINE__; }); connect(wlanItem, &QPushButton::clicked, this, [=] { openKylinm(); }); //记录到deviceFrame的itemMap中 deviceFrameMap[deviceName]->itemMap.insert(name, wlanItem); int index; if (status) { index = 0; } else { index = sortWlanNet(deviceName, name, signal); } qDebug()<<"insert " << name << " to " << deviceName << " list, postion " << index; frame->lanItemLayout->insertWidget(index, wlanItem); frame->filletStyleChange(); if (activeStatus == ACTIVATING || activeStatus == DEACTIVATING) { itemActiveConnectionStatusChanged(wlanItem, activeStatus); } } //减少ap void WlanConnect::removeOneWlanFrame(ItemFrame *frame, QString deviceName, QString ssid) { if (nullptr == frame) { return; } if (frame->itemMap.contains(ssid)) { qDebug() << "[WlanConnect]removeOneWlanFrame " << deviceName << ssid; frame->lanItemLayout->removeWidget(frame->itemMap[ssid]); delete frame->itemMap[ssid]; frame->itemMap.remove(ssid); frame->filletStyleChange(); } } void WlanConnect::itemActiveConnectionStatusChanged(WlanItem *item, int status) { if (status == ACTIVATING) { item->startLoading(); } else if (status == ACTIVATED) { item->stopLoading(); item->statusLabel->clear(); item->statusLabel->setMinimumSize(36,36); item->statusLabel->setMaximumSize(16777215,16777215); item->statusLabel->setText(tr("connected")); item->isAcitve = true; } else if (status == DEACTIVATING) { item->startLoading(); } else if (status == DEACTIVATED) { item->stopLoading(); item->statusLabel->clear(); item->statusLabel->setMinimumSize(36,36); item->statusLabel->setMaximumSize(16777215,16777215); item->isAcitve = false; } } void WlanConnect::openKylinm() { QDBusInterface sidebarIfc("org.ukui.Sidebar", "/org/ukui/Sidebar", "org.ukui.Sidebar", QDBusConnection::sessionBus()); sidebarIfc.call("shortcutWidgetActive", "org.ukui.shortcut.network", false); } QMap> WlanConnect::getWirelessList() { QMap> map; QStringList list; getDeviceList(list); for (int i = 0; i < list.size(); ++i) { qDebug() << "[NetConnect]call getWirelessList" << __LINE__; QDBusReply reply = m_interface->call(QStringLiteral("getWirelessList"), list.at(i)); qDebug() << "[NetConnect]call getWirelessList respond" << __LINE__; if(!reply.isValid()) { qWarning() << "getWirelessList error:" << reply.error().message(); break; } QList llist; for (int j = 0; j < reply.value().size(); ++j) { llist << reply.value().at(j).toStringList(); } map.insert(list.at(i), llist); } return map; } void WlanConnect::showNoDeiceInfo(bool visible,QString text) { m_wirelessNoDeviceLabel->setText(text); if (visible) { QIcon warningIcon = QIcon::fromTheme(WarningIconName); m_wirelessNoDeviceIconLabel->setPixmap(warningIcon.pixmap(warningIcon.actualSize(QSize(ICON_SIZE)))); m_wirelessNoDeviceLabel->resize(m_wirelessNoDeviceLabel->sizeHint()); // 设置标签大小以适应内容 m_wirelessNoDeviceLabel->show(); m_wirelessNoDeviceIconLabel->show(); } else { m_wirelessNoDeviceLabel->hide(); m_wirelessNoDeviceIconLabel->hide(); } } bool WlanConnect::getWirelessSwitchBtnState() { if (m_interface == nullptr || !m_interface->isValid()) { return false; } QDBusReply reply = m_interface->call(QStringLiteral("getWirelessSwitchBtnState")); qDebug() << "[WlanConnect]call getWirelessSwitchBtnState respond" << __LINE__; if (!reply.isValid()) { qWarning() << "[WlanConnect]getWirelessSwitchBtnState error:" << reply.error().message(); return false; } return reply.value(); } void WlanConnect::setSwitchStatus() { setSwitchBtnEnable(true); bool status = getWirelessSwitchBtnState(); setSwitchBtnState(status); if (deviceList.isEmpty()) { setSwitchBtnState(false); setSwitchBtnEnable(false); } showNoDeiceInfo(false,tr("")); if (!getSwitchBtnState()) { hideLayout(ui->availableLayout); if (deviceList.isEmpty()) showNoDeiceInfo(true,tr("No wireless network card detected")); } else { showLayout(ui->availableLayout); } } QMap WlanConnect::getModuleHideStatus() { QDBusReply> reply_res; QDBusInterface iface(DBUSSERVICE_UKCC, DBUSPATH_UKCC, DBUSINTERFACE_UKCC, QDBusConnection::sessionBus()); if (iface.isValid()) { QDBusPendingCall pcall = iface.asyncCall("getModuleHideStatus"); pcall.waitForFinished(); QDBusMessage res = pcall.reply(); if (res.type() == QDBusMessage::ReplyMessage) { if (res.arguments().size() > 0) { reply_res = res; qInfo() << reply_res.value(); } } else { qWarning()<< res.errorName() << ": "<< res.errorMessage(); } } else { qWarning()<< "dbus isValid"; } return reply_res.value(); } void WlanConnect::wlanComponnetSettings() { QMap configData = getModuleHideStatus(); QString moduleSettings = configData.value("wlanconnectSettings").toString(); QStringList setItems = moduleSettings.split(","); foreach (QString setItem, setItems) { QStringList item = setItem.split(":"); if (item.at(0) == "wlanAdvanced") { ui->detailBtn->setVisible(item.at(1) == "true"); } } QString moduleEnable = configData.value("wlanconnectEnable").toString(); QStringList enableItems = moduleEnable.split(","); foreach (QString setItem, enableItems) { QStringList item = setItem.split(":"); if (item.at(0) == "wlanAdvanced") { ui->detailBtn->setEnabled(item.at(1) == "true"); } } } kylin-nm/plugins/netconnect/0000775000175000017500000000000015167651420015066 5ustar fengfengkylin-nm/plugins/netconnect/netconnect.cpp0000664000175000017500000013223415167651420017737 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "netconnect.h" #include "ui_netconnect.h" #include #include #include #include #include #include #include #define WIRED_TYPE 0 #define ITEMHEIGH 50 #define LAN_TYPE 0 #define CONTROL_CENTER_WIFI "org.ukui.control-center.wifi.switch" #define KYLIN_APP_MANAGER_NAME "com.kylin.AppManager" #define KYLIN_APP_MANAGER_PATH "/com/kylin/AppManager" #define KYLIN_APP_MANAGER_INTERFACE "com.kylin.AppManager" #define SYSTEM_DBUS_SERVICE "com.kylin.network.qt.systemdbus" #define SYSTEM_DBUS_PATH "/" #define SYSTEM_DBUS_INTERFACE "com.kylin.network.interface" const QString KLanSymbolic = "network-wired-connected-symbolic"; const QString NoNetSymbolic = "network-wired-disconnected-symbolic"; const QString WIRED_SWITCH = "wiredswitch"; const QByteArray GSETTINGS_SCHEMA = "org.ukui.kylin-nm.switch"; #define ACTIVATING 1 #define ACTIVATED 2 #define DEACTIVATING 3 #define DEACTIVATED 4 #define NO_MARGINS 0,0,0,0 #define TOP_MARGINS 0,8,0,0 #define MAIN_LAYOUT_MARGINS 0,0,0,8 #define SPACING 8 #define ICON_SIZE 16,16 bool sortByVal(const QPair &l, const QPair &r) { return (l.second < r.second); } void NetConnect::showDesktopNotify(const QString &message) { QDBusInterface iface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus()); QList args; args<<(tr("Settings")) <<((unsigned int) 0) <(); qDBusRegisterMetaType>(); QTranslator* translator = new QTranslator(this); translator->load("/usr/share/kylin-nm/netconnect/" + QLocale::system().name()); QApplication::installTranslator(translator); pluginName = tr("LAN"); pluginType = NETWORK; } /*fortify扫描报错,需要显示删除一下*/ NetConnect::~NetConnect() { QMap::iterator iter1; for (iter1 = deviceFrameMap.begin(); iter1 != deviceFrameMap.end(); iter1++) { ItemFrame *temp= iter1.value(); if(temp) { delete temp; } } deviceFrameMap.clear(); } QString NetConnect::plugini18nName() { return pluginName; } int NetConnect::pluginTypes() { return pluginType; } QWidget *NetConnect::pluginUi() { if (mFirstLoad) { mFirstLoad = false; ui = new Ui::NetConnect; pluginWidget = new QWidget; pluginWidget->setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(pluginWidget); m_interface = new QDBusInterface("com.kylin.network", "/com/kylin/network", "com.kylin.network", QDBusConnection::sessionBus()); if(!m_interface->isValid()) { qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } updatePluginShowSettings(); connect(m_interface, SIGNAL(deviceStatusChanged()), this, SLOT(updatePluginShowSettings()),Qt::QueuedConnection); qDBusRegisterMetaType>(); initSearchText(); initComponent(); netComponnetSettings(); } return pluginWidget; } const QString NetConnect::name() const { return QStringLiteral("netconnect"); } bool NetConnect::isEnable() const { //get isEnable QDBusInterface dbus("com.kylin.network", "/com/kylin/network", "com.kylin.network", QDBusConnection::sessionBus()); if (!dbus.isValid()) { return false; } QMap map; QDBusReply reply = dbus.call(QStringLiteral("getDeviceListAndEnabled"),0); if(!reply.isValid()) { qWarning() << "[NetConnect]getWiredDeviceList error:" << reply.error().message(); return false; } QVariantMap::const_iterator item = reply.value().cbegin(); while (item != reply.value().cend()) { map.insert(item.key(), item.value().toBool()); item ++; } bool isEnabled = !map.isEmpty(); const QByteArray schema("org.ukui.control-center.plugins"); if (QGSettings::isSchemaInstalled(schema)) { return isEnabled; } //get gsettings QGSettings *showSettings; QString path("/org/ukui/control-center/plugins/netconnect/"); showSettings = new QGSettings(schema, path.toUtf8()); QVariant enabledState = showSettings->get("show"); //set gsettings if (!enabledState.isValid() || enabledState.isNull()) { qWarning() << "QGSettins get plugin show status error"; } else { if (enabledState.toBool() != isEnabled) { showSettings->set("show", isEnabled); } } delete showSettings; showSettings = nullptr; return isEnabled; } bool NetConnect::isShowOnHomePage() const { return true; } QIcon NetConnect::icon() const { return QIcon::fromTheme("network-wired-symbolic"); } QString NetConnect::translationPath() const { return "/usr/share/kylin-nm/netconnect/%1.ts"; } void NetConnect::initSearchText() { //~ contents_path /netconnect/Advanced settings" ui->detailBtn->setText(tr("Advanced settings")); ui->titleLabel->setText(tr("LAN")); //~ contents_path /netconnect/open tr("open"); ui->openLabel->setText(tr("LAN")); } bool NetConnect::eventFilter(QObject *w, QEvent *e) { if (e->type() == QEvent::Enter) { if (w->findChild()) w->findChild()->setStyleSheet("QWidget{background: palette(button);border-radius:4px;}"); } else if (e->type() == QEvent::Leave) { if (w->findChild()) w->findChild()->setStyleSheet("QWidget{background: palette(base);border-radius:4px;}"); } // if (w == wiredSwitch) { // if (e->type() == QMouseEvent::MouseButtonRelease) { // if (!wiredSwitch->isCheckable()) { // showDesktopNotify(tr("No ethernet device avaliable")); // } else { // UkccCommon::buriedSettings(QString("netconnect"), QString("Open"), QString("settings"),wiredSwitch->isChecked()?"false":"true"); // if (m_interface != nullptr && m_interface->isValid()) { // m_interface->call(QStringLiteral("setWiredSwitchEnable"), !wiredSwitch->isChecked()); // } // return true; // } // } // } return QObject::eventFilter(w,e); } void NetConnect::initComponent() { wiredSwitch = new KSwitchButton(pluginWidget); ui->openWIifLayout->addWidget(wiredSwitch); ui->openWIifLayout->setContentsMargins(0,0,8,0); // ui->openWifiFrame->hide(); ui->detailLayOut->setContentsMargins(MAIN_LAYOUT_MARGINS); ui->verticalLayout_3->setContentsMargins(NO_MARGINS); ui->verticalLayout_3->setSpacing(8); ui->availableLayout->setSpacing(SPACING); ui->horizontalLayout->setContentsMargins(TOP_MARGINS); // wiredSwitch->installEventFilter(this); m_pSysBusIntfs = new QDBusInterface(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, QDBusConnection::systemBus()); if (m_pSysBusIntfs->isValid()) { setSwitchStatus(); QDBusConnection::systemBus().connect(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, "sysWiredMainSwitchChanged", this, SLOT(renewSwitchLayout(bool))); } else { wiredSwitch->blockSignals(true); wiredSwitch->setChecked(true); wiredSwitch->blockSignals(false); } // if (QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA)) { // m_switchGsettings = new QGSettings(GSETTINGS_SCHEMA); // setSwitchStatus(); // connect(m_switchGsettings, &QGSettings::changed, this, [=] (const QString &key) { // if (key == WIRED_SWITCH) { // setSwitchStatus(); // } // }); // } else { // wiredSwitch->blockSignals(true); // wiredSwitch->setChecked(true); // wiredSwitch->blockSignals(false); // qDebug()<<"[Netconnect] org.ukui.kylin-nm.switch is not installed!"; // } getDeviceStatusMap(deviceStatusMap); if (deviceStatusMap.isEmpty()) { qDebug() << "[Netconnect] no device exist when init, set switch disable"; wiredSwitch->setChecked(false); wiredSwitch->setCheckable(false); } initNet(); if (!wiredSwitch->isChecked() || deviceStatusMap.isEmpty() || !m_interface->isValid()) { hideLayout(ui->availableLayout); } // 有线网络断开或连接时刷新可用网络列表 connect(m_interface, SIGNAL(lanActiveConnectionStateChanged(QString, QString, int)), this, SLOT(onActiveConnectionChanged(QString, QString, int)), Qt::QueuedConnection); //有线网络新增时添加网络 connect(m_interface, SIGNAL(lanAdd(QString, QStringList)), this, SLOT(onLanAdd(QString, QStringList)), Qt::QueuedConnection); //删除有线网络 connect(m_interface, SIGNAL(lanRemove(QString)), this, SLOT(onLanRemove(QString)), Qt::QueuedConnection); //更新有线网络 connect(m_interface, SIGNAL(lanUpdate(QString, QStringList)), this, SLOT(updateLanInfo(QString, QStringList)),Qt::QueuedConnection); //网卡插拔处理 connect(m_interface, SIGNAL(deviceStatusChanged()), this, SLOT(onDeviceStatusChanged()),Qt::QueuedConnection); //网卡name处理 connect(m_interface, SIGNAL(deviceNameChanged(QString, QString, int)), this, SLOT(onDeviceNameChanged(QString, QString, int)),Qt::QueuedConnection); connect(ui->detailBtn, &QPushButton::clicked, this, [=](bool checked) { Q_UNUSED(checked) UkccCommon::buriedSettings(QString("netconnect"), QString("Advanced settings"), QString("clicked")); runExternalApp(); }); connect(wiredSwitch, &KSwitchButton::clicked, this, &NetConnect::wiredSwitchSLot); } void NetConnect::wiredSwitchSLot(bool checked) { if (!wiredSwitch->isCheckable()) { showDesktopNotify(tr("No ethernet device avaliable")); return; } UkccCommon::buriedSettings(QString("netconnect"), QString("Open"), QString("settings"),wiredSwitch->isChecked()?"false":"true"); if (m_pSysBusIntfs == nullptr || !m_pSysBusIntfs->isValid()) return; m_pSysBusIntfs->call(QStringLiteral("setWiredMainSwitch"), checked); if (checked) { showLayout(ui->availableLayout); //后续切换到sessiondbus上,进行处理 QMap::iterator iter1; for (iter1 = deviceFrameMap.begin(); iter1 != deviceFrameMap.end(); iter1++) { //set device autoconnect qWarning() << Q_FUNC_INFO << __LINE__ << iter1.key() << checked; setDeviceAutoConnectState(iter1.key(),checked); } //后续切换到sessiondbus上,进行处理 return; } hideLayout(ui->availableLayout); //后续切换到sessiondbus上,进行处理 QMap::iterator iter1; for (iter1 = deviceFrameMap.begin(); iter1 != deviceFrameMap.end(); iter1++) { QMap::iterator iter2; for (iter2 = iter1.value()->itemMap.begin(); iter2 != iter1.value()->itemMap.end(); iter2++) { if (iter2.value()->isAcitve) { deActiveConnect(iter2.value()->uuid, iter1.value()->deviceFrame->dropDownLabel->m_devName, WIRED_TYPE); } } //set device autoconnect qWarning() << Q_FUNC_INFO << __LINE__ << iter1.key() << checked; setDeviceAutoConnectState(iter1.key(),checked); } //后续切换到sessiondbus上,进行处理 } void NetConnect::renewSwitchLayout(bool enable) { qDebug() << Q_FUNC_INFO << __LINE__ << enable; // wiredSwitch->blockSignals(true); wiredSwitch->setChecked(enable); // wiredSwitch->blockSignals(false); if (!enable) { hideLayout(ui->availableLayout); QMap::iterator iter1; for (iter1 = deviceFrameMap.begin(); iter1 != deviceFrameMap.end(); iter1++) { QMap::iterator iter2; for (iter2 = iter1.value()->itemMap.begin(); iter2 != iter1.value()->itemMap.end(); iter2++) { if (iter2.value()->isAcitve) { deActiveConnect(iter2.value()->uuid, iter1.value()->deviceFrame->dropDownLabel->m_devName, WIRED_TYPE); } } } } else { showLayout(ui->availableLayout); } } //获取网卡列表 void NetConnect::getDeviceStatusMap(QMap &map) { if (m_interface == nullptr || !m_interface->isValid()) { return; } map.clear(); qDebug() << "[NetConnect]call getDeviceListAndEnabled" << __LINE__; QDBusReply reply = m_interface->call(QStringLiteral("getDeviceListAndEnabled"),0); qDebug() << "[NetConnect]call getDeviceListAndEnabled Respond" << __LINE__; if(!reply.isValid()) { qWarning() << "[NetConnect]getWiredDeviceList error:" << reply.error().message(); return; } QVariantMap::const_iterator item = reply.value().cbegin(); while (item != reply.value().cend()) { map.insert(item.key(), item.value().toBool()); item ++; } } //lanUpdate void NetConnect::updateLanInfo(QString deviceName, QStringList lanInfo) { //she bei gui shu bian hua && you xian ming cheng bian hua QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if (deviceName.isEmpty()) { //变为无指定网卡,所有列表都要添加 if (!iter.value()->itemMap.contains(lanInfo.at(1))) { qDebug() << "[NetConnect]" << lanInfo.at(0) << " change to device none, add every list"; addOneLanFrame(iter.value(), iter.key(), lanInfo); } else { if (iter.value()->itemMap[lanInfo.at(1)]->titileLabel->text() != lanInfo.at(0)) { qDebug() << "[NetConnect]" << iter.key() << iter.value()->itemMap[lanInfo.at(1)]->titileLabel->text() << "change to" << lanInfo.at(0); iter.value()->itemMap[lanInfo.at(1)]->titileLabel->setText(lanInfo.at(0)); } } } else { if (iter.key() != deviceName) { qDebug() << "[NetConnect]" << lanInfo.at(0) << " not belongs to " << iter.key(); removeOneLanFrame(iter.value(), deviceName, lanInfo.at(1)); } else { if (!iter.value()->itemMap.contains(lanInfo.at(1))) { qDebug() << "[NetConnect]" << lanInfo.at(0) << " now belongs to " << deviceName; addOneLanFrame(iter.value(), deviceName, lanInfo); } else { qDebug() << "[NetConnect]" << deviceName << iter.value()->itemMap[lanInfo.at(1)]->titileLabel->text() << "change to" << lanInfo.at(0); if (iter.value()->itemMap[lanInfo.at(1)]->titileLabel->text() != lanInfo.at(0)) { iter.value()->itemMap[lanInfo.at(1)]->titileLabel->setText(lanInfo.at(0)); } } } } } } //总开关 void NetConnect::setSwitchStatus() { QDBusReply reply = m_pSysBusIntfs->call("getWiredMainSwitch"); if (reply.isValid()) { bool status = reply.value(); renewSwitchLayout(status); } else { qWarning () << "switch init dbus reply invalid"; } // if (QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA)) { // bool status = m_switchGsettings->get(WIRED_SWITCH).toBool(); // wiredSwitch->blockSignals(true); // wiredSwitch->setChecked(status); // wiredSwitch->blockSignals(false); // if (!status) { // hideLayout(ui->availableLayout); // } else { // showLayout(ui->availableLayout); // } // } else { // qDebug()<<"[netconnect] org.ukui.kylin-nm.switch is not installed!"; // } } //总体隐藏 void NetConnect::hideLayout(QVBoxLayout * layout) { for (int i = layout->layout()->count()-1; i >= 0; --i) { QLayoutItem *it = layout->layout()->itemAt(i); ItemFrame *itemFrame = qobject_cast(it->widget()); itemFrame->hide(); } } //总体显示 void NetConnect::showLayout(QVBoxLayout * layout) { for (int i = layout->layout()->count()-1; i >= 0; --i) { QLayoutItem *it = layout->layout()->itemAt(i); ItemFrame *itemFrame = qobject_cast(it->widget()); itemFrame->show(); } } //初始化 void NetConnect::initNet() { //先构建每个设备的列表头 QStringList deviceList = deviceStatusMap.keys(); for (int i = 0; i < deviceList.size(); ++i) { addDeviceFrame(deviceList.at(i)); } //再填充每个设备的列表 for (int i = 0; i < deviceList.size(); ++i) { initNetListFromDevice(deviceList.at(i)); initDeviceConnectivity(deviceList.at(i)); } } //刪除 void NetConnect::deleteOneLan(QString ssid, int type) { qDebug() << "[NetConnect]call deleteConnect" << __LINE__; m_interface->call(QStringLiteral("deleteConnect"), type, ssid); qDebug() << "[NetConnect]call deleteConnect respond" << __LINE__; } void NetConnect::runExternalApp() { if (!LaunchApp("nm-connection-editor.desktop")){ QString cmd = "nm-connection-editor"; QProcess process(this); process.startDetached(cmd); } } //激活 void NetConnect::activeConnect(QString ssid, QString deviceName, int type) { if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[NetConnect]call activateConnect" << __LINE__; m_interface->call(QStringLiteral("activateConnect"),type, deviceName, ssid); qDebug() << "[NetConnect]call activateConnect respond" << __LINE__; } //断开 void NetConnect::deActiveConnect(QString ssid, QString deviceName, int type) { if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[NetConnect]call deActivateConnect" << __LINE__; m_interface->call(QStringLiteral("deActivateConnectConcise"),type, true, deviceName, ssid); qDebug() << "[NetConnect]call deActivateConnect respond" << __LINE__; } //set void NetConnect::setDeviceAutoConnectState(QString deviceName, bool state) { if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[NetConnect]call setDeviceAutoConnectState" << __LINE__; m_interface->call(QStringLiteral("setDeviceAutoConnectState"),deviceName, state); qDebug() << "[NetConnect]call setDeviceAutoConnectState respond" << __LINE__; } //初始化设备列表 网卡标号问题? void NetConnect::initNetListFromDevice(QString deviceName) { qDebug() << "[NetConnect]initNetListFromDevice " << deviceName; if (!deviceFrameMap.contains(deviceName)) { qDebug() << "[NetConnect]initNetListFromDevice " << deviceName << " not exist"; return; } if (m_interface == nullptr || !m_interface->isValid()) { return; } QMap> variantList = getWiredList(); if (variantList.size() == 0) { qDebug() << "[NetConnect]initNetListFromDevice " << deviceName << " list empty"; return; } QMap>::iterator iter; for (iter = variantList.begin(); iter != variantList.end(); iter++) { if (deviceName == iter.key()) { QList wlanListInfo = iter.value(); //处理列表 已连接 qDebug() << "[NetConnect]initNetListFromDevice " << deviceName << " acitved lan " << wlanListInfo.at(0); addLanItem(deviceFrameMap[deviceName], deviceName, wlanListInfo.at(0), true); //处理列表 未连接 for (int i = 1; i < wlanListInfo.length(); i++) { qDebug() << "[NetConnect]initNetListFromDevice " << deviceName << " deacitved lan " << wlanListInfo.at(i); addLanItem(deviceFrameMap[deviceName], deviceName, wlanListInfo.at(i), false); } } } return; } //初始化时添加一个项 不考虑顺序 void NetConnect::addLanItem(ItemFrame *frame, QString devName, QStringList infoList, bool isActived) { if (frame == nullptr) { return; } if (infoList.size() == 1) { return; } LanItem * lanItem = new LanItem(isActived, pluginWidget); QString iconPath = KLanSymbolic; // 判断是否为pppoe if (isActived) { lanItem->statusLabel->setText(tr("connected")); } else { lanItem->statusLabel->setText(tr("not connected")); } QIcon searchIcon = QIcon::fromTheme(iconPath); // if (iconPath != KLanSymbolic && iconPath != NoNetSymbolic) { // lanItem->iconLabel->setProperty("useIconHighlightEffect", 0x10); // } if(isDslConnection(infoList.at(1))){ searchIcon = QIcon::fromTheme("ukui-dial-up-symbolic"); } lanItem->iconLabel->setPixmap(searchIcon.pixmap(searchIcon.actualSize(QSize(ICON_SIZE)))); lanItem->titileLabel->setText(infoList.at(0)); lanItem->uuid = infoList.at(1); lanItem->dbusPath = infoList.at(2); connect(lanItem->infoLabel, &GrayInfoButton::clicked, this, [=]{ // open landetail page if (m_interface == nullptr || !m_interface->isValid()) { return; } UkccCommon::buriedSettings(QString("netconnect"), QString("info"), QString("clicked")); qDebug() << "[NetConnect]call showPropertyWidget" << __LINE__; m_interface->call(QStringLiteral("showPropertyWidget"), devName, infoList.at(1)); qDebug() << "[NetConnect]call showPropertyWidget respond" << __LINE__; }); lanItem->isAcitve = isActived; connect(lanItem, &QPushButton::clicked, this, [=] { openKylinm(); }); //记录到deviceFrame的itemMap中 deviceFrameMap[devName]->itemMap.insert(infoList.at(1), lanItem); qDebug()<<"insert " << infoList.at(1) << " to " << devName << " list"; frame->lanItemLayout->addWidget(lanItem); } //增加设备 void NetConnect::addDeviceFrame(QString devName) { if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[NetConnect]addDeviceFrame " << devName; qDebug() << "[NetConnect]call getDeviceListAndEnabled" << __LINE__; QDBusReply reply = m_interface->call(QStringLiteral("getDeviceListAndEnabled"),0); qDebug() << "[NetConnect]call getDeviceListAndEnabled Respond" << __LINE__; if(!reply.isValid()) { qWarning() << "[NetConnect]getWiredDeviceList error:" << reply.error().message(); return; } QMap map; QVariantMap::const_iterator item = reply.value().cbegin(); while (item != reply.value().cend()) { map.insert(item.key(), item.value().toBool()); item ++; } bool enable = true; if (map.contains(devName)) { enable = map[devName]; } ItemFrame *itemFrame = new ItemFrame(devName, pluginWidget); ui->availableLayout->addWidget(itemFrame); itemFrame->deviceFrame->deviceLabel->setText(tr("card")+/*QString("%1").arg(count)+*/":"+devName); itemFrame->deviceFrame->deviceSwitch->setChecked(enable); if (enable) { itemFrame->lanItemFrame->show(); itemFrame->deviceFrame->dropDownLabel->show(); } else { itemFrame->lanItemFrame->hide(); itemFrame->deviceFrame->dropDownLabel->hide(); itemFrame->deviceFrame->dropDownLabel->setDropDownStatus(false); } deviceFrameMap.insert(devName, itemFrame); qDebug() << "[NetConnect]deviceFrameMap insert" << devName; // connect(itemFrame->deviceFrame, &DeviceFrame::deviceSwitchClicked ,this, [=] (bool checked) { // UkccCommon::buriedSettings(QString("netconnect"), "device open", QString("settings"), checked?"true":"fasle"); // qDebug() << "[NetConnect]call setDeviceEnable" << devName << checked << __LINE__; // m_interface->call(QStringLiteral("setDeviceEnable"), devName, checked); // if (m_pSysBusIntfs->isValid()) { // } // qDebug() << "[NetConnect]call setDeviceEnable Respond" << __LINE__; // }); connect(itemFrame->deviceFrame->deviceSwitch, &KSwitchButton::clicked, this, [=] (bool checked) { if (checked) { qDebug() << "[NetConnect]set " << devName << "status" << true; itemFrame->lanItemFrame->show(); itemFrame->deviceFrame->dropDownLabel->show(); itemFrame->addLanWidget->show(); itemFrame->deviceFrame->dropDownLabel->setDropDownStatus(true); deviceStatusMap[devName] = true; } else { qDebug() << "[NetConnect]set " << devName << "status" << false; itemFrame->lanItemFrame->hide(); itemFrame->deviceFrame->dropDownLabel->hide(); itemFrame->addLanWidget->hide(); deviceStatusMap[devName] = false; QMap::iterator iter; for (iter = deviceFrameMap.value(devName)->itemMap.begin(); iter != deviceFrameMap.value(devName)->itemMap.end(); iter++) { if (iter.value()->isAcitve) { deActiveConnect(iter.value()->uuid, devName, WIRED_TYPE); } } } m_pSysBusIntfs->call(QStringLiteral("setDeviceSwitch"), devName, checked); }); connect(itemFrame->addLanWidget, &AddNetBtn::clicked, this, [=](){ UkccCommon::buriedSettings(pluginName, "Add net", QString("clicked")); if (m_interface != nullptr && m_interface->isValid()) { qDebug() << "[NetConnect]call showCreateWiredConnectWidget" << devName << __LINE__; m_interface->call(QStringLiteral("showCreateWiredConnectWidget"), devName); qDebug() << "[NetConnect]call setDeviceEnable Respond" << __LINE__; } }); } //减少设备 void NetConnect::removeDeviceFrame(QString devName) { qDebug() << "[NetConnect]removeDeviceFrame " << devName; if (deviceFrameMap.contains(devName)) { ItemFrame *item = deviceFrameMap[devName]; if (item->lanItemFrame->layout() != NULL) { QLayoutItem* layoutItem; while ((layoutItem = item->lanItemFrame->layout()->takeAt(0)) != NULL) { delete layoutItem->widget(); delete layoutItem; layoutItem = nullptr; } item->itemMap.clear(); } delete item; item = nullptr; deviceFrameMap.remove(devName); qDebug() << "[NetConnect]deviceFrameMap remove" << devName; } } //device add or remove================================= void NetConnect::onDeviceStatusChanged() { qDebug()<<"[NetConnect]onDeviceStatusChanged"; QEventLoop eventloop; QTimer::singleShot(300, &eventloop, SLOT(quit())); eventloop.exec(); QStringList list; QMap map; getDeviceStatusMap(map); list = map.keys(); QStringList removeList; QMap addMap; //remove的设备 for (int i = 0; i< deviceStatusMap.keys().size(); ++i) { if (!list.contains(deviceStatusMap.keys().at(i))) { qDebug() << "[NetConnect]onDeviceStatusChanged " << deviceStatusMap.keys().at(i) << "was removed"; removeList << deviceStatusMap.keys().at(i); } } //add的设备 for (int i = 0; i< list.size(); ++i) { if (!deviceStatusMap.keys().contains(list.at(i))) { qDebug() << "[NetConnect]onDeviceStatusChanged " << list.at(i) << "was add, init status" << map[list.at(i)]; addMap.insert(list.at(i),map[list.at(i)]); } } for (int i = 0; i < removeList.size(); ++i) { removeDeviceFrame(removeList.at(i)); } QStringList addList = addMap.keys(); for (int i = 0; i < addList.size(); ++i) { qDebug() << "add a device " << addList.at(i) << "status" << map[addList.at(i)]; addDeviceFrame(addList.at(i)); initNetListFromDevice(addList.at(i)); } deviceStatusMap = map; if (deviceStatusMap.isEmpty()) { wiredSwitch->setChecked(false); wiredSwitch->setCheckable(false); } else { wiredSwitch->setCheckable(true); setSwitchStatus(); } QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if (deviceStatusMap.contains(iter.key())) { if (iter.value()->deviceFrame->deviceSwitch->isChecked() != deviceStatusMap[iter.key()]) { iter.value()->deviceFrame->deviceSwitch->setChecked(deviceStatusMap[iter.key()]); } } } } void NetConnect::onDeviceNameChanged(QString oldName, QString newName, int type) { if (WIRED_TYPE != type || !deviceFrameMap.contains(oldName) || !deviceStatusMap.contains(oldName)) { qDebug() << "[NetConnect]onDeviceNameChanged no such device " << oldName; return; } if (deviceFrameMap.contains(newName) && deviceStatusMap.contains(newName)) { qDebug() << "[NetConnect]onDeviceNameChanged already has device " << newName; return; } qDebug() << "[NetConnect]onDeviceNameChanged " << oldName << "change to" << newName; //shan chu chong jian removeDeviceFrame(oldName); removeDeviceFrame(newName); getDeviceStatusMap(deviceStatusMap); if (deviceStatusMap.contains(newName)) { addDeviceFrame(newName); initNetListFromDevice(newName); } } //wifi add=============================================================== void NetConnect::onLanAdd(QString deviceName, QStringList lanInfo) { qDebug()<<"[NetConnect]onLanAdd "<< deviceName << " " << lanInfo; if (!deviceName.isEmpty() && !deviceStatusMap.contains(deviceName)) { return; } QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if (deviceName.isEmpty()) { qDebug() << "[NetConnect]onLanAdd every list" << iter.key(); addOneLanFrame(iter.value(), iter.key(), lanInfo); } else if (deviceName == iter.key()) { qDebug() << "[NetConnect]onLanAdd "<< deviceName; addOneLanFrame(iter.value(), deviceName, lanInfo); break; } } } //wifi remove ============================================================= void NetConnect::onLanRemove(QString lanPath) { //开关已关闭 忽略 // if (!wifiSwtch->isChecked()) { // qDebug() << "[NetConnect]recieve network remove,but wireless switch is off"; // return; // } qDebug()<<"[NetConnect]lan remove " << "dbus path:" << lanPath; QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { QMap::iterator itemIter; for (itemIter = iter.value()->itemMap.begin(); itemIter != iter.value()->itemMap.end(); itemIter++) { if (itemIter.value()->dbusPath == lanPath) { qDebug()<<"[NetConnect]lan remove " << lanPath << " find in " << itemIter.value()->titileLabel->text(); QString key = itemIter.key(); iter.value()->lanItemLayout->removeWidget(itemIter.value()); delete itemIter.value(); iter.value()->itemMap.remove(key); break; } } } } //增加一项 void NetConnect::addOneLanFrame(ItemFrame *frame, QString deviceName, QStringList infoList) { if (nullptr == frame) { return; } if (frame->itemMap.contains(infoList.at(1))) { qDebug() << "[NetConnect]Already exist a lan " << infoList.at(1) << " in " << deviceName; return; } qDebug() << "[NetConnect]addOneLanFrame" << deviceName << infoList.at(0); QString connName = infoList.at(0); QString connUuid = infoList.at(1); QString connDbusPath = infoList.at(2); LanItem * lanItem = new LanItem(pluginWidget); QString iconPath; iconPath = KLanSymbolic; lanItem->statusLabel->setText(tr("not connected")); QIcon searchIcon = QIcon::fromTheme(iconPath); // if (iconPath != KLanSymbolic && iconPath != NoNetSymbolic) { // lanItem->iconLabel->setProperty("useIconHighlightEffect", 0x10); // } if(isDslConnection(connUuid)){ searchIcon = QIcon::fromTheme("ukui-dial-up-symbolic"); } lanItem->iconLabel->setPixmap(searchIcon.pixmap(searchIcon.actualSize(QSize(ICON_SIZE)))); lanItem->titileLabel->setText(connName); lanItem->uuid = connUuid; lanItem->dbusPath = connDbusPath; connect(lanItem->infoLabel, &GrayInfoButton::clicked, this, [=]{ // open landetail page if (m_interface == nullptr || !m_interface->isValid()) { return; } UkccCommon::buriedSettings(QString("netconnect"), QString("info"), QString("clicked")); qDebug() << "[NetConnect]call showPropertyWidget" << deviceName << connUuid << __LINE__; m_interface->call(QStringLiteral("showPropertyWidget"), deviceName, connUuid); qDebug() << "[NetConnect]call showPropertyWidget respond" << __LINE__; }); lanItem->isAcitve = false; connect(lanItem, &QPushButton::clicked, this, [=] { openKylinm(); }); //记录到deviceFrame的itemMap中 deviceFrameMap[deviceName]->itemMap.insert(connUuid, lanItem); int index = getInsertPos(connName, deviceName); qDebug()<<"[NetConnect]addOneLanFrame " << connName << " to " << deviceName << " list at pos:" << index; frame->lanItemLayout->insertWidget(index, lanItem); } void NetConnect::removeOneLanFrame(ItemFrame *frame, QString deviceName, QString uuid) { if (nullptr == frame) { return; } if (!frame->itemMap.contains(uuid)) { qDebug() << "[NetConnect]not exist a lan " << uuid << " in " << deviceName; return; } qDebug()<<"[NetConnect]removeOneLanFrame " << uuid << " find in " << deviceName; frame->lanItemLayout->removeWidget(frame->itemMap[uuid]); delete frame->itemMap[uuid]; frame->itemMap.remove(uuid); } //activeconnect status change void NetConnect::onActiveConnectionChanged(QString deviceName, QString uuid, int status) { if (uuid.isEmpty()) { qDebug() << "[NetConnect]onActiveConnectionChanged but uuid is empty"; return; } qDebug() << "[NetConnect]onActiveConnectionChanged " << deviceName << uuid << status; LanItem * item= nullptr; if (deviceName.isEmpty()) { if (status != DEACTIVATED) { return; } //断开时 设备为空 说明此有线未指定设备 添加到所有列表中 QStringList infoList; QMap::iterator iters; for (iters = deviceFrameMap.begin(); iters != deviceFrameMap.end(); iters++) { if (iters.value()->itemMap.contains(uuid)) { item = iters.value()->itemMap[uuid]; infoList << item->titileLabel->text() << item->uuid << item->dbusPath; //若断开连接,需要把网卡下的item全部赋为未连接 item->setConnectivityWarn(ConnectivityType::NoConnectivity); //为断开则重新插入 int index = getInsertPos(item->titileLabel->text(), iters.key()); qDebug() << "[NetConnect]reinsert" << item->titileLabel->text() << "pos" << index << "in" << iters.key() << "because status changes to deactive"; deviceFrameMap[iters.key()]->lanItemLayout->removeWidget(item); deviceFrameMap[iters.key()]->lanItemLayout->insertWidget(index,item); itemActiveConnectionStatusChanged(item, status); } } //添加到所有列表中 if (!infoList.isEmpty()) { QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if (!iter.value()->itemMap.contains(uuid)) { addOneLanFrame(iter.value(), iter.key(), infoList); } } } } else { if (deviceFrameMap.contains(deviceName)) { if (deviceFrameMap[deviceName]->itemMap.contains(uuid)) { item = deviceFrameMap[deviceName]->itemMap[uuid]; if (status == ACTIVATED) { //为已连接则放到第一个 deviceFrameMap[deviceName]->lanItemLayout->removeWidget(item); deviceFrameMap[deviceName]->lanItemLayout->insertWidget(0,item); } else if (status == DEACTIVATED) { //为断开则重新插入 int index = getInsertPos(item->titileLabel->text(), deviceName); qDebug() << "[NetConnect]reinsert" << item->titileLabel->text() << "pos" << index << "in" << deviceName << "because status changes to deactive"; deviceFrameMap[deviceName]->lanItemLayout->removeWidget(item); deviceFrameMap[deviceName]->lanItemLayout->insertWidget(index,item); } itemActiveConnectionStatusChanged(item, status); } } else { if (status == ACTIVATED || status == DEACTIVATED) { //虚拟网卡处理 QMap::iterator iters; for (iters = deviceFrameMap.begin(); iters != deviceFrameMap.end(); iters++) { if (iters.value()->itemMap.contains(uuid)) { removeOneLanFrame(iters.value(), iters.key(), uuid); } } } } } qDebug() << "onActiveConnectionChanged deviceName = " << deviceName; initDeviceConnectivity(deviceName); } void NetConnect::initDeviceConnectivity(QString deviceName) { if (!deviceFrameMap.contains(deviceName)) { return; } if (m_interface == nullptr || !m_interface->isValid()) { return; } QDBusReply reply = m_interface->call(QStringLiteral("getDeviceConnectivity"), deviceName); if (!reply.isValid()) { return; } updateDeviceFrameFromConnectivity(deviceFrameMap[deviceName], (ConnectivityType)reply.value()); } void NetConnect::updateDeviceFrameFromConnectivity(ItemFrame *frame, ConnectivityType type) { if (frame->itemMap.isEmpty()) { return; } //modify ui QMap ::iterator iter; for (iter = frame->itemMap.begin(); iter != frame->itemMap.end(); iter++) { if (iter.value()->isAcitve) { iter.value()->setNetworkCheckFrameHidden(false); iter.value()->setConnectivityWarn(type); } else { iter.value()->setNetworkCheckFrameHidden(true); } } } void NetConnect::itemActiveConnectionStatusChanged(LanItem *item, int status) { // QString iconPath = NoNetSymbolic; if (status == ACTIVATING) { item->startLoading(); } else if (status == ACTIVATED) { item->stopLoading(); // iconPath = KLanSymbolic; item->statusLabel->clear(); item->statusLabel->setMinimumSize(36,36); item->statusLabel->setMaximumSize(16777215,16777215); item->statusLabel->setText(tr("connected")); item->isAcitve = true; } else if (status == DEACTIVATING) { item->startLoading(); } else { item->stopLoading(); item->statusLabel->setMinimumSize(36,36); item->statusLabel->setMaximumSize(16777215,16777215); item->statusLabel->clear(); item->isAcitve = false; item->statusLabel->setText(tr("not connected")); } } void NetConnect::openKylinm() { QDBusInterface sidebarIfc("org.ukui.Sidebar", "/org/ukui/Sidebar", "org.ukui.Sidebar", QDBusConnection::sessionBus()); sidebarIfc.call("shortcutWidgetActive", "org.ukui.shortcut.network", false); } void NetConnect::netComponnetSettings() { QDBusInterface m_interface( "org.ukui.ukcc.session", "/", "org.ukui.ukcc.session.interface", QDBusConnection::sessionBus()); QDBusReply reply = m_interface.call("getModuleHideStatus"); if (!reply.isValid()) { qDebug()<<"execute dbus method getModuleHideStatus failed"; } QMap configData = reply.value(); QString moduleSettings = configData.value("netconnctSettings").toString(); QStringList setItems = moduleSettings.split(","); foreach (QString setItem, setItems) { QStringList item = setItem.split(":"); if (item.at(0) == "wlanAdvanced") { ui->detailBtn->setVisible(item.at(1) == "true"); } } QString moduleEnable = configData.value("netconnctEnable").toString(); QStringList enableItems = moduleEnable.split(","); foreach (QString setItem, enableItems) { QStringList item = setItem.split(":"); if (item.at(0) == "wlanAdvanced") { ui->detailBtn->setEnabled(item.at(1) == "true"); } } } int NetConnect::getInsertPos(QString connName, QString deviceName) { qDebug() << "[NetConnect]getInsertPos" << connName << deviceName; int index = 0; if(m_interface == nullptr || !m_interface->isValid()) { index = 0; } else { QMap> variantList = getWiredList(); if (!variantList.contains(deviceName)) { qDebug() << "[NetConnect] getInsertPos but " << deviceName << "not exist"; return 0; } for (int i = 0; i < variantList[deviceName].size(); ++i ) { if (variantList[deviceName].at(i).at(0) == connName) { qDebug() << "pos in kylin-nm is " << i; index = i; break; } } if (variantList[deviceName].at(0).size() == 1) { index--; } } return index; } bool NetConnect::LaunchApp(QString desktopFile) { QDBusInterface m_appManagerDbusInterface(KYLIN_APP_MANAGER_NAME, KYLIN_APP_MANAGER_PATH, KYLIN_APP_MANAGER_INTERFACE, QDBusConnection::sessionBus());//局部变量 if (!m_appManagerDbusInterface.isValid()) { qWarning()<<"m_appManagerDbusInterface init error"; return false; } else { QDBusReply reply =m_appManagerDbusInterface.call("LaunchApp",desktopFile); return reply; } } QMap> NetConnect::getWiredList() { QMap> map; QMap statusMap; getDeviceStatusMap(statusMap); for (int i = 0; i < statusMap.keys().size(); ++i) { qDebug() << "[NetConnect]call getWiredList" << __LINE__; QDBusReply reply = m_interface->call(QStringLiteral("getWiredList"), statusMap.keys().at(i)); qDebug() << "[NetConnect]call getWiredList respond" << __LINE__; if(!reply.isValid()) { qWarning() << "getWiredList error:" << reply.error().message(); break; } QList list; for (int j = 0; j < reply.value().size(); ++j) { list << reply.value().at(j).toStringList(); } map.insert(statusMap.keys().at(i), list); } return map; } void NetConnect::updatePluginShowSettings() { isEnable(); } bool NetConnect::isDslConnection(const QString &uuid) { QProcess process; process.start("nmcli", {"-g", "connection.type", "con", "show", uuid}); process.waitForFinished(); QString output = process.readAllStandardOutput().trimmed(); return (output == "pppoe"); // 如果是pppoe类型则返回true } kylin-nm/plugins/netconnect/translations/0000775000175000017500000000000015167654227017617 5ustar fengfengkylin-nm/plugins/netconnect/translations/de.ts0000664000175000017500000000706715167651420020561 0ustar fengfeng AddNetBtn Add Others Andere hinzufügen Add WiredNetork WiredNetork hinzufügen LanItem Connected, restricting access. NetConnect Wired Network Kabelgebundenes Netzwerk open offen /netconnect/open Advanced settings Erweiterte Einstellungen /netconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 WiredConnect 有线网络 Settings Einstellungen Settings desktop message Desktop-Meldung für Einstellungen LAN LAN No ethernet device avaliable Kein Ethernet-Gerät verfügbar connected verbunden not connected card Karte kylin-nm/plugins/netconnect/translations/ky.ts0000664000175000017500000000713215167651420020605 0ustar fengfeng AddNetBtn Add Others باشقانى قوشۇۇ Add WiredNetork سىمدۇۇ تور قوشۇۇ LanItem Connected, restricting access. NetConnect Wired Network open /netconnect/open Advanced settings /netconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 WiredConnect 有线网络 Settings Settings desktop message LAN No ethernet device avaliable 未检测到有线设备 connected not connected card kylin-nm/plugins/netconnect/translations/zh_CN.ts0000664000175000017500000000756515167651420021175 0ustar fengfeng AddNetBtn Add Others Add WiredNetork 添加有线网络 LanItem Delete 删除 Disconnect 断开 Connect 连接 Connected, restricting access. 已连接,网络受限。 NetConnect Wired Network 有线网络 open 开启 /netconnect/open Advanced settings 高级设置 /netconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 WiredConnect 有线网络 Settings 设置 Settings desktop message 设置 桌面通知 LAN 有线网络 No ethernet device avaliable 未检测到有线设备 connected 已连接 not connected 未连接 card 网卡 kylin-nm/plugins/netconnect/translations/kk.ts0000664000175000017500000000712315167651420020567 0ustar fengfeng AddNetBtn Add Others باسقانٸ قوسۋ Add WiredNetork سىمدى تور قوسۋ LanItem Connected, restricting access. NetConnect Wired Network open /netconnect/open Advanced settings /netconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 WiredConnect 有线网络 Settings Settings desktop message LAN No ethernet device avaliable 未检测到有线设备 connected not connected card kylin-nm/plugins/netconnect/translations/ms.ts0000664000175000017500000000763015167651420020604 0ustar fengfeng AddNetBtn Add Others Add WiredNetork LanItem Delete 删除 Disconnect 断开 Connect 连接 Connected, restricting access. NetConnect Wired Network open /netconnect/open Advanced settings /netconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 WiredConnect 有线网络 Settings Settings desktop message LAN No ethernet device avaliable connected not connected card kylin-nm/plugins/netconnect/translations/tr.ts0000664000175000017500000000617715167651420020617 0ustar fengfeng AddNetBtn Add Others Add WiredNetork LanItem Connected, restricting access. NetConnect Wired Network open /netconnect/open Advanced settings /netconnect/Advanced settings" Settings Settings desktop message LAN No ethernet device avaliable connected not connected card kylin-nm/plugins/netconnect/translations/bo.ts0000664000175000017500000000617715167651420020572 0ustar fengfeng AddNetBtn Add Others Add WiredNetork LanItem Connected, restricting access. NetConnect Wired Network open /netconnect/open Advanced settings /netconnect/Advanced settings" Settings Settings desktop message LAN No ethernet device avaliable connected not connected card kylin-nm/plugins/netconnect/translations/ug.ts0000664000175000017500000000773715167651420020610 0ustar fengfeng AddNetBtn Add Others Add WiredNetork Add WiredNetork LanItem Delete ئۆچۈر Disconnect ئۈزۈۋېتىش Connect ئۇلىنىش Connected, restricting access. NetConnect Wired Network سىملىق تور open ئېچىش /netconnect/open Advanced settings يۇقىرى تەڭشەكلەر /netconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 WiredConnect 有线网络 Settings تور تەڭشىكى Settings desktop message ئۈستەل يۈزى ئۇچۇرى تەڭشىكى LAN سىملىق تور No ethernet device avaliable 未检测到有线设备 connected ئۇلانغان not connected ئۇلانمىغان card تور كارتىسى kylin-nm/plugins/netconnect/translations/bo_CN.ts0000664000175000017500000001175115167651420021144 0ustar fengfeng AddNetBtn Add Others སྐུད་ཡོད་བརྙན་འཕྲིན་ཁ་སྣོན་བྱས་ཡོད། Add WiredNetork སྐུད་ཡོད་བརྙན་འཕྲིན་ཁ་སྣོན་བྱས་ཡོད། LanItem Delete བསུབ་པ། Disconnect འབྲེལ་ཐག་ཆད་པ། Connect སྦྲེལ་མཐུད་བྱེད་པ། Connected, restricting access. ཚོད་འཛིན་ཐེབས་པའི་དྲ་བ། NetConnect Wired Network སྐུད་ཡོད་བརྙན་འཕྲིན་དྲ་བ། open སྒོ་ཕྱེ་བ། /netconnect/open Advanced settings སྔོན་ཐོན་གྱི་སྒྲིག་བཀོད། /netconnect/Advanced settings" ukui control center ཝུའུ་ཁི་ལན་གྱི་ཚོད་འཛིན་ལྟེ་གནས། ukui control center desktop message ukui ཚོད་འཛིན་ལྟེ་གནས་ཀྱི་ཅོག་ངོས་ཆ་འཕྲིན། WiredConnect སྐུད་ཡོད་སྦྲེལ་མཐུད། Settings བཀོད་སྒྲིག་བཅས་བྱ་དགོས། Settings desktop message བཀོད་སྒྲིག་བཅས་བྱ་དགོས། ཅོག་ངོས་ལ་བརྡ་ཐོ་གཏོང་དགོས། LAN སྐུད་ཡོད་དྲ་བ། No ethernet device avaliable ཨེ་ཙི་དྲ་རྒྱའི་སྒྲིག་ཆས་ལ་བཙན་འཛུལ་བྱས་མི་ཆོག། connected འབྲེལ་མཐུད་བྱེད་པ། not connected འབྲེལ་མཐུད་མི་བྱེད་པ། card བྱང་བུ། kylin-nm/plugins/netconnect/translations/vi.ts0000664000175000017500000000762115167651420020603 0ustar fengfeng AddNetBtn Add Others Add WiredNetork Thêm WiredNetork LanItem Delete Xóa bản sao lưu Disconnect Ngắt Connect Kết nối NetConnect Wired Network Mạng dây open mở /netconnect/open Advanced settings Cài đặt nâng cao /netconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 WiredConnect 有线网络 Settings Cài đặt Settings desktop message Cài đặt thông báo trên màn hình LAN LAN No ethernet device avaliable 未检测到有线设备 connected Đã kết nối not connected không kết nối card Card âm thanh kylin-nm/plugins/netconnect/translations/mn.ts0000664000175000017500000001036615167651420020577 0ustar fengfeng AddNetBtn Add Others ᠪᠤᠰᠤᠳ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠵᠠᠯᠭᠠᠬᠤ Add WiredNetork ᠤᠲᠠᠰᠤᠲᠤ ᠨᠧᠲ ᠨᠡᠮᠡᠬᠦ LanItem Connected, restricting access. NetConnect Wired Network ᠤᠳᠠᠰᠤᠳᠤ ᠰᠦᠯᠵᠢᠶ᠎ᠡ open ᠨᠡᠭᠡᠭᠡᠬᠦ /netconnect/open Advanced settings ᠦᠨᠳᠦᠷ ᠵᠡᠷᠬᠡ ᠵᠢᠨ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠤᠯᠳᠠ /netconnect/Advanced settings" ukui control center ᠡᠵᠡᠮᠰᠢᠯ ᠤ᠋ᠨ ᠬᠠᠪᠳᠠᠰᠤ ukui control center desktop message ᠡᠵᠡᠮᠰᠢᠯ ᠤ᠋ᠨ ᠬᠠᠪᠳᠠᠰᠤᠨ ᠤ᠋ ᠰᠢᠷᠡᠭᠡᠨ ᠨᠢᠭᠤᠷ ᠤ᠋ᠨ ᠮᠡᠳᠡᠭᠳᠡᠯ WiredConnect ᠤᠳᠠᠰᠤᠳᠤ ᠰᠦᠯᠵᠢᠶ᠎ᠡ Settings ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Settings desktop message ᠰᠢᠷᠡᠭᠡᠨ ᠨᠢᠭᠤᠷ᠎ᠤ᠋ᠨ ᠵᠠᠩᠭᠢ᠎ᠶ᠋ᠢ ᠵᠣᠬᠢᠷᠠᠭᠤᠯᠬᠤ LAN ᠤᠲᠠᠰᠤᠲᠤ ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠃ No ethernet device avaliable ᠤᠳᠠᠰᠤᠳᠤ ᠳᠦᠬᠦᠬᠡᠷᠦᠮᠵᠢ ᠵᠢ ᠪᠠᠢᠴᠠᠭᠠᠵᠤ ᠤᠯᠤᠭᠰᠠᠨ ᠦᠬᠡᠢ connected ᠨᠢᠬᠡᠨᠳᠡ ᠴᠦᠷᠬᠡᠯᠡᠪᠡ not connected card ᠨᠧᠲ ᠤ᠋ᠨ ᠺᠠᠷᠲ kylin-nm/plugins/netconnect/translations/zh_Hant.ts0000664000175000017500000000755515167651420021566 0ustar fengfeng AddNetBtn Add Others 添加其他 Add WiredNetork 添加有線網路 LanItem Delete 删去 Disconnect 斷開 Connect 連接 Connected, restricting access. NetConnect Wired Network 有線網路 open 開啟 /netconnect/open Advanced settings 高級設置 /netconnect/Advanced settings" ukui control center 烏奎控制中心 ukui control center desktop message UKUI 控制中心桌面消息 WiredConnect 連線連接 No ethernet device avaliable 未檢測到有線設備 Settings 設定 Settings desktop message 設定案頭消息 LAN 有線網路 connected 已連接 not connected 未連接 card 網卡 kylin-nm/plugins/netconnect/translations/fr.ts0000664000175000017500000000706615167651420020577 0ustar fengfeng AddNetBtn Add Others Ajouter d’autres Add WiredNetork Ajouter WiredNetork LanItem Connected, restricting access. NetConnect Wired Network Réseau câblé open ouvrir /netconnect/open Advanced settings Paramètres avancés /netconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 WiredConnect 有线网络 Settings Paramètres Settings desktop message Message sur le bureau des paramètres LAN LAN No ethernet device avaliable Aucun périphérique Ethernet n’est disponible connected relié not connected card carte kylin-nm/plugins/netconnect/translations/en_US.ts0000664000175000017500000000662415167651420021200 0ustar fengfeng AddNetBtn Add Others Add Others Add WiredNetork Add WiredNetork LanItem Connected, restricting access. NetConnect Wired Network Wired Network open open /netconnect/open Advanced settings Advanced settings /netconnect/Advanced settings" ukui control center ukui control center ukui control center desktop message ukui control center desktop message Settings Settings desktop message LAN LAN No ethernet device avaliable No ethernet device avaliable connected connected not connected card card kylin-nm/plugins/netconnect/translations/es.ts0000664000175000017500000000705115167651420020571 0ustar fengfeng AddNetBtn Add Others Agregar otros Add WiredNetork Añadir WiredNetork LanItem Connected, restricting access. NetConnect Wired Network Red cableada open abrir /netconnect/open Advanced settings Ajustes avanzados /netconnect/Advanced settings" ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 WiredConnect 有线网络 Settings Configuración Settings desktop message Mensaje de escritorio de configuración LAN LAN No ethernet device avaliable No hay dispositivos ethernet disponibles connected conexo not connected card tarjeta kylin-nm/plugins/netconnect/translations/zh_HK.ts0000664000175000017500000000761015167651420021166 0ustar fengfeng AddNetBtn Add Others 添加其他 Add WiredNetork 添加有線網路 LanItem Delete 删去 Disconnect 斷開 Connect 連接 Connected, restricting access. 已連接,網絡受限。 NetConnect Wired Network 有線網路 open 開啟 /netconnect/open Advanced settings 高級設置 /netconnect/Advanced settings" ukui control center 烏奎控制中心 ukui control center desktop message UKUI 控制中心桌面消息 WiredConnect 連線連接 No ethernet device avaliable 未檢測到有線設備 Settings 設定 Settings desktop message 設定案頭消息 LAN 有線網路 connected 已連接 not connected 未連接 card 網卡 kylin-nm/plugins/netconnect/itemframe.cpp0000664000175000017500000000425315167651420017547 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "itemframe.h" #include #include #define LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_MARGINS 0,0,0,0 ItemFrame::ItemFrame(QString devName, QWidget *parent) : QFrame(parent) { deviceLanLayout = new QVBoxLayout(this); deviceLanLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); lanItemFrame = new QFrame(this); lanItemFrame->setFrameShape(QFrame::Shape::NoFrame); lanItemLayout = new QVBoxLayout(this); lanItemLayout->setContentsMargins(LAYOUT_MARGINS); lanItemLayout->setSpacing(1); addLanWidget = new AddNetBtn(false, this); deviceLanLayout->setSpacing(0); setLayout(deviceLanLayout); lanItemFrame->setLayout(lanItemLayout); deviceFrame = new DeviceFrame(devName, this); deviceLanLayout->addWidget(deviceFrame); deviceLanLayout->addWidget(lanItemFrame); deviceLanLayout->addSpacing(1); deviceLanLayout->addWidget(addLanWidget); //下拉按钮 connect(deviceFrame->dropDownLabel, &DrownLabel::labelClicked, this, &ItemFrame::onDrownLabelClicked); } void ItemFrame::onDrownLabelClicked() { if (!deviceFrame->dropDownLabel->isChecked) { lanItemFrame->show(); deviceFrame->dropDownLabel->setDropDownStatus(true); } else { lanItemFrame->hide(); deviceFrame->dropDownLabel->setDropDownStatus(false); } } kylin-nm/plugins/netconnect/lanitem.h0000664000175000017500000000527415167651420016700 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef LANITEM_H #define LANITEM_H #include #include #include #include #include #include #include #include #include #include #include #include "klabel.h" //#include "infobutton.h" #include "../component/AddBtn/grayinfobutton.h" //#include "kborderlessbutton.h" using namespace kdk; enum ConnectivityType { UnknownConnectivity = 0, NoConnectivity = 1, Portal = 2, Limited = 3, Full = 4 }; enum ConnectState { UnknownState = 0, /**< The active connection is in an unknown state */ Activating, /**< The connection is activating */ Activated, /**< The connection is activated */ Deactivating, /**< The connection is being torn down and cleaned up */ Deactivated /**< The connection is no longer active */ }; class LanItem : public QPushButton { Q_OBJECT public: LanItem(bool isAcitve, QWidget *parent = nullptr); ~LanItem(); public: QLabel * iconLabel = nullptr; GrayInfoButton * infoLabel = nullptr; KLabel * titileLabel = nullptr; QLabel * statusLabel = nullptr; public: void startLoading(); void stopLoading(); void setNetworkCheckFrameHidden(bool state); void setConnectivityWarn(ConnectivityType connectivityType); bool loading = false; bool isAcitve = false; bool isPppoe = false; QString uuid; QString dbusPath; protected: void paintEvent(QPaintEvent *); private: QTimer *waitTimer = nullptr; QGSettings *themeGsettings = nullptr; QList loadIcons; int currentIconIndex=0; QFrame *m_networkCheckFrame = nullptr; QLabel * m_warnLabel = nullptr; QLabel * m_warnTextLabel = nullptr; //KBorderlessButton * m_networkCheckBtn = nullptr; private slots: void updateIcon(); }; #endif // LANITEM_H kylin-nm/plugins/netconnect/deviceframe.cpp0000664000175000017500000000543415167651420020052 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "deviceframe.h" #include #define LAYOUT_MARGINS 16,0,16,0 #define FRAME_HEIGHT 58 #define RADIUS 6.0 DeviceFrame::DeviceFrame(QString devName, QWidget *parent) : QFrame(parent) { this->setFrameShape(QFrame::Box); this->setFixedHeight(FRAME_HEIGHT); QHBoxLayout *deviceLayout = new QHBoxLayout(this); deviceLayout->setContentsMargins(LAYOUT_MARGINS); setLayout(deviceLayout); deviceLabel = new QLabel(this); dropDownLabel = new DrownLabel(devName, this); deviceSwitch = new KSwitchButton(this); // deviceSwitch->installEventFilter(this); deviceLayout->addWidget(deviceLabel); deviceLayout->addStretch(); deviceLayout->addWidget(dropDownLabel); deviceLayout->addWidget(deviceSwitch); } bool DeviceFrame::eventFilter(QObject *w,QEvent *e) { if (w == deviceSwitch) { if (e->type() == QEvent::MouseButtonPress) { emit deviceSwitchClicked(!deviceSwitch->isChecked()); return true; } } return QFrame::eventFilter(w, e); } void DeviceFrame::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true); QRect rect = this->rect(); const int radius = RADIUS; // 创建单一路径实现上圆角下直角 QPainterPath path; path.moveTo(rect.topLeft() + QPointF(0, radius)); path.arcTo(rect.left(), rect.top(), radius * 2, radius * 2, 180, -90); path.lineTo(rect.right() - radius, rect.top()); path.arcTo(rect.right() - radius * 2, rect.top(), radius * 2, radius * 2, 90, -90); path.lineTo(rect.right(), rect.bottom()); path.lineTo(rect.left(), rect.bottom()); path.lineTo(rect.left(), rect.top() + radius); // 绘制背景 painter.setPen(Qt::NoPen); painter.setBrush(pal.color(QPalette::Base)); painter.drawPath(path); // 保持基类绘制 QFrame::paintEvent(event); } kylin-nm/plugins/netconnect/translate_generation.sh0000775000175000017500000000056615167651420021644 0ustar fengfeng#!/bin/bash export PATH="/usr/lib/qt6/bin:$PATH" ts_list=(`ls translations/*.ts`) source /etc/os-release version=(`echo $ID`) for ts in "${ts_list[@]}" do printf "\nprocess ${ts}\n" if [ "$version" == "fedora" ] || [ "$version" == "opensuse-leap" ] || [ "$version" == "opensuse-tumbleweed" ];then lrelease-qt5 "${ts}" else lrelease "${ts}" fi done kylin-nm/plugins/netconnect/netconnect.ui0000664000175000017500000001434115167646234017577 0ustar fengfeng NetConnect 0 0 885 700 0 0 16777215 16777215 NetConnect 0 0 0 0 0 0 Wired Network true 1 0 0 60 16777215 50 QFrame::Box 18 0 9 0 0 8 118 0 open Qt::Horizontal 523 20 1 0 QFrame::NoFrame QFrame::Raised 0 0 0 0 0 1 120 36 16777215 36 Advanced settings Qt::Horizontal 40 20 Qt::Vertical 20 40 TitleLabel QLabel
titlelabel.h
kylin-nm/plugins/netconnect/netconnect.h0000664000175000017500000001204015167651420017374 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef NETCONNECT_H #define NETCONNECT_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "interface.h" #include "addbtn.h" #include "klabel.h" #include "hoverbtn.h" #include "lanitem.h" #include "deviceframe.h" #include "itemframe.h" #include "kwidget.h" #include "kswitchbutton.h" #include "ukcccommon.h" using namespace kdk; using namespace ukcc; enum { DISCONNECTED, NOINTERNET, CONNECTED }; namespace Ui { class NetConnect; } class NetConnect : public QObject, CommonInterface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.ukcc.CommonInterface") Q_INTERFACES(CommonInterface) public: NetConnect(); ~NetConnect(); QString plugini18nName() Q_DECL_OVERRIDE; int pluginTypes() Q_DECL_OVERRIDE; QWidget * pluginUi() Q_DECL_OVERRIDE; const QString name() const Q_DECL_OVERRIDE; bool isShowOnHomePage() const Q_DECL_OVERRIDE; QIcon icon() const Q_DECL_OVERRIDE; bool isEnable() const Q_DECL_OVERRIDE; QString translationPath() const Q_DECL_OVERRIDE; private: void initSearchText(); void initComponent(); void runExternalApp(); void showDesktopNotify(const QString &message); //开关相关 void setSwitchStatus(); void hideLayout(QVBoxLayout * layout); void showLayout(QVBoxLayout * layout); int getInsertPos(QString connName, QString deviceName); void deleteOneLan(QString ssid, int type); void activeConnect(QString ssid, QString deviceName, int type); void deActiveConnect(QString ssid, QString deviceName, int type); void setDeviceAutoConnectState(QString deviceName, bool state); //获取设备列表 void getDeviceStatusMap(QMap &map); void initNet(); void initNetListFromDevice(QString deviceName); void initDeviceConnectivity(QString deviceName); void updateDeviceFrameFromConnectivity(ItemFrame *frame, ConnectivityType type); //处理列表增加 void addLanItem(ItemFrame *frame, QString devName, QStringList infoList, bool isActived); //增加设备 void addDeviceFrame(QString devName); //减少设备 void removeDeviceFrame(QString devName); //增加一项 void addOneLanFrame(ItemFrame *frame, QString devName, QStringList infoList); //减少一项 void removeOneLanFrame(ItemFrame *frame, QString deviceName, QString uuid); //单个lan连接状态变化 void itemActiveConnectionStatusChanged(LanItem *item, int status); // 打卡托盘网络窗口,后续需要跳转到指定密码框 void openKylinm(); void netComponnetSettings(); bool LaunchApp(QString desktopFile); bool isExitWiredDevice(); bool isDslConnection(const QString &uuid); protected: bool eventFilter(QObject *w,QEvent *e); private: Ui::NetConnect *ui; QString pluginName; int pluginType; QWidget *pluginWidget; QDBusInterface *m_interface = nullptr; KSwitchButton *wiredSwitch; bool mFirstLoad; QGSettings *m_switchGsettings; QMap deviceStatusMap; QMap deviceFrameMap; QMap> getWiredList(); QDBusInterface *m_pSysBusIntfs; private slots: void updateLanInfo(QString deviceName, QStringList lanInfo); void onLanAdd(QString deviceName, QStringList lanInfo); void onLanRemove(QString dbusPath); void onActiveConnectionChanged(QString deviceName, QString uuid, int status); void onDeviceStatusChanged(); void onDeviceNameChanged(QString, QString, int); //更新控制面板插件Gsetting show void updatePluginShowSettings(); void renewSwitchLayout(bool enable); void wiredSwitchSLot(bool checked); }; Q_DECLARE_METATYPE(QList); #endif // NETCONNECT_H kylin-nm/plugins/netconnect/netconnect.pro0000664000175000017500000000303615167651420017752 0ustar fengfengQT += widgets network dbus gui core TEMPLATE = lib CONFIG += plugin include(../component/drownlabel.pri) include(../component/addbtn.pri) TARGET = $$qtLibraryTarget(netconnect) DESTDIR = ../.. CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } target.path = $$[QT_INSTALL_LIBS]/ukui-control-center trans.files = translations/* trans.path = /usr/share/kylin-nm/netconnect/ INCLUDEPATH += \ $$PROJECT_COMPONENTSOURCE \ $$PROJECT_ROOTDIR \ /usr/include/ukcc/interface \ /usr/include/ukcc/widgets LIBS += -L$$[QT_INSTALL_LIBS] -lukcc CONFIG += c++11 \ link_pkgconfig \ PKGCONFIG += gsettings-qt6 \ kysdk-applications \ #DEFINES += QT_DEPRECATED_WARNINGS SOURCES += \ deviceframe.cpp \ # drownlabel.cpp \ itemframe.cpp \ lanitem.cpp \ netconnect.cpp HEADERS += \ deviceframe.h \ # drownlabel.h \ itemframe.h \ lanitem.h \ netconnect.h FORMS += \ netconnect.ui INSTALLS += target \ trans TRANSLATIONS += \ translations/zh_Hant.ts \ translations/zh_HK.ts \ translations/zh_CN.ts \ translations/ug.ts \ translations/tr.ts \ translations/mn.ts \ translations/ky.ts \ translations/kk.ts \ translations/fr.ts \ translations/es.ts \ translations/en_US.ts \ translations/de.ts \ translations/bo.ts\ translations/bo_CN.ts kylin-nm/plugins/netconnect/itemframe.h0000664000175000017500000000323715167646234017224 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef ITEMFRAME_H #define ITEMFRAME_H #include #include #include "deviceframe.h" #include #include "../component/AddBtn/addnetbtn.h" #include "lanitem.h" class ItemFrame : public QFrame { Q_OBJECT public: ItemFrame(QString devName, QWidget *parent = nullptr); //单设备整体layout QVBoxLayout * deviceLanLayout = nullptr; //单设备名称+下拉按钮Frame+d单设备开关 DeviceFrame * deviceFrame = nullptr; //单设备列表Frame QFrame * lanItemFrame = nullptr; //单设备列表layout QVBoxLayout * lanItemLayout = nullptr; //新建有线连接 AddNetBtn * addLanWidget = nullptr; //单设备item列表 key:uuid QMap itemMap; private slots: void onDrownLabelClicked(); }; #endif // ITEMFRAME_H kylin-nm/plugins/netconnect/deviceframe.h0000664000175000017500000000316115167646234017521 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef DEVICEFRAME_H #define DEVICEFRAME_H #include #include #include #include #include #include #include #include "../component/DrownLabel/drownlabel.h" #include "kwidget.h" #include "kswitchbutton.h" using namespace kdk; class DeviceFrame : public QFrame { Q_OBJECT public: DeviceFrame(QString devName, QWidget *parent = nullptr); public: QLabel * deviceLabel = nullptr; KSwitchButton * deviceSwitch = nullptr; DrownLabel *dropDownLabel = nullptr; protected: void paintEvent(QPaintEvent *event); bool eventFilter(QObject *w,QEvent *e); private: bool isDropDown = false; int frameSize; signals: void deviceSwitchClicked(bool); }; #endif // DEVICEFRAME_H kylin-nm/plugins/netconnect/lanitem.cpp0000664000175000017500000001212715167651420017226 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "lanitem.h" #include #include #define FRAME_SPEED 150 #define LIMIT_TIME 60*1000 #define TOTAL_PAGE 8 #define MIN_TITLE_Width 80 #define THEME_QT_SCHEMA "org.ukui.style" #define MODE_QT_KEY "style-name" #define ICON_THEME "iconThemeName" LanItem::LanItem(bool isAcitve, QWidget *parent) : QPushButton(parent),isAcitve(isAcitve) { this->setMinimumSize(550, 58); this->setProperty("useButtonPalette", true); this->setFlat(true); QHBoxLayout *mLanLyt = new QHBoxLayout(this); mLanLyt->setContentsMargins(16,0,16,0); mLanLyt->setSpacing(16); iconLabel = new QLabel(this); iconLabel->setProperty("useIconHighlightEffect", 0x2); titileLabel = new KLabel(this); titileLabel->setMinimumWidth(MIN_TITLE_Width); statusLabel = new QLabel(this); statusLabel->setProperty("useIconHighlightEffect", 0x2); statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); infoLabel = new GrayInfoButton(this); m_networkCheckFrame = new QFrame(this); m_warnLabel = new QLabel(this); m_warnLabel->setContentsMargins(0,0,0,0); m_warnLabel->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(16,16)); m_warnTextLabel = new QLabel(this); QHBoxLayout *netCheckFrameLyt = new QHBoxLayout(m_networkCheckFrame); netCheckFrameLyt->setContentsMargins(0, 0, 0, 0); netCheckFrameLyt->setSpacing(5); netCheckFrameLyt->addWidget(m_warnLabel); netCheckFrameLyt->addWidget(m_warnTextLabel); m_networkCheckFrame->setHidden(true); mLanLyt->addWidget(iconLabel); mLanLyt->addWidget(titileLabel,Qt::AlignLeft); mLanLyt->addStretch(); mLanLyt->addWidget(statusLabel); mLanLyt->addWidget(m_networkCheckFrame); mLanLyt->addWidget(infoLabel); loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); waitTimer = new QTimer(this); connect(waitTimer, &QTimer::timeout, this, &LanItem::updateIcon); const QByteArray id(THEME_QT_SCHEMA); if (QGSettings::isSchemaInstalled(id)) { QGSettings * styleGsettings = new QGSettings(id, QByteArray(), this); connect(styleGsettings, &QGSettings::changed, this, [=](QString key){ if (ICON_THEME == key && m_warnLabel) { m_warnLabel->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(16,16)); } }); } } LanItem::~LanItem() { } void LanItem::updateIcon() { if (currentIconIndex > 6) { currentIconIndex = 0; } statusLabel->setPixmap(loadIcons.at(currentIconIndex).pixmap(16,16)); currentIconIndex ++; } void LanItem::startLoading() { waitTimer->start(FRAME_SPEED); loading = true; } void LanItem::stopLoading(){ waitTimer->stop(); loading = false; } void LanItem::setNetworkCheckFrameHidden(bool state) { m_networkCheckFrame->setHidden(state); statusLabel->setVisible(state); } void LanItem::setConnectivityWarn(ConnectivityType connectivityType) { QString text; switch (connectivityType) { case NoConnectivity: text = QString(""); setNetworkCheckFrameHidden(true); break; case Portal: case Limited: text = QString(tr("Connected, restricting access.")); break; case Full: default: text = QString(""); setNetworkCheckFrameHidden(true); break; } m_warnTextLabel->setText(text); } void LanItem::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); painter.setBrush(this->palette().base().color()); QPalette pal = qApp->palette(); QColor color = pal.color(QPalette::Button); color.setAlphaF(0.5); pal.setColor(QPalette::Button, color); this->setPalette(pal); QRect rect = this->rect(); painter.drawRect(rect); QPushButton::paintEvent(event); } kylin-nm/plugins/mobilehotspot/0000775000175000017500000000000015167651420015616 5ustar fengfengkylin-nm/plugins/mobilehotspot/connectdevpage.cpp0000664000175000017500000001336215167646234021323 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "connectdevpage.h" #include #define CONTENTS_MARGINS 0, 0, 0, 0 #define FRAME_MIN_SIZE 550, 60 #define FRAME_MAX_SIZE 16777215, 16777215 #define LINE_MAX_SIZE 16777215, 1 #define LINE_MIN_SIZE 0, 1 #define LOG_HEAD "[ConnectdevPage]" ConnectdevPage::ConnectdevPage(QWidget *parent) : QWidget(parent) { QVBoxLayout *Vlayout = new QVBoxLayout(this); Vlayout->setContentsMargins(CONTENTS_MARGINS); Vlayout->setSpacing(0); m_staistFrame = new QFrame(this); m_staistFrame->setMinimumSize(FRAME_MIN_SIZE); m_staistFrame->setMaximumSize(FRAME_MAX_SIZE); m_staistFrame->setFrameShape(QFrame::Box); m_staListLayout = new QVBoxLayout(m_staistFrame); m_staListLayout->setContentsMargins(0, 0, 0, 0); m_staListLayout->setSpacing(0); m_titleLabel = new KLabel(this); m_titleLabel->setText(tr("Connect device")); m_titleLabel->setContentsMargins(16, 0, 0, 0); Vlayout->addWidget(m_titleLabel); Vlayout->addSpacing(8); Vlayout->addWidget(m_staistFrame); } QFrame* ConnectdevPage::myLine() { QFrame *line = new QFrame(this); line->setMinimumSize(QSize(LINE_MIN_SIZE)); line->setMaximumSize(QSize(LINE_MAX_SIZE)); line->setLineWidth(0); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); return line; } void ConnectdevPage::getConnectStaDevice(QMap &staMap) { staMap.clear(); if (m_activePathInterface == nullptr || !m_activePathInterface->isValid()) { qDebug() << LOG_HEAD << "dbus interface m_activePathInterface is invaild"; return; } QDBusMessage reply = m_activePathInterface->call("Getstainfo"); if(reply.type() == QDBusMessage::ErrorMessage) { qWarning() << LOG_HEAD << "Getstainfo error:" << reply.errorMessage(); return; } if (reply.arguments().isEmpty() || reply.arguments().at(0).toString() == "" || reply.arguments().at(0).toString() == "[Invalid UTF-8]" || reply.arguments().at(1).toString() == "") { qDebug() << LOG_HEAD << "Dbus interface call Getstainfo return is empty!"; return; } QStringList macList = reply.arguments().at(0).toString().split(";"); QStringList hostNameList = reply.arguments().at(1).toString().split(";"); for (int index = 0; index < macList.count() && macList.at(index) != nullptr; index ++) { if (!staMap.contains(macList.at(index)) && hostNameList.at(index) != nullptr) { staMap[macList.at(index)] = hostNameList.at(index); } } } void ConnectdevPage::initStaDev() { QMap::const_iterator item = m_staMap.cbegin(); while (item != m_staMap.cend()) { addStaDevFrame(item.key(), item.value()); item ++; if (item != m_staMap.cend()) { m_staListLayout->addWidget(myLine()); } } } void ConnectdevPage::addStaDevFrame(QString staMac, QString staName) { ConnectDevListItem *itemFrame = new ConnectDevListItem(staMac, staName, m_staListLayout->widget()); m_staListLayout->addWidget(itemFrame); connect(itemFrame, &ConnectDevListItem::onBtnClicked, this, &ConnectdevPage::onDropIntoBlacklistBtnClicked); } void ConnectdevPage::clearStaListLayout() { if (m_staListLayout->layout() != NULL) { QLayoutItem* layoutItem; while ((layoutItem = m_staListLayout->layout()->takeAt(0)) != NULL) { delete layoutItem->widget(); delete layoutItem; } } } void ConnectdevPage::onStaDevAdded(bool istrue, QString staMac, QString staName) { if (!m_staMap.contains(staMac)) { m_staMap.insert(staMac, staName); clearStaListLayout(); initStaDev(); resetLayoutHight(); } } void ConnectdevPage::onStaDevRemoved(bool istrue, QString staMac, QString staName) { if (m_staMap.contains(staMac)) { if (m_staMap.remove(staMac)) { clearStaListLayout(); initStaDev(); resetLayoutHight(); } } } void ConnectdevPage::resetLayoutHight() { int height = 0; for (int i = 0; i < m_staListLayout->count(); i ++) { QWidget *w = m_staListLayout->itemAt(i)->widget(); if (w != nullptr) { height += w->height(); } } m_staistFrame->setFixedHeight(height); if (m_staMap.isEmpty()) { this->hide(); } else { this->show(); } this->update(); } void ConnectdevPage::refreshStalist() { m_staMap.clear(); getConnectStaDevice(m_staMap); clearStaListLayout(); initStaDev(); resetLayoutHight(); } void ConnectdevPage::onDropIntoBlacklistBtnClicked(QString staMac, QString staName) { if (staMac.isNull() || staMac.isEmpty() || staName.isNull() || staName.isEmpty()) { qDebug() << LOG_HEAD <<"On drop into blacklist button clicked error! sta mac or name is empty!"; return; } emit setStaIntoBlacklist(staMac, staName); } kylin-nm/plugins/mobilehotspot/mobilehotspot.pro0000664000175000017500000000307615167651420021236 0ustar fengfengQT += widgets network dbus gui core TEMPLATE = lib CONFIG += plugin TARGET = $$qtLibraryTarget(mobilehotspot) DESTDIR = ../.. CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } target.path = $$[QT_INSTALL_LIBS]/ukui-control-center trans.files = translations/* trans.path = /usr/share/kylin-nm/mobilehotspot/ INCLUDEPATH += \ $$PROJECT_COMPONENTSOURCE \ $$PROJECT_ROOTDIR \ /usr/include/ukcc/interface \ /usr/include/ukcc/widgets LIBS += -L$$[QT_INSTALL_LIBS] -lukcc CONFIG += c++11 \ link_pkgconfig \ PKGCONFIG += gsettings-qt6 \ kysdk-applications \ #DEFINES += QT_DEPRECATED_WARNINGS SOURCES += \ blacklistpage.cpp \ blacklistitem.cpp \ connectdevpage.cpp \ connectdevlistitem.cpp \ mobilehotspot.cpp \ mobilehotspotwidget.cpp HEADERS += \ blacklistpage.h \ blacklistitem.h \ connectdevpage.h \ connectdevlistitem.h \ mobilehotspot.h \ mobilehotspotwidget.h \ libukcc_global.h INSTALLS += target \ trans TRANSLATIONS += \ translations/zh_Hant.ts \ translations/zh_CN.ts \ translations/zh_HK.ts \ translations/ug.ts \ translations/tr.ts \ translations/mn.ts \ translations/ky.ts \ translations/kk.ts \ translations/fr.ts \ translations/es.ts \ translations/en_US.ts \ translations/de.ts \ translations/bo.ts\ translations/bo_CN.ts \ kylin-nm/plugins/mobilehotspot/connectdevpage.h0000664000175000017500000000470315167646234020767 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef CONNECTDEVPAGE_H #define CONNECTDEVPAGE_H #include #include #include #include #include #include #include #include #include "klabel.h" #include "connectdevlistitem.h" using namespace kdk; class ConnectdevPage : public QWidget { Q_OBJECT public: explicit ConnectdevPage(QWidget *parent = nullptr); void refreshStalist(); inline void setInterface(QDBusInterface *activeInterface) { m_activePathInterface = activeInterface; } private: QFrame* myLine(); void getConnectStaDevice(QMap &blacklistMap); bool removeStaFromBlacklist(QString staMac); void initStaDev(); void addStaDevFrame(QString staMac, QString staName); void clearStaListLayout(); QString getActivePathByUuid(QDBusInterface *interface); void initNmDbus(QDBusInterface *interface); void onStaDevChanged(bool istrue, QString staMac, QString staName); void resetLayoutHight(); private: QFrame *m_staistFrame = nullptr; KLabel *m_titleLabel = nullptr; QVBoxLayout *m_staListLayout = nullptr; QMap m_staMap; QDBusInterface *m_activePathInterface = nullptr; signals: void setStaIntoBlacklist(QString staMac, QString staName); public slots: void onStaDevAdded(bool istrue, QString staMac, QString staName); void onStaDevRemoved(bool istrue, QString staMac, QString staName); private slots: void onDropIntoBlacklistBtnClicked(QString staMac, QString staName); }; #endif // MOBILEHOTSPOTWIDGET_H kylin-nm/plugins/mobilehotspot/blacklistpage.h0000664000175000017500000000427615167646234020614 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef BLACKLISTPAGE_H #define BLACKLISTPAGE_H #include #include #include #include #include #include #include #include #include "klabel.h" #include "blacklistitem.h" using namespace kdk; class BlacklistPage : public QWidget { Q_OBJECT public: explicit BlacklistPage(QWidget *parent = nullptr); void refreshBlacklist(); bool setStaIntoBlacklist(QString staMac); inline void setInterface(QDBusInterface *settingInterface) { m_settingPathInterface = settingInterface; } private: QFrame* myLine(); void getBlacklistDevice(QMap &blacklistMap); bool removeStaFromBlacklist(QString staMac, QString staName); void initBlacklistDev(); void addBlacklistDevFrame(QString staMac, QString staName); void clearBlacklistLayout(); void resetLayoutHight(); private: QFrame *m_blacklistFrame = nullptr; KLabel *m_titleLabel = nullptr; QVBoxLayout *m_blacklistLayout = nullptr; QMap m_blacklistMap; QDBusInterface *m_settingPathInterface = nullptr; private slots: void onsetStaIntoBlacklist(QString staMac, QString staName); void onRemoveFromBlacklistBtnClicked(QString staMac, QString staName); }; #endif // MOBILEHOTSPOTWIDGET_H kylin-nm/plugins/mobilehotspot/blacklistpage.cpp0000664000175000017500000001462615167646234021147 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "blacklistpage.h" #include #define CONTENTS_MARGINS 0, 0, 0, 0 #define FRAME_MIN_SIZE 550, 60 #define FRAME_MAX_SIZE 16777215, 16777215 #define LINE_MAX_SIZE 16777215, 1 #define LINE_MIN_SIZE 0, 1 #define LOG_HEAD "[BlacklistPage]" BlacklistPage::BlacklistPage(QWidget *parent) : QWidget(parent) { QVBoxLayout *Vlayout = new QVBoxLayout(this); Vlayout->setContentsMargins(CONTENTS_MARGINS); Vlayout->setSpacing(0); m_blacklistFrame = new QFrame(this); m_blacklistFrame->setMinimumSize(FRAME_MIN_SIZE); m_blacklistFrame->setMaximumSize(FRAME_MAX_SIZE); m_blacklistFrame->setFrameShape(QFrame::Box); m_blacklistLayout = new QVBoxLayout(m_blacklistFrame); m_blacklistLayout->setContentsMargins(0, 0, 0, 0); m_blacklistLayout->setSpacing(0); m_titleLabel = new KLabel(this); m_titleLabel->setText(tr("Blacklist")); m_titleLabel->setContentsMargins(16, 0, 0, 0); Vlayout->addWidget(m_titleLabel); Vlayout->addSpacing(8); Vlayout->addWidget(m_blacklistFrame); } QFrame* BlacklistPage::myLine() { QFrame *line = new QFrame(this); line->setMinimumSize(QSize(LINE_MIN_SIZE)); line->setMaximumSize(QSize(LINE_MAX_SIZE)); line->setLineWidth(0); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); return line; } void BlacklistPage::getBlacklistDevice(QMap &blacklistMap) { if (m_settingPathInterface == nullptr || !m_settingPathInterface->isValid()) { qDebug() << LOG_HEAD << "dbus interface m_settingPathInterface is invaild"; return; } QDBusMessage reply = m_settingPathInterface->call("Getblacklist"); if(reply.type() == QDBusMessage::ErrorMessage) { qWarning() << LOG_HEAD << "Getblacklist error:" << reply.errorMessage(); return; } if (reply.arguments().isEmpty() || reply.arguments().at(0).toString() == "" || reply.arguments().at(1).toString() == "") { qDebug() << LOG_HEAD << "Dbus interface call Getblacklist return is empty!"; return; } QStringList macList = reply.arguments().at(0).toString().split(";"); QStringList hostNameList = reply.arguments().at(1).toString().split(";"); for (int index = 0; index < macList.count() && macList.at(index) != nullptr; index ++) { QString macTemp = macList.at(index); macTemp = macTemp.trimmed(); if (!blacklistMap.contains(macTemp) && hostNameList.at(index) != nullptr) { blacklistMap[macTemp] = hostNameList.at(index); } } } void BlacklistPage::initBlacklistDev() { QMap::const_iterator item = m_blacklistMap.cbegin(); while (item != m_blacklistMap.cend()) { addBlacklistDevFrame(item.key(), item.value()); item ++; if (item != m_blacklistMap.cend()) { m_blacklistLayout->addWidget(myLine()); } } } void BlacklistPage::onsetStaIntoBlacklist(QString staMac, QString staName) { if (m_settingPathInterface == nullptr || !m_settingPathInterface->isValid()) { qDebug() << LOG_HEAD << LOG_HEAD << "dbus interface m_settingPathInterface is invaild"; return; } QDBusMessage reply = m_settingPathInterface->call("Addblacklist", staMac, staName); if(reply.type() == QDBusMessage::ErrorMessage) { qWarning() << LOG_HEAD << "Addblacklist error:" << reply.errorMessage(); return; } refreshBlacklist(); } void BlacklistPage::addBlacklistDevFrame(QString staMac, QString staName) { BlacklistItem *itemFrame = new BlacklistItem(staMac, staName, m_blacklistLayout->widget()); m_blacklistLayout->addWidget(itemFrame); connect(itemFrame, &BlacklistItem::onBtnClicked, this, &BlacklistPage::onRemoveFromBlacklistBtnClicked); } void BlacklistPage::clearBlacklistLayout() { if (m_blacklistLayout->layout() != NULL) { QLayoutItem* layoutItem; while ((layoutItem = m_blacklistLayout->layout()->takeAt(0)) != NULL) { delete layoutItem->widget(); delete layoutItem; } } } bool BlacklistPage::removeStaFromBlacklist(QString staMac, QString staName) { if (m_settingPathInterface == nullptr || !m_settingPathInterface->isValid()) { qDebug() << LOG_HEAD << "dbus interface m_settingPathInterface is invaild"; return false; } QDBusMessage reply = m_settingPathInterface->call("Delblacklist", staMac, staName); if(reply.type() == QDBusMessage::ErrorMessage) { qWarning() << LOG_HEAD << "Delblacklist error:" << reply.errorMessage(); return false; } return true; } void BlacklistPage::resetLayoutHight() { int height = 0; for (int i = 0; i < m_blacklistLayout->count(); i ++) { QWidget *w = m_blacklistLayout->itemAt(i)->widget(); if (w != nullptr) { height += w->height(); } } m_blacklistFrame->setFixedHeight(height); if (m_blacklistMap.isEmpty()) { this->hide(); } else { this->show(); } this->update(); } void BlacklistPage::refreshBlacklist() { m_blacklistMap.clear(); getBlacklistDevice(m_blacklistMap); clearBlacklistLayout(); initBlacklistDev(); resetLayoutHight(); } void BlacklistPage::onRemoveFromBlacklistBtnClicked(QString staMac, QString staName) { if (staMac.isNull() || staMac.isEmpty() || staName.isNull() || staName.isEmpty()) { qDebug() << LOG_HEAD <<"On remove from blacklist button clicked error! sta mac or name is empty!"; return; } removeStaFromBlacklist(staMac, staName); refreshBlacklist(); } kylin-nm/plugins/mobilehotspot/translations/0000775000175000017500000000000015167654227020347 5ustar fengfengkylin-nm/plugins/mobilehotspot/translations/de.ts0000664000175000017500000002016615167646234021313 0ustar fengfeng BlacklistItem Remove Entfernen BlacklistPage Blacklist Schwarze Liste ConnectDevListItem drag into blacklist In Blacklist ziehen ConnectdevPage Connect device Gerät anschließen MobileHotspot MobileHotspot Mobiler Hotspot Mobile Hotspot Mobiler Hotspot /mobilehotspot/Mobile Hotspot Open mobile hotspot Mobiler Hotspot öffnen /mobilehotspot/Open mobile hotspot Wi-Fi Name Name des drahtlosen Netzwerks /mobilehotspot/Wi-Fi Name Network Password Netzwerkpasswort /mobilehotspot/Network Password Network Frequency band Netzwerkbandbreite /mobilehotspot/Network Frequency band Shared NIC port Gemeinsamer Netzwerkkartenport /mobilehotspot/Shared NIC port mobilehotspot Mobiler Hotspot /mobilehotspot/mobilehotspot mobilehotspot open MobileHotspot geöffnet /mobilehotspot/mobilehotspot open MobileHotspotWidget ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 wirless switch is close or no wireless device Der kabellose Schalter ist in der Nähe oder kein drahtloses Gerät start to close hotspot 开始关闭热点 hotpots name or device is invalid Der Name oder das Gerät des Hotpots ist ungültig can not create hotspot with password length less than eight! 不能创建密码长度小于八位的热点! start to open hotspot 开始创建热点 Contains at least 8 characters Enthält mindestens 8 Zeichen Hotspot Hotspot (Hotspot) Settings Einstellungen Settings desktop message Desktop-Meldung für Einstellungen use gebrauchen share network, will interrupt local wireless connection Netzwerk freigeben, unterbricht die lokale drahtlose Verbindung hotspot already close Hotspot bereits geschlossen Open mobile hotspot Mobiler Hotspot aktivieren Network Password Netzwerkpasswort Network Frequency band Netzwerkbandbreite Shared NIC port Gemeinsamer Netzwerkkartenport Open Offen Wi-Fi Name Wi-Fi-Name Password Passwort Frequency band Frequenzband Net card Netzkarte hotspot already open Hotspot bereits geöffnet kylin-nm/plugins/mobilehotspot/translations/ky.ts0000664000175000017500000002130615167646234021343 0ustar fengfeng BlacklistItem Remove چىعارۇۇ BlacklistPage Blacklist جابدۇۇ قارا تىزىمدىگى ConnectDevListItem drag into blacklist قارا تىزىمدىكە قوشۇۇ ConnectdevPage Connect device اسپاپتى ۇلوو MobileHotspot MobileHotspot كۅچمۅ اعىم تۉيۉنۉ Mobile Hotspot /mobilehotspot/Mobile Hotspot Open mobile hotspot /mobilehotspot/Open mobile hotspot Wi-Fi Name سەمىز تور ناامى /mobilehotspot/Wi-Fi Name Network Password /mobilehotspot/Network Password Network Frequency band /mobilehotspot/Network Frequency band Shared NIC port /mobilehotspot/Shared NIC port mobilehotspot كۅچمۅ اعىم تۉيۉنۉ /mobilehotspot/mobilehotspot mobilehotspot open كۅچمۅ اعىم تۉيۉنۉ اچۇۇ /mobilehotspot/mobilehotspot open MobileHotspotWidget ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 wirless switch is close or no wireless device سەمىز ۋىكلىۇچاتەل تاقالدى كۅرۉنۉشتۅرۉ قىزىق تۉيۉن قۇرباتى بار سەمىز تور كارتوچكاسى باربولۇۇسۇ ەمەس start to close hotspot 开始关闭热点 hotpots name or device is invalid اعىم تۉيۉن ناامى كۅرۉنۉشتۅرۉ شايمان ەسەپ ەمەس can not create hotspot with password length less than eight! 不能创建密码长度小于八位的热点! start to open hotspot 开始创建热点 Contains at least 8 characters از دەگەندە 8 تامعانى ۅز ىچىنە الات Hotspot اعىم تۉيۉنۉ Settings تەڭشەكتەر Settings desktop message شىرە بەتى ۇچۇرۇ تەڭشەگى use ىشتەتىش share network, will interrupt local wireless connection ورتوق باارلانۇۇ بولوتۇرعان تور ، جەردىك سەمىز ۇلانۇۇ ۉزۉلۉپ قالات hotspot already close اعىم تۉيۉنۉ تەە مۇردا جابىلىپ بولدۇ Open mobile hotspot Network Password Network Frequency band Shared NIC port Open اچۇۇ Wi-Fi Name سەمىز تور ناامى Password جاشىرۇۇن نومۇر Frequency band تور جىشتىق القاعى Net card ورتوق باارلانۇۇ بولوتۇرعان تور كارتوچكاسى hotspot already open اعىم تۉيۉنۉ تەە مۇردا ئېچىۋېتىلدى kylin-nm/plugins/mobilehotspot/translations/zh_CN.ts0000664000175000017500000001637215167651420021721 0ustar fengfeng BlacklistItem Remove 移出 BlacklistPage Blacklist 设备黑名单 ConnectDevListItem drag into blacklist 添加进黑名单 ConnectdevPage Connect device 连接设备 MobileHotspot MobileHotspot 移动热点 Mobile Hotspot 移动热点 /mobilehotspot/Mobile Hotspot Open mobile hotspot 开启移动热点 /mobilehotspot/Open mobile hotspot Wi-Fi Name Wi-Fi 名称 /mobilehotspot/Wi-Fi Name Network Password 网络密码 /mobilehotspot/Network Password Network Frequency band 网络频带 /mobilehotspot/Network Frequency band Shared NIC port 共享网卡端口 /mobilehotspot/Shared NIC port mobilehotspot 移动热点 MobileHotspotWidget ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 wirless switch is close or no wireless device 无线开关已关闭或不存在有热点功能的无线网卡 start to close hotspot 开始关闭热点 hotpots name or device is invalid 热点名称或设备错误 can not create hotspot with password length less than eight! 不能创建密码长度小于八位的热点! start to open hotspot 开始创建热点 Contains at least 8 characters 至少包含8个字符 Hotspot 移动热点 Settings 设置 Settings desktop message 设置 桌面通知 use 使用 share network, will interrupt local wireless connection 进行热点共享,会中断本机无线网络连接 hotspot already close 热点已关闭 Open mobile hotspot 开启移动热点 Network Password 网络密码 Network Frequency band 网络频带 Shared NIC port 共享网卡端口 Open 开启 Wi-Fi Name Wi-Fi 名称 Password 网络密码 Frequency band 网络频带 hotspot already open 热点已开启 kylin-nm/plugins/mobilehotspot/translations/kk.ts0000664000175000017500000002123315167646234021324 0ustar fengfeng BlacklistItem Remove شىعارىپ وتۋ BlacklistPage Blacklist ماتەريال قارا تٸزٸمدٸگٸ ConnectDevListItem drag into blacklist قارا تٸزٸمدٸككە قوسۋ ConnectdevPage Connect device اسبابٸن اۋلاۋ MobileHotspot MobileHotspot كۇشەمەكشى اعٸم نۇكتەسى Mobile Hotspot /mobilehotspot/Mobile Hotspot Open mobile hotspot /mobilehotspot/Open mobile hotspot Wi-Fi Name سىمسىز تور مى /mobilehotspot/Wi-Fi Name Network Password /mobilehotspot/Network Password Network Frequency band /mobilehotspot/Network Frequency band Shared NIC port /mobilehotspot/Shared NIC port mobilehotspot كۇشەمەكشى اعٸم نۇكتەسى /mobilehotspot/mobilehotspot mobilehotspot open كۇشەمەكشى اعٸم نۇكتەسى ٸشٸۋ /mobilehotspot/mobilehotspot open MobileHotspotWidget ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 wirless switch is close or no wireless device سىمسىز ايىرپ قوسقىش جابٸلدٸ ياكي قىزىق نۇكتە رولدارٸ بار سىمسىز تور كارتاسى ساقتالعان ەمەس start to close hotspot 开始关闭热点 hotpots name or device is invalid اعٸم نۇكتە مى ياكي اسباب كۇشكە يە ەمەس can not create hotspot with password length less than eight! 不能创建密码长度小于八位的热点! start to open hotspot 开始创建热点 Contains at least 8 characters از دەگەندە 8 ٵربى ٶز ىشىنە الادٸ Hotspot اعٸم نۇكتەسى Settings تەڭشەۋلەر Settings desktop message ۇستەل بەتى حابارى تەڭگەرگٸش use ٸستەتۋ share network, will interrupt local wireless connection ورتاق ٴلاززاتتانۋ بولاتٸن تور، جەرلىك سىمسىز جالعانۋ ٷزٸلٸپ قالدى hotspot already close اعٸم نۇكتەسى الدەقاشان جابىلىپ قالدى Open mobile hotspot Network Password Network Frequency band Shared NIC port Open ٸشٸۋ Wi-Fi Name سىمسىز تور مى Password قۇپيا نومەر Frequency band تور جيىلىگى Net card ورتاق ٴلاززاتتانۋ بولاتٸن تور كارتاسى hotspot already open اعٸم نۇكتەسى الدەقاشان ئېچىۋېتىلدى kylin-nm/plugins/mobilehotspot/translations/ms.ts0000664000175000017500000001637715167651420021344 0ustar fengfeng BlacklistItem Remove BlacklistPage Blacklist ConnectDevListItem drag into blacklist ConnectdevPage Connect device MobileHotspot MobileHotspot Mobile Hotspot /mobilehotspot/Mobile Hotspot Open mobile hotspot /mobilehotspot/Open mobile hotspot Wi-Fi Name /mobilehotspot/Wi-Fi Name Network Password /mobilehotspot/Network Password Network Frequency band /mobilehotspot/Network Frequency band Shared NIC port /mobilehotspot/Shared NIC port mobilehotspot 移动热点 MobileHotspotWidget ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 wirless switch is close or no wireless device start to close hotspot 开始关闭热点 hotpots name or device is invalid can not create hotspot with password length less than eight! 不能创建密码长度小于八位的热点! start to open hotspot 开始创建热点 Contains at least 8 characters Hotspot Settings Settings desktop message use share network, will interrupt local wireless connection hotspot already close Open mobile hotspot Network Password Network Frequency band Shared NIC port Open 开启 Wi-Fi Name Password 网络密码 Frequency band 网络频带 hotspot already open kylin-nm/plugins/mobilehotspot/translations/tr.ts0000664000175000017500000001370615167651420021343 0ustar fengfeng BlacklistItem Remove BlacklistPage Blacklist ConnectDevListItem drag into blacklist ConnectdevPage Connect device MobileHotspot MobileHotspot Mobile Hotspot /mobilehotspot/Mobile Hotspot Open mobile hotspot /mobilehotspot/Open mobile hotspot Wi-Fi Name /mobilehotspot/Wi-Fi Name Network Password /mobilehotspot/Network Password Network Frequency band /mobilehotspot/Network Frequency band Shared NIC port /mobilehotspot/Shared NIC port MobileHotspotWidget wirless switch is close or no wireless device hotpots name or device is invalid Open mobile hotspot Network Password Contains at least 8 characters Hotspot Settings Settings desktop message use share network, will interrupt local wireless connection hotspot already close Network Frequency band Shared NIC port Wi-Fi Name hotspot already open kylin-nm/plugins/mobilehotspot/translations/bo.ts0000664000175000017500000001370615167651420021316 0ustar fengfeng BlacklistItem Remove BlacklistPage Blacklist ConnectDevListItem drag into blacklist ConnectdevPage Connect device MobileHotspot MobileHotspot Mobile Hotspot /mobilehotspot/Mobile Hotspot Open mobile hotspot /mobilehotspot/Open mobile hotspot Wi-Fi Name /mobilehotspot/Wi-Fi Name Network Password /mobilehotspot/Network Password Network Frequency band /mobilehotspot/Network Frequency band Shared NIC port /mobilehotspot/Shared NIC port MobileHotspotWidget wirless switch is close or no wireless device hotpots name or device is invalid Open mobile hotspot Network Password Contains at least 8 characters Hotspot Settings Settings desktop message use share network, will interrupt local wireless connection hotspot already close Network Frequency band Shared NIC port Wi-Fi Name hotspot already open kylin-nm/plugins/mobilehotspot/translations/ug.ts0000664000175000017500000001760215167646234021337 0ustar fengfeng BlacklistItem Remove چىقىرىۋېتىش BlacklistPage Blacklist ئۈسكىنە قارا تىزىملىكى ConnectDevListItem drag into blacklist قارا تىزىملىككە قوشۇش ConnectdevPage Connect device ئۈسكۈنىنى ئۇلاش MobileHotspot MobileHotspot كۆچمە ئېقىم نۇقتىسى Mobile Hotspot /mobilehotspot/Mobile Hotspot Open mobile hotspot /mobilehotspot/Open mobile hotspot Wi-Fi Name سىمسىز تور نامى /mobilehotspot/Wi-Fi Name Network Password /mobilehotspot/Network Password Network Frequency band /mobilehotspot/Network Frequency band Shared NIC port /mobilehotspot/Shared NIC port mobilehotspot كۆچمە ئېقىم نۇقتىسى /mobilehotspot/mobilehotspot mobilehotspot open كۆچمە ئېقىم نۇقتىسى ئېچىش /mobilehotspot/mobilehotspot open MobileHotspotWidget wirless switch is close or no wireless device سىمسىز ۋىكليۇچاتېل تاقالدى ياكى قىزىق نۇقتا ئىقتىدارى بار سىمسىز تور كارتىسى مەۋجۇت ئەمەس hotpots name or device is invalid ئېقىم نۇقتا نامى ياكى ئۈسكۈنە ئىناۋەتسىز Open mobile hotspot Network Password Contains at least 8 characters ئاز دېگەندە 8 ھەرپنى ئۆز ئىچىگە ئالىدۇ Hotspot ئېقىم نۇقتىسى Settings تەڭشەكلەر Settings desktop message ئۈستەل يۈزى ئۇچۇرى تەڭشىكى use ئىشلىتىش share network, will interrupt local wireless connection ئورتاق بەھرىمەن بولىدىغان تور، يەرلىك سىمسىز ئۇلىنىش ئۈزۈلۈپ قالىدۇ hotspot already close ئېقىم نۇقتىسى ئاللىقاچان يېپىلىپ بولدى Network Frequency band Shared NIC port Open ئېچىش Wi-Fi Name سىمسىز تور نامى Password ئىم Frequency band تور چاستوتىسى Net card ئورتاق بەھرىمەن بولىدىغان تور كارتىسى hotspot already open ئېقىم نۇقتىسى ئاللىقاچان ئېچىۋېتىلدى kylin-nm/plugins/mobilehotspot/translations/bo_CN.ts0000664000175000017500000002513215167651420021672 0ustar fengfeng BlacklistItem Remove སྤོ་སྐྱོད་བྱས་པ། BlacklistPage Blacklist སྒྲིག་ཆས་ཀྱི་མིང་ཐོ་ནག་པོ། ConnectDevListItem drag into blacklist མིང་ཐོ་ནག་པོའི་ཁ་སྣོན་རྒྱག་པ། ConnectdevPage Connect device འབྲེལ་མཐུད་སྒྲིག་ཆས། MobileHotspot MobileHotspot སྒུལ་བདེའི་ཧའོ་ཚི་ཀུང་སི། Mobile Hotspot སྒུལ་བདེའི་ཧའོ་ཚི་ཀུང་སི། /mobilehotspot/Mobile Hotspot Open mobile hotspot སྒུལ་བདེའི་འཕྲུལ་ཆས་ཀྱི་སྒོ་ཕྱེ་བ། /mobilehotspot/Open mobile hotspot Wi-Fi Name Wi-Fiཡི་མིང་། /mobilehotspot/Wi-Fi Name Network Password འབྲེལ་བརྒྱབ་སྤྱི་བདེན་ /mobilehotspot/Network Password Network Frequency band འབྲེལ་ཡུལ་འཕྲུལ་འབད་བར་ཆད་ /mobilehotspot/Network Frequency band Shared NIC port འབྲེལ་བའི་བར་འབབ་སྒྲིག /mobilehotspot/Shared NIC port Password གསང་གྲངས། /mobilehotspot/Password Frequency band ཐེངས་གྲངས་ཀྱི་རོལ་ཆའི་རུ་ཁག /mobilehotspot/Frequency band Net card དྲ་རྒྱའི་བྱང་བུ། /mobilehotspot/Net card mobilehotspot སྒུལ་བདེའི་འཕྲུལ་ཆས། MobileHotspotWidget ukui control center ཝུའུ་ཁི་ལན་གྱི་ཚོད་འཛིན་ལྟེ་གནས། ukui control center desktop message ukui ཚོད་འཛིན་ལྟེ་གནས་ཀྱི་ཅོག་ངོས་ཆ་འཕྲིན། wirless switch is close or no wireless device སྐུད་མེད་གློག་སྒོ་རྒྱག་པའམ་ཡང་ན་སྐུད་མེད་སྒྲིག་ཆས་མེད་པ། start to close hotspot སྒོ་རྒྱག་འགོ་བརྩམས། hotpots name or device is invalid ཚ་བ་ཆེ་བའི་མིང་ངམ་སྒྲིག་ཆས་ལ་ནུས་པ་མེད། can not create hotspot with password length less than eight! གསང་གྲངས་ཀྱི་རིང་ཚད་ནི་གླེང་མང་བའི་གནད་དོན་བརྒྱད་ལས་ཆུང་བ་བྱེད་མི་རུང་།! start to open hotspot ཀུན་གྱིས་དོ་སྣང་བྱེད་ཡུལ་གསར་སྐྲུན་བྱེད་འགོ་ Contains at least 8 characters མ་མཐར་ཡང་ཡིག་རྟགས་བརྒྱད་འདུས་ཡོད། Hotspot ཚ་བ་ཆེ་བ། Settings བཀོད་སྒྲིག་བཅས་བྱ་དགོས། Settings desktop message བཀོད་སྒྲིག་བཅས་བྱ་དགོས། ཅོག་ངོས་ལ་བརྡ་ཐོ་གཏོང་དགོས། use བེད་སྤྱོད། share network, will interrupt local wireless connection གླེང་མང་མཉམ་སྤྱོད་བྱས་ནས་འཕྲུལ་ཆས་ཀྱི་སྐུད་མེད་དྲ་བ་སྦྲེལ་མཐུད་བྱེད་ངེས་རེད། hotspot already close ཚ་བ་ཆེ་བའི་གནད་དོན་ཐག་ཉེ་རུ་སོང་ཡོད། Open mobile hotspot སྒུལ་བདེའི་འཕྲུལ་ཆས་ཀྱི་སྒོ་ཕྱེ་བ། Network Password འབྲེལ་བརྒྱབ་སྤྱི་བདེན་ Network Frequency band འབྲེལ་ཡུལ་འཕྲུལ་འབད་བར་ཆད་ Shared NIC port འབྲེལ་བའི་བར་འབབ་སྒྲིག Open སྒོ་ཕྱེ་བ། Wi-Fi Name Wi-Fiཡི་མིང་། Password གསང་གྲངས། Frequency band ཐེངས་གྲངས་ཀྱི་རོལ་ཆའི་རུ་ཁག Net card དྲ་རྒྱའི་བྱང་བུ། hotspot already open ཚ་བ་ཆེ་བའི་གནད་དོན་དེ་སྒོ་ཕྱེ་ཟིན། kylin-nm/plugins/mobilehotspot/translations/vi.ts0000664000175000017500000002113515167651420021327 0ustar fengfeng BlacklistItem Remove Chuyển ra ngoài BlacklistPage Blacklist Danh sách đen thiết bị ConnectDevListItem drag into blacklist Thêm vào danh sách đen ConnectdevPage Connect device Kết nối thiết bị MobileHotspot MobileHotspot Điểm truy cập di động Mobile Hotspot Điểm truy cập di động /mobilehotspot/Mobile Hotspot Open mobile hotspot Bật điểm phát sóng di động /mobilehotspot/Open mobile hotspot Wi-Fi Name Tên Wi-Fi /mobilehotspot/Wi-Fi Name Network Password Mật khẩu mạng /mobilehotspot/Network Password Network Frequency band Dải tần mạng /mobilehotspot/Network Frequency band Shared NIC port Chia sẻ cổng card mạng /mobilehotspot/Shared NIC port Password 网络密码 /mobilehotspot/Password Frequency band 网络频带 /mobilehotspot/Frequency band Net card 共享网卡端口 /mobilehotspot/Net card mobilehotspot 移动热点 MobileHotspotWidget ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 wirless switch is close or no wireless device Công tắc không dây bị tắt hoặc không có card mạng không dây có chức năng điểm phát sóng start to close hotspot 开始关闭热点 hotpots name or device is invalid Tên hoặc thiết bị điểm phát sóng sai can not create hotspot with password length less than eight! 不能创建密码长度小于八位的热点! start to open hotspot 开始创建热点 Contains at least 8 characters Chứa ít nhất 8 ký tự Hotspot Điểm truy cập di động Settings Dựng Settings desktop message Thiết lập thông báo trên màn hình nền use dùng share network, will interrupt local wireless connection Chia sẻ điểm phát sóng làm gián đoạn kết nối mạng không dây cục bộ hotspot already close Điểm phát sóng bị tắt Open mobile hotspot Bật điểm phát sóng di động Network Password Mật khẩu mạng Network Frequency band Dải tần mạng Shared NIC port Chia sẻ cổng card mạng Open 开启 Wi-Fi Name Tên Wi-Fi Password 网络密码 Frequency band 网络频带 Net card 共享网卡端口 hotspot already open Điểm phát sóng được bật kylin-nm/plugins/mobilehotspot/translations/mn.ts0000664000175000017500000002504315167651420021325 0ustar fengfeng BlacklistItem Remove ᠰᠢᠯᠵᠢᠬᠦᠯᠦᠨ ᠬᠠᠰᠤᠬᠤ BlacklistPage Blacklist ᠬᠠᠷ᠎ᠠ ᠳᠠᠩᠰᠠ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠬᠤ ConnectDevListItem drag into blacklist ᠬᠠᠷ᠎ᠠ ᠳᠠᠩᠰᠠᠨ ᠳ᠋ᠤ᠌ ᠤᠷᠤᠭᠤᠯᠬᠤ ConnectdevPage Connect device ᠳᠦᠬᠦᠬᠡᠷᠦᠮᠵᠢ ᠵᠢ ᠴᠦᠷᠬᠡᠯᠡᠬᠦ MobileHotspot MobileHotspot ᠰᠢᠯᠵᠢᠮᠡᠯ ᠬᠠᠯᠠᠭᠤᠨ ᠴᠡᠭ Mobile Hotspot ᠰᠢᠯᠵᠢᠮᠡᠯ ᠬᠠᠯᠠᠭᠤᠨ ᠴᠡᠭ /mobilehotspot/Mobile Hotspot Open mobile hotspot ᠰᠢᠯᠵᠢᠮᠡᠯ ᠬᠠᠯᠠᠭᠤᠨ ᠴᠡᠭ ᠡᠬᠢᠯᠡᠬᠦ /mobilehotspot/Open mobile hotspot Wi-Fi Name Wi-Fi ᠨᠡᠷᠡᠢᠳᠦᠯ /mobilehotspot/Wi-Fi Name Network Password ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠨᠢᠭᠤᠴᠠ ᠲᠡᠮᠳᠡᠭ /mobilehotspot/Network Password Network Frequency band ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳᠠᠪᠲᠠᠮᠵᠢ᠎ᠶ᠋ᠢᠨ ᠪᠦᠰᠡ /mobilehotspot/Network Frequency band Shared NIC port ᠬᠠᠮᠲᠤ ᠡᠳ᠋ᠯᠡᠬᠦ ᠲᠣᠣᠷ᠎ᠤ᠋ᠨ ᠺᠠᠷᠲ᠎ᠤ᠋ᠨ ᠫᠣᠷᠲ /mobilehotspot/Shared NIC port Password ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ /mobilehotspot/Password Frequency band ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠳᠠᠪᠳᠠᠮᠵᠢ ᠵᠢᠨ ᠪᠦᠰᠡ /mobilehotspot/Frequency band Net card ᠬᠠᠮᠳᠤᠪᠠᠷ ᠡᠳ᠋ᠯᠡᠬᠦ ᠨᠧᠲ ᠤ᠋ᠨ ᠦᠵᠦᠬᠦᠷ /mobilehotspot/Net card mobilehotspot ᠰᠢᠯᠵᠢᠮᠡᠯ ᠬᠠᠯᠠᠭᠤᠨ ᠴᠡᠭ MobileHotspotWidget ukui control center ᠡᠵᠡᠮᠰᠢᠯ ᠤ᠋ᠨ ᠬᠠᠪᠳᠠᠰᠤ ukui control center desktop message ᠡᠵᠡᠮᠰᠢᠯ ᠤ᠋ᠨ ᠬᠠᠪᠳᠠᠰᠤᠨ ᠤ᠋ ᠰᠢᠷᠡᠭᠡᠨ ᠨᠢᠭᠤᠷ ᠤ᠋ᠨ ᠮᠡᠳᠡᠭᠳᠡᠯ wirless switch is close or no wireless device ᠤᠲᠠᠰᠤ ᠦᠭᠡᠢ ᠨᠡᠭᠡᠭᠡᠯᠭᠡ ᠨᠢᠭᠡᠨᠲᠡ ᠬᠠᠭᠠᠭᠰᠠᠨ ᠪᠤᠶᠤ ᠬᠠᠯᠠᠭᠤᠨ ᠴᠡᠭ ᠤ᠋ᠨ ᠴᠢᠳᠠᠮᠵᠢ ᠲᠠᠢ ᠤᠲᠠᠰᠤ ᠦᠭᠡᠢ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠺᠠᠷᠲ ᠪᠠᠢᠬᠤ ᠦᠭᠡᠢ start to close hotspot ᠬᠠᠯᠠᠭᠤᠨ ᠴᠡᠭ ᠢ᠋ ᠡᠬᠢᠯᠡᠵᠤ ᠬᠠᠭᠠᠬᠤ hotpots name or device is invalid ᠬᠠᠯᠠᠭᠤᠨ ᠴᠡᠭ ᠤ᠋ᠨ ᠨᠡᠷᠡᠢᠳᠦᠯ ᠪᠤᠶᠤ ᠳᠦᠬᠦᠬᠡᠷᠦᠮᠵᠢ ᠪᠤᠷᠤᠭᠤ can not create hotspot with password length less than eight! 不能创建密码长度小于八位的热点! start to open hotspot ᠬᠠᠯᠠᠭᠤᠨ ᠴᠡᠭ ᠢ᠋ ᠡᠬᠢᠯᠡᠵᠤ ᠪᠠᠢᠭᠤᠯᠬᠤ Contains at least 8 characters ᠠᠳᠠᠭ ᠲᠤ᠌ ᠪᠡᠨ 8 ᠦᠰᠦᠭ ᠳᠡᠮᠳᠡᠭ ᠠᠭᠤᠯᠠᠭᠳᠠᠵᠤ ᠪᠠᠢᠨ᠎ᠠ Hotspot ᠰᠢᠯᠵᠢᠮᠡᠯ ᠬᠠᠯᠠᠭᠤᠨ ᠴᠡᠭ Settings ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Settings desktop message ᠰᠢᠷᠡᠭᠡᠨ ᠨᠢᠭᠤᠷ᠎ᠤ᠋ᠨ ᠵᠠᠩᠭᠢ᠎ᠶ᠋ᠢ ᠵᠣᠬᠢᠷᠠᠭᠤᠯᠬᠤ use ᠬᠡᠷᠡᠭᠯᠡᠬᠦ share network, will interrupt local wireless connection ᠬᠠᠮᠲᠤ ᠡᠳ᠋ᠯᠡᠬᠦ ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠂ ᠲᠤᠰ ᠭᠠᠵᠠᠷ᠎ᠤ᠋ᠨ ᠤᠲᠠᠰᠤᠭᠤᠢ ᠵᠠᠯᠭᠠᠯᠲᠠ᠎ᠶ᠋ᠢ ᠲᠠᠰᠤᠯᠠᠬᠤ hotspot already close ᠬᠠᠯᠠᠭᠤᠨ ᠴᠡᠭ ᠢ᠋ ᠬᠠᠭᠠᠪᠠ Open mobile hotspot ᠰᠢᠯᠵᠢᠮᠡᠯ ᠬᠠᠯᠠᠭᠤᠨ ᠴᠡᠭ ᠡᠬᠢᠯᠡᠬᠦ Network Password ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠨᠢᠭᠤᠴᠠ ᠲᠡᠮᠳᠡᠭ Network Frequency band ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳᠠᠪᠲᠠᠮᠵᠢ᠎ᠶ᠋ᠢᠨ ᠪᠦᠰᠡ Shared NIC port ᠬᠠᠮᠲᠤ ᠡᠳ᠋ᠯᠡᠬᠦ ᠲᠣᠣᠷ᠎ᠤ᠋ᠨ ᠺᠠᠷᠲ᠎ᠤ᠋ᠨ ᠫᠣᠷᠲ Open ᠨᠡᠭᠡᠭᠡᠭᠦ Wi-Fi Name Wi-Fi ᠨᠡᠷᠡᠢᠳᠦᠯ Password ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ Frequency band ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠳᠠᠪᠳᠠᠮᠵᠢ ᠵᠢᠨ ᠪᠦᠰᠡ Net card ᠬᠠᠮᠳᠤᠪᠠᠷ ᠡᠳ᠋ᠯᠡᠬᠦ ᠨᠧᠲ ᠤ᠋ᠨ ᠦᠵᠦᠬᠦᠷ hotspot already open ᠬᠠᠯᠠᠭᠤᠨ ᠴᠡᠭ ᠢ᠋ ᠨᠡᠬᠡᠬᠡᠪᠡ kylin-nm/plugins/mobilehotspot/translations/zh_Hant.ts0000664000175000017500000001770515167651420022314 0ustar fengfeng BlacklistItem Remove 刪除 BlacklistPage Blacklist 黑名單 ConnectDevListItem drag into blacklist 加入黑名單 ConnectdevPage Connect device 連接設備 MobileHotspot MobileHotspot 移動熱點 Mobile Hotspot 移動熱點 /mobilehotspot/Mobile Hotspot Open mobile hotspot 打開移動熱點 /mobilehotspot/Open mobile hotspot Wi-Fi Name 無線網絡名稱 /mobilehotspot/Wi-Fi Name Network Password 網絡密碼 /mobilehotspot/Network Password Network Frequency band 網絡頻帶 /mobilehotspot/Network Frequency band Shared NIC port 共用網卡埠 /mobilehotspot/Shared NIC port Password 網絡密碼 /mobilehotspot/Password Frequency band 網絡頻帶 /mobilehotspot/Frequency band Net card 共享網卡埠 /mobilehotspot/Net card mobilehotspot 移動熱點 MobileHotspotWidget ukui control center 烏奎控制中心 ukui control center desktop message UKUI 控制中心桌面消息 wirless switch is close or no wireless device 無線開關已關閉或不存在有熱點功能的無線網卡 start to close hotspot 開始關閉熱點 hotpots name or device is invalid 熱點名稱或設備錯誤 can not create hotspot with password length less than eight! 不能创建密码长度小于八位的热点! start to open hotspot 開始打開熱點 Contains at least 8 characters 至少包含8個字元 Hotspot 移動熱點 Settings 設置 Settings desktop message 設置桌面通知 use 使用 share network, will interrupt local wireless connection 共亯網絡,將中斷本地無線連接 hotspot already close 熱點已關閉 Open mobile hotspot 打開移動熱點 Network Password 網絡密碼 Network Frequency band 網絡頻帶 Shared NIC port 共用網卡埠 Open 打開 Wi-Fi Name Wi-Fi 名稱 Password 密碼 Frequency band 頻帶 Net card 網卡 hotspot already open 熱點已打開 kylin-nm/plugins/mobilehotspot/translations/fr.ts0000664000175000017500000002024015167646234021323 0ustar fengfeng BlacklistItem Remove Enlever BlacklistPage Blacklist Liste noire ConnectDevListItem drag into blacklist Glissez dans la liste noire ConnectdevPage Connect device Connecter l’appareil MobileHotspot MobileHotspot MobileHotspot (en anglais seulement) Mobile Hotspot Hotspots mobiles /mobilehotspot/Mobile Hotspot Open mobile hotspot Ouvrir un Hotspot mobile /mobilehotspot/Open mobile hotspot Wi-Fi Name Nom du Wi-Fi /mobilehotspot/Wi-Fi Name Network Password Mot de passe réseau /mobilehotspot/Network Password Network Frequency band Bande de fréquences réseau /mobilehotspot/Network Frequency band Shared NIC port Port de carte réseau partagé /mobilehotspot/Shared NIC port mobilehotspot mobilehotspot /mobilehotspot/mobilehotspot mobilehotspot open mobilehotspot ouvert /mobilehotspot/mobilehotspot open MobileHotspotWidget ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 wirless switch is close or no wireless device L’interrupteur sans fil est proche ou aucun appareil sans fil start to close hotspot 开始关闭热点 hotpots name or device is invalid Le nom ou l’appareil des pots chauds n’est pas valide can not create hotspot with password length less than eight! 不能创建密码长度小于八位的热点! start to open hotspot 开始创建热点 Contains at least 8 characters Contient au moins 8 caractères Hotspot Point d’accès Settings Paramètres Settings desktop message Message sur le bureau des paramètres use utiliser share network, will interrupt local wireless connection partager le réseau, interrompra la connexion sans fil locale hotspot already close hotspot déjà proche Open mobile hotspot Ouvrir un Hotspot mobile Network Password Mot de passe réseau Network Frequency band Bande de fréquences réseau Shared NIC port Port de carte réseau partagé Open Ouvrir Wi-Fi Name Nom du Wi-Fi Password Mot de passe Frequency band Bande de fréquence Net card Carte réseau hotspot already open hotspot déjà ouvert kylin-nm/plugins/mobilehotspot/translations/en_US.ts0000664000175000017500000001700215167651420021720 0ustar fengfeng BlacklistItem Remove Remove BlacklistPage Blacklist Blacklist ConnectDevListItem drag into blacklist drag into blacklist ConnectdevPage Connect device Connect device MobileHotspot MobileHotspot MobileHotspot Mobile Hotspot Mobile Hotspot /mobilehotspot/Mobile Hotspot Open mobile hotspot Open mobile hotspot /mobilehotspot/Open mobile hotspot Wi-Fi Name Wi-Fi Name /mobilehotspot/Wi-Fi Name Network Password /mobilehotspot/Network Password Network Frequency band /mobilehotspot/Network Frequency band Shared NIC port /mobilehotspot/Shared NIC port Password Password /mobilehotspot/Password Frequency band Frequency band /mobilehotspot/Frequency band Net card Net card /mobilehotspot/Net card mobilehotspot mobilehotspot MobileHotspotWidget ukui control center ukui control center ukui control center desktop message ukui control center desktop message Settings Settings desktop message wirless switch is close or no wireless device wirless switch is close or no wireless device hotpots name or device is invalid hotpots name or device is invalid Hotspot Hotspot use share network, will interrupt local wireless connection hotspot already close hotspot already close Open mobile hotspot Open mobile hotspot Network Password Network Frequency band Shared NIC port Open Open Wi-Fi Name Wi-Fi Name Password Password Contains at least 8 characters Contains at least 8 characters Frequency band Frequency band Net card Net card hotspot already open hotspot already open kylin-nm/plugins/mobilehotspot/translations/es.ts0000664000175000017500000002031415167646234021325 0ustar fengfeng BlacklistItem Remove Eliminar BlacklistPage Blacklist Lista negra ConnectDevListItem drag into blacklist arrastrar a la lista negra ConnectdevPage Connect device Conectar dispositivo MobileHotspot MobileHotspot Hotspot móvil Mobile Hotspot Hotspot móvil /mobilehotspot/Mobile Hotspot Open mobile hotspot Abrir puntos calientes móviles /mobilehotspot/Open mobile hotspot Wi-Fi Name Nombre de Wi-Fi /mobilehotspot/Wi-Fi Name Network Password Contraseña de red /mobilehotspot/Network Password Network Frequency band Banda de frecuencia de la red /mobilehotspot/Network Frequency band Shared NIC port Puerto de tarjeta de red compartida /mobilehotspot/Shared NIC port mobilehotspot Hotspot móvil /mobilehotspot/mobilehotspot mobilehotspot open MobileHotspot abierto /mobilehotspot/mobilehotspot open MobileHotspotWidget ukui control center 控制面板 ukui control center desktop message 控制面板桌面通知 wirless switch is close or no wireless device El interruptor inalámbrico está cerca o no hay ningún dispositivo inalámbrico start to close hotspot 开始关闭热点 hotpots name or device is invalid El nombre o el dispositivo de Hotpots no son válidos can not create hotspot with password length less than eight! 不能创建密码长度小于八位的热点! start to open hotspot 开始创建热点 Contains at least 8 characters Contiene al menos 8 caracteres Hotspot Punto de acceso Settings Configuración Settings desktop message Mensaje de escritorio de configuración use uso share network, will interrupt local wireless connection red compartida, interrumpirá la conexión inalámbrica local hotspot already close El punto de acceso ya está cerrado Open mobile hotspot Abrir puntos calientes móviles Network Password Contraseña de red Network Frequency band Banda de frecuencia de la red Shared NIC port Puerto de tarjeta de red compartida Open Abrir Wi-Fi Name Nombre de Wi-Fi Password Contraseña Frequency band Banda de frecuencias Net card Tarjeta de red hotspot already open El punto de acceso ya está abierto kylin-nm/plugins/mobilehotspot/translations/zh_HK.ts0000664000175000017500000001526215167651420021720 0ustar fengfeng BlacklistItem Remove 移出 BlacklistPage Blacklist 設置黑名單 ConnectDevListItem drag into blacklist 添加進黑名單 ConnectdevPage Connect device 連接設備 MobileHotspot MobileHotspot 移動熱點 mobilehotspot 移動熱點 /mobilehotspot/mobilehotspot mobilehotspot open 移動熱點開啓 /mobilehotspot/mobilehotspot open Mobile Hotspot 移動熱點 /mobilehotspot/Mobile Hotspot Open mobile hotspot 開啓移動熱點 /mobilehotspot/Open mobile hotspot Wi-Fi Name Wi-Fi 名稱 /mobilehotspot/Wi-Fi Name Network Password 網絡密碼 /mobilehotspot/Network Password Network Frequency band 網絡頻帶 /mobilehotspot/Network Frequency band Shared NIC port 共享網卡端口 /mobilehotspot/Shared NIC port MobileHotspotWidget Settings 設置 Settings desktop message 設置 桌面通知 wirless switch is close or no wireless device 無線開關已關閉或不存在有熱點功能的無線網卡 hotpots name or device is invalid 熱點名稱或設備錯誤 Hotspot 移動熱點 use 使用 share network, will interrupt local wireless connection 進行熱點共享,會中斷本機無線網絡連接 hotspot already close 熱點已關閉 Open mobile hotspot 開啓移動熱點 Wi-Fi Name Wi-Fi 名稱 Network Password 網絡密碼 Contains at least 8 characters 至少包含8個字符 Network Frequency band 網絡頻帶 Shared NIC port 共享網卡端口 hotspot already open 熱點已開啓 kylin-nm/plugins/mobilehotspot/blacklistitem.h0000664000175000017500000000273315167646234020632 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef BLACKLISTITEM_H #define BLACKLISTITEM_H #include #include #include #include #include #include #include #include "kborderlessbutton.h" using namespace kdk; class BlacklistItem : public QFrame { Q_OBJECT public: BlacklistItem(QString staMac, QString staName, QWidget *parent = nullptr); protected: KBorderlessButton *m_removeFromBlacklistBtn = nullptr; QString m_mac; QString m_hostName; bool eventFilter(QObject *w, QEvent *e); signals: void onBtnClicked(QString staMac, QString staName); }; #endif // LISTITEM_H kylin-nm/plugins/mobilehotspot/blacklistitem.cpp0000664000175000017500000000454615167646234021171 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "blacklistitem.h" #include #define MAIN_LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_SPACING 0 #define ITEM_FRAME_MARGINS 0,0,0,0 #define ITEM_FRAME_SPACING 10 #define FRAME_WIDTH 395 #define INFO_ICON_WIDTH 16 #define INFO_ICON_HEIGHT 16 #define LIGHT_HOVER_COLOR QColor(240,240,240,255) #define DARK_HOVER_COLOR QColor(15,15,15,255) #define FRAME_MIN_SIZE 550, 60 #define CONTECT_FRAME_MAX_SIZE 16777215, 60 #define LABLE_MIN_WIDTH 188 #define ITEM_MARGINS 16, 0, 16, 0 BlacklistItem::BlacklistItem(QString staMac, QString staName, QWidget *parent) : QFrame(parent), m_mac(staMac), m_hostName(staName) { this->setMinimumHeight(60); this->setFixedHeight(60); QHBoxLayout *hItemLayout = new QHBoxLayout(this); hItemLayout->setContentsMargins(ITEM_MARGINS); QLabel *nameLabel = new QLabel(staName, this); m_removeFromBlacklistBtn = new KBorderlessButton(this); m_removeFromBlacklistBtn->setText(tr("Remove")); hItemLayout->setSpacing(0); hItemLayout->addWidget(nameLabel, Qt::AlignLeft); hItemLayout->addStretch(); hItemLayout->addWidget(m_removeFromBlacklistBtn, Qt::AlignRight); m_removeFromBlacklistBtn->installEventFilter(this); this->setLayout(hItemLayout); } bool BlacklistItem::eventFilter(QObject *w, QEvent *e) { if (e->type() == QEvent::MouseButtonRelease) { if (w == m_removeFromBlacklistBtn) { emit onBtnClicked(m_mac, m_hostName); return true; } } return QWidget::eventFilter(w,e); } kylin-nm/plugins/mobilehotspot/connectdevlistitem.cpp0000664000175000017500000000460715167646234022243 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "connectdevlistitem.h" #include #define MAIN_LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_SPACING 0 #define ITEM_FRAME_MARGINS 0,0,0,0 #define ITEM_FRAME_SPACING 10 #define FRAME_WIDTH 395 #define INFO_ICON_WIDTH 16 #define INFO_ICON_HEIGHT 16 #define LIGHT_HOVER_COLOR QColor(240,240,240,255) #define DARK_HOVER_COLOR QColor(15,15,15,255) #define FRAME_MIN_SIZE 550, 60 #define CONTECT_FRAME_MAX_SIZE 16777215, 60 #define LABLE_MIN_WIDTH 188 #define ITEM_MARGINS 16, 0, 16, 0 ConnectDevListItem::ConnectDevListItem(QString staMac, QString staName, QWidget *parent) : QFrame(parent), m_mac(staMac), m_hostName(staName) { this->setMinimumSize(FRAME_MIN_SIZE); this->setFixedHeight(60); QHBoxLayout *hItemLayout = new QHBoxLayout(this); hItemLayout->setContentsMargins(ITEM_MARGINS); QLabel *nameLabel = new QLabel(staName, this); m_dragIntoBlackListBtn = new KBorderlessButton(this); m_dragIntoBlackListBtn->setText(tr("drag into blacklist")); hItemLayout->setSpacing(0); hItemLayout->addWidget(nameLabel, Qt::AlignLeft); hItemLayout->addStretch(); hItemLayout->addWidget(m_dragIntoBlackListBtn, Qt::AlignRight); m_dragIntoBlackListBtn->installEventFilter(this); this->setLayout(hItemLayout); } bool ConnectDevListItem::eventFilter(QObject *w, QEvent *e) { if (e->type() == QEvent::MouseButtonRelease) { if (w == m_dragIntoBlackListBtn) { emit onBtnClicked(m_mac, m_hostName); return true; } } return QWidget::eventFilter(w,e); } kylin-nm/plugins/mobilehotspot/translate_generation.sh0000775000175000017500000000056615167651420022374 0ustar fengfeng#!/bin/bash export PATH="/usr/lib/qt6/bin:$PATH" ts_list=(`ls translations/*.ts`) source /etc/os-release version=(`echo $ID`) for ts in "${ts_list[@]}" do printf "\nprocess ${ts}\n" if [ "$version" == "fedora" ] || [ "$version" == "opensuse-leap" ] || [ "$version" == "opensuse-tumbleweed" ];then lrelease-qt5 "${ts}" else lrelease "${ts}" fi done kylin-nm/plugins/mobilehotspot/connectdevlistitem.h0000664000175000017500000000275515167646234021712 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef CONNECTDEVLISTITEM_H #define CONNECTDEVLISTITEM_H #include #include #include #include #include #include #include #include "kborderlessbutton.h" using namespace kdk; class ConnectDevListItem : public QFrame { Q_OBJECT public: ConnectDevListItem(QString staMac, QString staName, QWidget *parent = nullptr); protected: KBorderlessButton *m_dragIntoBlackListBtn = nullptr; QString m_mac; QString m_hostName; bool eventFilter(QObject *w, QEvent *e); signals: void onBtnClicked(QString staMac, QString staName); }; #endif // LISTITEM_H kylin-nm/plugins/mobilehotspot/mobilehotspot.h0000664000175000017500000000415315167646234020671 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef MOBILEHOTSPOT_H #define MOBILEHOTSPOT_H #include #include #include #include #include #include #include #include #include #include "interface.h" #include "switchbutton.h" #include "hoverbtn.h" #include "mobilehotspotwidget.h" namespace Ui { class MobileHotspot; } class MobileHotspot : public QObject, CommonInterface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.ukcc.CommonInterface") Q_INTERFACES(CommonInterface) public: MobileHotspot(); ~MobileHotspot(); QString plugini18nName() Q_DECL_OVERRIDE; int pluginTypes() Q_DECL_OVERRIDE; QWidget * pluginUi() Q_DECL_OVERRIDE; const QString name() const Q_DECL_OVERRIDE; bool isShowOnHomePage() const Q_DECL_OVERRIDE; QIcon icon() const Q_DECL_OVERRIDE; bool isEnable() const Q_DECL_OVERRIDE; QString translationPath() const Q_DECL_OVERRIDE; private: void initSearchText(); bool isExitWirelessDevice(); QString pluginName; int pluginType; MobileHotspotWidget *pluginWidget; private: bool mFirstLoad; bool needLoad; }; #endif // MOBILEHOTSPOT_H kylin-nm/plugins/mobilehotspot/mobilehotspot.cpp0000664000175000017500000001215515167651420021216 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "mobilehotspot.h" #include #include MobileHotspot::MobileHotspot() : mFirstLoad(true) { QTranslator* translator = new QTranslator(this); qDebug() << "/usr/share/kylin-nm/mobilehotspot/" + QLocale::system().name(); if (!translator->load("/usr/share/kylin-nm/mobilehotspot/" + QLocale::system().name())) { qDebug() << "load failed"; } QApplication::installTranslator(translator); pluginName = tr("MobileHotspot"); qDebug() << pluginName; pluginType = NETWORK; qDBusRegisterMetaType >(); qDBusRegisterMetaType >(); needLoad = isExitWirelessDevice(); } MobileHotspot::~MobileHotspot() { if (!mFirstLoad) { // delete pluginWidget; // pluginWidget = nullptr; } } QString MobileHotspot::plugini18nName() { return pluginName; } int MobileHotspot::pluginTypes() { return pluginType; } QWidget *MobileHotspot::pluginUi() { if (mFirstLoad) { mFirstLoad = false; pluginWidget = new MobileHotspotWidget; pluginWidget->setAttribute(Qt::WA_DeleteOnClose); } return pluginWidget; } const QString MobileHotspot::name() const { return QStringLiteral("mobilehotspot"); } bool MobileHotspot::isEnable() const { qDebug() << needLoad; return needLoad; } bool MobileHotspot::isShowOnHomePage() const { return false; } QIcon MobileHotspot::icon() const { return QIcon::fromTheme("ukui-hotspot-symbolic"); } QString MobileHotspot::translationPath() const { return "/usr/share/kylin-nm/mobilehotspot/%1.ts"; } void MobileHotspot::initSearchText() { //~ contents_path /mobilehotspot/mobilehotspot tr("mobilehotspot"); //~ contents_path /mobilehotspot/mobilehotspot open tr("mobilehotspot open"); //~ contents_path /mobilehotspot/Mobile Hotspot tr("Mobile Hotspot"); //~ contents_path /mobilehotspot/Open mobile hotspot tr("Open mobile hotspot"); //~ contents_path /mobilehotspot/Wi-Fi Name tr("Wi-Fi Name"); //~ contents_path /mobilehotspot/Network Password tr("Network Password"); //~ contents_path /mobilehotspot/Network Frequency band tr("Network Frequency band"); //~ contents_path /mobilehotspot/Shared NIC port tr("Shared NIC port"); } bool MobileHotspot::isExitWirelessDevice() { QDBusInterface *interface = new QDBusInterface("com.kylin.network", "/com/kylin/network", "com.kylin.network", QDBusConnection::sessionBus()); if (!interface->isValid()) { qDebug() << "/com/kylin/network is invalid"; return false; } QDBusReply reply = interface->call(QStringLiteral("getDeviceListAndEnabled"),1); if(!reply.isValid()) { qWarning() << "getWirelessDeviceList error:" << reply.error().message(); return false; } QMap deviceListMap; QVariantMap::const_iterator itemIter = reply.value().cbegin(); while (itemIter != reply.value().cend()) { deviceListMap.insert(itemIter.key(), itemIter.value().toBool()); itemIter ++; } QDBusReply capReply = interface->call("getWirelessDeviceCap"); if (!capReply.isValid()) { qDebug()<<"execute dbus method 'getWirelessDeviceCap' is invalid in func initInterfaceInfo()" < devCapMap; QVariantMap::const_iterator item = reply.value().cbegin(); while (item != reply.value().cend()) { devCapMap.insert(item.key(), item.value().toInt()); item ++; } if (deviceListMap.isEmpty()) { qDebug() << "no wireless device"; return false; } else { QMap::Iterator iter = deviceListMap.begin(); while (iter != deviceListMap.end()) { QString interfaceName = iter.key(); if (!devCapMap.contains(interfaceName)) { iter++; continue; } if (devCapMap[interfaceName] & 0x01) { qDebug() << "wireless device" << interfaceName << "support hotspot"; return true; } iter++; } } qDebug() << "no wireless device support hotspot"; return false; } kylin-nm/plugins/mobilehotspot/mobilehotspotwidget.h0000664000175000017500000001161215167651420022064 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef MOBILEHOTSPOTWIDGET_H #define MOBILEHOTSPOTWIDGET_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kwidget.h" #include "kswitchbutton.h" #include "kpasswordedit.h" #include "connectdevlistitem.h" #include "blacklistpage.h" #include "connectdevpage.h" #include "ukcccommon.h" #include "klabel.h" using namespace kdk; using namespace ukcc; class MobileHotspotWidget : public QWidget { Q_OBJECT public: explicit MobileHotspotWidget(QWidget *parent = nullptr); ~MobileHotspotWidget(); private: QFrame *m_hotspotFrame = nullptr; QFrame *m_switchFrame = nullptr; //开关 QFrame *m_ApNameFrame = nullptr; //wifi名称 QFrame *m_passwordFrame = nullptr; //密码 QFrame *m_freqBandFrame = nullptr; //频带 QFrame *m_interfaceFrame = nullptr; //网卡 KSwitchButton *m_switchBtn; KLabel *m_hotspotTitleLabel; QLabel *m_switchLabel; QLabel *m_apNameLabel; KLabel *m_pwdLabel; QLabel *m_pwdHintLabel; KLabel *m_freqBandLabel; KLabel *m_interfaceLabel; QFrame *switchAndApNameLine; QFrame *apNameAndPwdLine; QFrame *pwdAndfreqBandLine; QFrame *freqBandAndInterfaceLine; QVBoxLayout *m_Vlayout; QLineEdit *m_apNameLine; KPasswordEdit *m_pwdNameLine; QComboBox *m_freqBandComboBox; QComboBox *m_interfaceComboBox; KLabel *m_interfaceWarnLabel; QWidget* m_warnWidget; QDBusInterface *m_interface = nullptr; QString m_interfaceName = ""; QGSettings *m_switchGsettings = nullptr; QString m_uuid = ""; QString m_hostName = ""; QLabel *m_statusLabel; QTimer *m_waitTimer = nullptr; QList m_loadIcons; int m_currentIconIndex=0; void updateLoadingIcon(); void resetFrameSize(); void initUI(); void initDbusConnect(); void initInterfaceInfo(); void getApInfo(); bool getApInfoBySsid(QString devName, QString ssid, QStringList &info); void setSwitchFrame(); void setApNameFrame(); void setPasswordFrame(); void setFreqBandFrame(); void setInterFaceFrame(); void setUiEnabled(bool enable); void setWidgetHidden(bool isHidden); void showDesktopNotify(const QString &message); void updateBandCombox(); QString getHostName(); bool eventFilter(QObject *watched, QEvent *event); void paintEvent(QPaintEvent *event); QFrame* myLine(); QDBusInterface *m_activePathInterface = nullptr; QDBusInterface *m_settingPathInterface = nullptr; ConnectdevPage * m_connectDevPage = nullptr; BlacklistPage *m_blacklistPage = nullptr; QString getActivePathByUuid(); QString getSettingPathByUuid(); void initNmDbus(); void initActivePathInterface(QString path); void deleteActivePathInterface(); void initSettingPathInterface(QString path); void deleteSettingPathInterface(); void initConnectDevPage(); void initBlackListPage(); bool m_isUserSelect = true; //是否用户操作 signals: private slots: void onActivateFailed(QString errorMessage); void onDeactivateFailed(QString errorMessage); //设备插拔 void onDeviceStatusChanged(); void onDeviceNameChanged(QString oldName, QString newName, int type); //热点断开 void onHotspotDeactivated(QString devName, QString ssid); //热点连接 void onHotspotActivated(QString devName, QString ssid, QString uuid, QString activePath, QString settingPath); void onWirelessBtnChanged(bool state); void onActiveConnectionChanged(QString deviceName, QString ssid, QString uuid, int status); void onApLineEditTextEdit(QString text); void onPwdTextChanged(); void onInterfaceChanged(); void startLoading(); void stopLoading(); }; #endif // MOBILEHOTSPOTWIDGET_H kylin-nm/plugins/mobilehotspot/mobilehotspotwidget.cpp0000664000175000017500000011233115167651420022417 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "mobilehotspotwidget.h" #include #include #define LABEL_RECT 17, 0, 105, 23 #define CONTENTS_MARGINS 0, 0, 0, 0 #define ITEM_MARGINS 16, 0, 16, 0 #define FRAME_MIN_SIZE 550, 60 #define FRAME_MAX_SIZE 16777215, 16777215 #define CONTECT_FRAME_MAX_SIZE 16777215, 60 #define HINT_TEXT_MARGINS 8, 0, 0, 0 #define FRAME_MIN_SIZE 550, 60 #define LABLE_MIN_WIDTH 188 #define COMBOBOX_MIN_WIDTH 200 #define LINE_MAX_SIZE 16777215, 1 #define LINE_MIN_SIZE 0, 1 #define ICON_SIZE 24,24 #define PASSWORD_FRAME_MIN_HIGHT 60 #define PASSWORD_FRAME_FIX_HIGHT 90 #define PASSWORD_FRAME_MIN_SIZE 550, 60 #define PASSWORD_FRAME_MAX_SIZE 16777215, 90 #define PASSWORD_ITEM_MARGINS 16, 10, 16, 10 #define WIRELESS 1 #define AP_NAME_MAX_LENGTH 32 #define REFRESH_MSEC 20*1000 #define FRAME_SPEED 150 #define LOG_HEAD "[MobileHotspotWidget]" const QByteArray GSETTINGS_SCHEMA = "org.ukui.kylin-nm.switch"; const QString WIRELESS_SWITCH = "wirelessswitch"; void MobileHotspotWidget::showDesktopNotify(const QString &message) { QDBusInterface iface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus()); QList args; args<<(tr("Settings")) <<((unsigned int) 0) <setContentsMargins(CONTENTS_MARGINS); m_Vlayout->setSpacing(0); qDBusRegisterMetaType >(); qDBusRegisterMetaType >(); qDBusRegisterMetaType >(); qDBusRegisterMetaType >>(); initUI(); #ifdef HOTSPOT_CONTROL initConnectDevPage(); initBlackListPage(); #endif m_switchBtn->installEventFilter(this); m_interface = new QDBusInterface("com.kylin.network", "/com/kylin/network", "com.kylin.network", QDBusConnection::sessionBus()); if(!m_interface->isValid()) { qDebug() << LOG_HEAD << "dbus interface com.kylin.network is invaild"; m_switchBtn->setChecked(false); setUiEnabled(false); } m_hostName = getHostName(); initDbusConnect(); initInterfaceInfo(); getApInfo(); #ifdef HOTSPOT_CONTROL initNmDbus(); #endif this->setLayout(m_Vlayout); m_Vlayout->addStretch(); connect(m_switchBtn, &KSwitchButton::stateChanged, this, &MobileHotspotWidget::setUiEnabled); connect(m_interfaceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &MobileHotspotWidget::onInterfaceChanged); connect(m_interfaceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [=]() { UkccCommon::buriedSettings("MobileHotspot", "Net card", QString("select"), m_interfaceComboBox->currentText()); m_interfaceName = m_interfaceComboBox->currentText(); updateBandCombox(); }); connect(m_freqBandComboBox, QOverload::of(&QComboBox::currentIndexChanged), [=](){ if (m_isUserSelect && !m_freqBandComboBox->currentText().isEmpty()) { UkccCommon::buriedSettings("MobileHotspot", "Frequency band", QString("select"), m_freqBandComboBox->currentText()); } }); onInterfaceChanged(); #ifdef HOTSPOT_CONTROL m_connectDevPage->refreshStalist(); m_blacklistPage->refreshBlacklist(); #endif this->update(); } MobileHotspotWidget::~MobileHotspotWidget() { deleteActivePathInterface(); deleteSettingPathInterface(); delete m_interface; } bool MobileHotspotWidget::eventFilter(QObject *watched, QEvent *event) { if (event->type() == QEvent::MouseButtonDblClick && watched == m_switchBtn) { return true; } if (watched == m_switchBtn && m_switchBtn->isEnabled()) { if (event->type() == QEvent::MouseButtonRelease) { if (!m_interface->isValid()) { return true; } if (!m_switchBtn->isCheckable()) { showDesktopNotify(tr("wirless switch is close or no wireless device")); return true; } UkccCommon::buriedSettings("MobileHotspot", "Open", QString("settings"), !m_switchBtn->isChecked() ? "true":"false"); if (m_switchBtn->isChecked()) { // showDesktopNotify(tr("start to close hotspot")); QDBusReply reply = m_interface->call("deactiveWirelessAp", m_apNameLine->text(), m_uuid); if (!reply.isValid()) { qDebug() << LOG_HEAD << "call deactiveWirelessAp failed "; return true; } #ifdef HOTSPOT_CONTROL deleteActivePathInterface(); m_connectDevPage->setInterface(nullptr); m_connectDevPage->refreshStalist(); m_blacklistPage->refreshBlacklist(); #endif this->update(); } else { if (m_apNameLine->text().isEmpty() || m_interfaceName.isEmpty()) { showDesktopNotify(tr("hotpots name or device is invalid")); return true; } if (m_pwdNameLine->text().length() < 8) { // showDesktopNotify(tr("can not create hotspot with password length less than eight!")); return true; } // showDesktopNotify(tr("start to open hotspot ") + m_apNameLine->text()); QDBusReply reply = m_interface->call("activeWirelessAp", m_apNameLine->text(), m_pwdNameLine->text(), m_freqBandComboBox->currentText(), m_interfaceComboBox->currentText()); if (!reply.isValid()) { qDebug() << LOG_HEAD << "call activeWirelessAp failed "; return true; } } return true; } } return QWidget::eventFilter(watched, event); } void MobileHotspotWidget::paintEvent(QPaintEvent *event) { QWidget::paintEvent(event); } void MobileHotspotWidget::resetFrameSize() { int height = 0; for (int i = 0; i < m_hotspotFrame->layout()->count(); i ++) { QWidget *w = m_hotspotFrame->layout()->itemAt(i)->widget(); if (w != nullptr && !w->isHidden()) { height += w->height(); } } m_hotspotFrame->setFixedHeight(height); } void MobileHotspotWidget::initUI() { m_hotspotFrame = new QFrame(this); m_hotspotFrame->setMinimumSize(FRAME_MIN_SIZE); m_hotspotFrame->setMaximumSize(FRAME_MAX_SIZE); m_hotspotFrame->setFrameShape(QFrame::Box); QVBoxLayout *hotspotLyt = new QVBoxLayout(this); hotspotLyt->setContentsMargins(0, 0, 0, 0); m_hotspotFrame->setLayout(hotspotLyt); m_hotspotTitleLabel = new KLabel(this); m_hotspotTitleLabel->setText(tr("Hotspot")); m_hotspotTitleLabel->setContentsMargins(16, 0, 0, 0); setSwitchFrame(); setApNameFrame(); setPasswordFrame(); setFreqBandFrame(); setInterFaceFrame(); switchAndApNameLine = myLine(); apNameAndPwdLine = myLine(); pwdAndfreqBandLine = myLine(); freqBandAndInterfaceLine = myLine(); hotspotLyt->addWidget(m_switchFrame); hotspotLyt->addWidget(switchAndApNameLine); hotspotLyt->addWidget(m_ApNameFrame); hotspotLyt->addWidget(apNameAndPwdLine); hotspotLyt->addWidget(m_passwordFrame); hotspotLyt->addWidget(pwdAndfreqBandLine); hotspotLyt->addWidget(m_freqBandFrame); hotspotLyt->addWidget(freqBandAndInterfaceLine); hotspotLyt->addWidget(m_interfaceFrame); hotspotLyt->setSpacing(0); resetFrameSize(); m_Vlayout->addWidget(m_hotspotTitleLabel); m_Vlayout->addSpacing(8); m_Vlayout->addWidget(m_hotspotFrame); } void MobileHotspotWidget::initDbusConnect() { if(m_interface->isValid()) { connect(m_interface,SIGNAL(activateFailed(QString)), this, SLOT(onActivateFailed(QString)), Qt::QueuedConnection); connect(m_interface,SIGNAL(deactivateFailed(QString)), this, SLOT(onDeactivateFailed(QString)), Qt::QueuedConnection); connect(m_interface,SIGNAL(wirelessDeviceStatusChanged()), this, SLOT(onDeviceStatusChanged()), Qt::QueuedConnection); connect(m_interface,SIGNAL(deviceNameChanged(QString, QString, int)), this, SLOT(onDeviceNameChanged(QString, QString, int)), Qt::QueuedConnection); connect(m_interface,SIGNAL(hotspotDeactivated(QString, QString)), this, SLOT(onHotspotDeactivated(QString, QString)), Qt::QueuedConnection); connect(m_interface,SIGNAL(hotspotActivated(QString, QString, QString, QString, QString)), this, SLOT(onHotspotActivated(QString, QString, QString, QString, QString)), Qt::QueuedConnection); connect(m_interface,SIGNAL(hotspotDeactivating(QString, QString)), this, SLOT(startLoading()), Qt::QueuedConnection); connect(m_interface,SIGNAL(hotspotActivating(QString, QString)), this, SLOT(startLoading()), Qt::QueuedConnection); connect(m_interface, SIGNAL(wlanactiveConnectionStateChanged(QString, QString, QString, int)), this, SLOT(onActiveConnectionChanged(QString, QString, QString, int)), Qt::QueuedConnection); connect(m_interface, SIGNAL(wirelessSwitchBtnChanged(bool)), this, SLOT(onWirelessBtnChanged(bool)), Qt::QueuedConnection); } connect(m_apNameLine, &QLineEdit::textEdited, this, &MobileHotspotWidget::onApLineEditTextEdit); #ifdef HOTSPOT_CONTROL connect(m_connectDevPage, SIGNAL(setStaIntoBlacklist(QString, QString)), m_blacklistPage, SLOT(onsetStaIntoBlacklist(QString, QString))); #endif connect(m_pwdNameLine, SIGNAL(textChanged(QString)), this, SLOT(onPwdTextChanged())); } void MobileHotspotWidget::onApLineEditTextEdit(QString text) { int count = 0; int i = 0; if (text.toLocal8Bit().length() <= AP_NAME_MAX_LENGTH) { return; } int index = m_apNameLine->cursorPosition(); QString leftStr = text.left(index); QString rightStr = text.mid(index); if (rightStr.isEmpty()) { for ( ; i < text.length(); ++i) { count += text.mid(i,1).toLocal8Bit().length(); if (count > AP_NAME_MAX_LENGTH) { m_apNameLine->setText(text.left(i)); return; } } } else { count = rightStr.toLocal8Bit().length(); for ( ; i < leftStr.length(); ++i) { count += leftStr.mid(i,1).toLocal8Bit().length(); if (count > AP_NAME_MAX_LENGTH) { m_apNameLine->setText(leftStr.left(i) + rightStr); m_apNameLine->setCursorPosition(i); return; } } } } void MobileHotspotWidget::onPwdTextChanged() { if (m_pwdNameLine->text().length() < 8) { m_passwordFrame->setFixedHeight(PASSWORD_FRAME_FIX_HIGHT); m_pwdHintLabel->show(); } else { m_passwordFrame->setFixedHeight(PASSWORD_FRAME_MIN_HIGHT); m_pwdHintLabel->hide(); } resetFrameSize(); this->update(); } void MobileHotspotWidget::onInterfaceChanged() { m_interfaceName = m_interfaceComboBox->currentText(); if(m_interface->isValid()) { QDBusReply reply = m_interface->call(QStringLiteral("getWirelessList"), m_interfaceName); if(!reply.isValid()) { qWarning() << "getWirelessList error:" << reply.error().message(); return; } bool flag = false; QList variantList; for (int j = 0; j < reply.value().size(); ++j) { variantList << reply.value().at(j).toStringList(); } if (!variantList.isEmpty() && variantList.at(0).size() > 1) { flag = true; } if (flag) { m_interfaceWarnLabel->setText(tr("use ") + m_interfaceName + tr(" share network, will interrupt local wireless connection")); m_interfaceFrame->setFixedHeight(PASSWORD_FRAME_FIX_HIGHT); m_warnWidget->show(); } else { m_interfaceFrame->setFixedHeight(PASSWORD_FRAME_MIN_HIGHT); m_warnWidget->hide(); } resetFrameSize(); } updateBandCombox(); } void MobileHotspotWidget::onActiveConnectionChanged(QString deviceName, QString ssid, QString uuid, int status) { if(m_uuid == uuid && status == 4) { if(m_switchBtn->isChecked()) showDesktopNotify(tr("hotspot already close")); m_switchBtn->setChecked(false); setUiEnabled(false); m_uuid.clear(); } if (deviceName != m_interfaceName) { return; } if (m_interfaceComboBox && status == 2) { onInterfaceChanged(); } } void MobileHotspotWidget::onWirelessBtnChanged(bool state) { stopLoading(); if (!state) { if(m_switchBtn->isChecked()) showDesktopNotify(tr("hotspot already close")); m_switchBtn->setChecked(state); m_uuid.clear(); m_switchBtn->setCheckable(false); } else { m_switchBtn->setCheckable(true); } } void MobileHotspotWidget::initInterfaceInfo() { if(!m_interface->isValid()) { return; } if (m_interfaceComboBox->isVisible()) { m_interfaceComboBox->hidePopup(); } m_interfaceComboBox->clear(); QDBusReply reply = m_interface->call(QStringLiteral("getDeviceListAndEnabled"),WIRELESS); if(!reply.isValid()) { qWarning() << "[WlanConnect]getWirelessDeviceList error:" << reply.error().message(); return; } QMap devMap; QVariantMap::const_iterator item = reply.value().cbegin(); while (item != reply.value().cend()) { devMap.insert(item.key(), item.value().toBool()); item ++; } QDBusReply capReply = m_interface->call("getWirelessDeviceCap"); if (!capReply.isValid()) { qDebug() << LOG_HEAD <<"execute dbus method 'getWirelessDeviceCap' is invalid in func initInterfaceInfo()" < devCapMap; QVariantMap::const_iterator itemIter = capReply.value().cbegin(); while (itemIter != capReply.value().cend()) { devCapMap.insert(itemIter.key(), itemIter.value().toInt()); itemIter ++; } if (devMap.isEmpty()) { qDebug() << LOG_HEAD << "no wireless device"; setWidgetHidden(true); m_switchBtn->setCheckable(false); } else { QMap::Iterator iter = devMap.begin(); while (iter != devMap.end()) { if (!iter.value()) { iter++; continue; } QString interfaceName = iter.key(); if (!(devCapMap[interfaceName] & 0x01)) { m_interfaceComboBox->addItem(interfaceName); } iter++; } if (m_interfaceComboBox->count() > 0) { setWidgetHidden(false); m_interfaceName = m_interfaceComboBox->currentText(); if (m_interfaceComboBox->count() == 1) { updateBandCombox(); } } else { qDebug() << LOG_HEAD << "no useable wireless device"; setWidgetHidden(true); } } } void MobileHotspotWidget::getApInfo() { if (!m_interface->isValid()) { return; } if (m_interfaceComboBox->count() <= 0) { if(m_switchBtn->isChecked()) showDesktopNotify(tr("hotspot already close")); m_switchBtn->setChecked(false); setWidgetHidden(true); qWarning() << LOG_HEAD << "getApInfo but interface is empty"; return; } QDBusReply reply = m_interface->call("getStoredApInfo"); if (!reply.isValid()) { qDebug() << LOG_HEAD <<"execute dbus method 'getStoredApInfo' is invalid in func getObjectPath()"; } QStringList apInfo = reply.value(); if (apInfo.isEmpty()) { qDebug() << LOG_HEAD << "no stored hotspot info"; m_apNameLine->setText(m_hostName); m_pwdNameLine->setText("12345678"); return; } else { m_apNameLine->setText(apInfo.at(0)); m_pwdNameLine->setText(apInfo.at(1)); int index = m_interfaceComboBox->findText(apInfo.at(2)); if (index >= 0) { m_interfaceComboBox->setCurrentIndex(index); m_interfaceName = apInfo.at(2); } else { qDebug() << LOG_HEAD << "no such interface " << apInfo.at(2); } if (apInfo.at(3) == "true") { /* //fix306895 【移动热点】控制面板开启热点后,右上角弹窗通知,此时关闭控制面板,重新进入移动热点界面,会再弹一次弹窗 if(!m_switchBtn->isChecked()) showDesktopNotify(tr("hotspot already open")); */ m_switchBtn->setChecked(true); setUiEnabled(true); m_uuid = apInfo.at(4); } else { if(m_switchBtn->isChecked()) showDesktopNotify(tr("hotspot already close")); m_switchBtn->setChecked(false); setUiEnabled(false); m_uuid = apInfo.at(4); } int i = m_freqBandComboBox->findText(apInfo.at(5)); if (i >= 0) { m_isUserSelect = false; m_freqBandComboBox->setCurrentIndex(i); m_isUserSelect = true; } } } void MobileHotspotWidget::setSwitchFrame() { /* Open */ m_switchFrame = new QFrame(this); m_switchFrame->setFrameShape(QFrame::Shape::NoFrame); m_switchFrame->setMinimumSize(FRAME_MIN_SIZE); m_switchFrame->setMaximumSize(CONTECT_FRAME_MAX_SIZE); QHBoxLayout *switchLayout = new QHBoxLayout(m_switchFrame); m_switchLabel = new QLabel(tr("Open mobile hotspot"), this); m_switchLabel->setMinimumWidth(LABLE_MIN_WIDTH); m_switchBtn = new KSwitchButton(this); m_statusLabel= new QLabel(this); m_statusLabel->hide(); switchLayout->setContentsMargins(ITEM_MARGINS); switchLayout->addWidget(m_switchLabel); switchLayout->addStretch(); switchLayout->addWidget(m_statusLabel); switchLayout->addSpacing(4); switchLayout->addWidget(m_switchBtn); m_switchFrame->setLayout(switchLayout); m_loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); m_loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); m_waitTimer = new QTimer(this); connect(m_waitTimer, &QTimer::timeout, this, &MobileHotspotWidget::updateLoadingIcon); } void MobileHotspotWidget::updateLoadingIcon() { if (m_currentIconIndex > 6) { m_currentIconIndex = 0; } m_statusLabel->setPixmap(m_loadIcons.at(m_currentIconIndex).pixmap(16,16)); m_statusLabel->setProperty("useIconHighlightEffect", 0x2); m_currentIconIndex ++; } void MobileHotspotWidget::startLoading() { m_waitTimer->start(FRAME_SPEED); m_switchBtn->hide(); m_statusLabel->setFocus(); m_statusLabel->show(); } void MobileHotspotWidget::stopLoading() { m_waitTimer->stop(); m_statusLabel->clearFocus(); m_statusLabel->hide(); m_switchBtn->show(); } void MobileHotspotWidget::setApNameFrame() { /* ApName */ m_ApNameFrame = new QFrame(this); m_ApNameFrame->setFrameShape(QFrame::Shape::NoFrame); m_ApNameFrame->setMinimumSize(FRAME_MIN_SIZE); m_ApNameFrame->setMaximumSize(CONTECT_FRAME_MAX_SIZE); QHBoxLayout *apNameHLayout = new QHBoxLayout(m_ApNameFrame); m_apNameLabel = new QLabel(tr("Wi-Fi Name"), this); m_apNameLabel->setMinimumWidth(LABLE_MIN_WIDTH); m_apNameLine = new QLineEdit(this); m_apNameLine->setMinimumWidth(COMBOBOX_MIN_WIDTH); m_apNameLine->setMaxLength(AP_NAME_MAX_LENGTH); apNameHLayout->setContentsMargins(ITEM_MARGINS); apNameHLayout->setSpacing(0); apNameHLayout->addWidget(m_apNameLabel); apNameHLayout->addWidget(m_apNameLine); m_ApNameFrame->setLayout(apNameHLayout); } void MobileHotspotWidget::setPasswordFrame() { /* Password */ m_passwordFrame = new QFrame(this); m_passwordFrame->setFrameShape(QFrame::Shape::NoFrame); m_passwordFrame->setMinimumSize(PASSWORD_FRAME_MIN_SIZE); m_passwordFrame->setMaximumSize(PASSWORD_FRAME_MAX_SIZE); m_pwdLabel = new KLabel(this); m_pwdLabel->setText(tr("Network Password")); m_pwdLabel->setFixedWidth(LABLE_MIN_WIDTH); m_pwdNameLine = new KPasswordEdit(this); m_pwdNameLine->setClearButtonEnabled(false);//禁用ClearBtn按钮X m_pwdNameLine->setMinimumWidth(COMBOBOX_MIN_WIDTH); m_pwdHintLabel= new QLabel(this); m_pwdHintLabel->setFixedHeight(20); m_pwdHintLabel->setContentsMargins(HINT_TEXT_MARGINS); QPalette hintTextColor; hintTextColor.setColor(QPalette::WindowText, Qt::red); m_pwdHintLabel->setPalette(hintTextColor); m_pwdHintLabel->setText(tr("Contains at least 8 characters")); //至少包含8个字符 QGridLayout *pwdLayout = new QGridLayout(m_passwordFrame); pwdLayout->setContentsMargins(PASSWORD_ITEM_MARGINS); pwdLayout->setSpacing(0); pwdLayout->addWidget(m_pwdLabel, 0, 0); pwdLayout->addWidget(m_pwdNameLine, 0, 1); pwdLayout->addWidget(m_pwdHintLabel, 1, 1); m_passwordFrame->setLayout(pwdLayout); //init m_passwordFrame->setFixedHeight(PASSWORD_FRAME_FIX_HIGHT); m_pwdHintLabel->show(); m_pwdNameLine->installEventFilter(this); } void MobileHotspotWidget::setFreqBandFrame() { /* frequency band */ m_freqBandFrame = new QFrame(this); m_freqBandFrame->setFrameShape(QFrame::Shape::NoFrame); m_freqBandFrame->setMinimumSize(FRAME_MIN_SIZE); m_freqBandFrame->setMaximumSize(CONTECT_FRAME_MAX_SIZE); QHBoxLayout *freqBandHLayout = new QHBoxLayout(m_freqBandFrame); m_freqBandLabel = new KLabel(this); m_freqBandLabel->setText(tr("Network Frequency band")); m_freqBandLabel->setFixedWidth(LABLE_MIN_WIDTH - 8); m_freqBandComboBox = new QComboBox(this); m_freqBandComboBox->setInsertPolicy(QComboBox::NoInsert); m_freqBandComboBox->setMinimumWidth(COMBOBOX_MIN_WIDTH); m_freqBandComboBox->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); m_freqBandComboBox->addItem("2.4GHz"); m_freqBandComboBox->addItem("5GHz"); freqBandHLayout->setContentsMargins(ITEM_MARGINS); freqBandHLayout->setSpacing(8); freqBandHLayout->addWidget(m_freqBandLabel); freqBandHLayout->addWidget(m_freqBandComboBox); m_freqBandFrame->setLayout(freqBandHLayout); } void MobileHotspotWidget::setInterFaceFrame() { /* key tips */ m_interfaceFrame = new QFrame(this); m_interfaceFrame->setFrameShape(QFrame::Shape::NoFrame); m_interfaceFrame->setMinimumSize(PASSWORD_FRAME_MIN_SIZE); m_interfaceFrame->setMaximumSize(PASSWORD_FRAME_MAX_SIZE); m_interfaceLabel = new KLabel( this); m_interfaceLabel->setText(tr("Shared NIC port")); m_interfaceLabel->setFixedWidth(LABLE_MIN_WIDTH); m_interfaceComboBox = new QComboBox(this); m_interfaceComboBox->setInsertPolicy(QComboBox::NoInsert); m_interfaceComboBox->setMinimumWidth(COMBOBOX_MIN_WIDTH); m_warnWidget = new QWidget(this); m_warnWidget->setContentsMargins(8,0,0,0); QHBoxLayout *warnTextHLayout = new QHBoxLayout(m_warnWidget); QLabel* warnIcon = new QLabel(this); warnIcon->setContentsMargins(0,0,0,0); warnIcon->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(16,16)); m_interfaceWarnLabel= new KLabel(this); // m_interfaceWarnLabel->setFixedHeight(20); QPalette hintTextColor; //hintTextColor.setColor(QPalette::WindowText, Qt::red); //m_interfaceWarnLabel->setPalette(hintTextColor); m_interfaceWarnLabel->setFontColorRole(QPalette::WindowText); m_interfaceWarnLabel->setFontColor(Qt::red); warnTextHLayout->setSpacing(8); warnTextHLayout->setContentsMargins(0,0,0,0); warnTextHLayout->addWidget(warnIcon); warnTextHLayout->addWidget(m_interfaceWarnLabel); warnIcon->setFixedWidth(16); m_warnWidget->setLayout(warnTextHLayout); QGridLayout *interfaceFLayout = new QGridLayout(m_interfaceFrame); interfaceFLayout->setContentsMargins(PASSWORD_ITEM_MARGINS); interfaceFLayout->setSpacing(0); interfaceFLayout->addWidget(m_interfaceLabel, 0, 0); interfaceFLayout->addWidget(m_interfaceComboBox, 0, 1); interfaceFLayout->addWidget(m_warnWidget, 1, 1); m_interfaceFrame->setLayout(interfaceFLayout); m_warnWidget->hide(); } void MobileHotspotWidget::onActivateFailed(QString errorMessage) { if (errorMessage.indexOf("hotspot")) { //todo // showDesktopNotify(errorMessage); } } void MobileHotspotWidget::onDeactivateFailed(QString errorMessage) { if (errorMessage.indexOf("hotspot")) { // showDesktopNotify(errorMessage); } } //设备插拔 void MobileHotspotWidget::onDeviceStatusChanged() { initInterfaceInfo(); getApInfo(); } void MobileHotspotWidget::onDeviceNameChanged(QString oldName, QString newName, int type) { if (WIRELESS != type) { return; } int index = m_interfaceComboBox->findText(oldName); if (index >= 0) { m_interfaceComboBox->setItemText(index, newName); if (m_interfaceName == oldName) { m_interfaceName = newName; } } QTimer::singleShot(100, this, [=]() { if (m_interfaceComboBox->currentText() == newName) { updateBandCombox(); } }); } //热点断开 void MobileHotspotWidget::onHotspotDeactivated(QString devName, QString ssid) { QTimer::singleShot(7000,this,[=](){ stopLoading(); }); if (!m_switchBtn->isChecked()) { return; } if (devName == m_interfaceComboBox->currentText() && ssid == m_apNameLine->text()) { if(m_switchBtn->isChecked()) showDesktopNotify(tr("hotspot already close")); m_switchBtn->setChecked(false); m_uuid.clear(); // setUiEnabled(true); } } //热点连接 void MobileHotspotWidget::onHotspotActivated(QString devName, QString ssid, QString uuid, QString activePath, QString settingPath) { qDebug() << LOG_HEAD << "onHotspotActivated" <isChecked()) { return; } #ifdef HOTSPOT_CONTROL if (activePath != nullptr) { deleteActivePathInterface(); initActivePathInterface(activePath); } if (settingPath != nullptr) { deleteSettingPathInterface(); initSettingPathInterface(settingPath); } m_connectDevPage->refreshStalist(); m_blacklistPage->refreshBlacklist(); #endif this->update(); if (devName == m_interfaceComboBox->currentText() && ssid == m_apNameLine->text()) { if(!m_switchBtn->isChecked()) showDesktopNotify(tr("hotspot already open")); m_switchBtn->setChecked(true); m_uuid = uuid; // setUiEnabled(false); } else { QStringList info; if (!getApInfoBySsid(devName, ssid, info)) { return; } int index = m_interfaceComboBox->findText(devName); if (index >= 0) { if(!m_switchBtn->isChecked()) showDesktopNotify(tr("hotspot already open")); m_apNameLine->setText(ssid); m_interfaceComboBox->setCurrentIndex(index); m_switchBtn->setChecked(true); m_switchBtn->setCheckable(true); m_pwdNameLine->setText(info.at(0)); m_interfaceName = devName; updateBandCombox(); index = m_freqBandComboBox->findText(info.at(1)); if (index >= 0) { m_isUserSelect = false; m_freqBandComboBox->setCurrentIndex(index); m_isUserSelect = true; } m_uuid = uuid; } else { qDebug() << "no such device in combo box"; } } } bool MobileHotspotWidget::getApInfoBySsid(QString devName, QString ssid, QStringList &info) { info.clear(); if(!m_interface->isValid()) { return false; } QDBusReply reply = m_interface->call("getApInfoBySsid", devName, ssid); if (!reply.isValid()) { qDebug()<<"execute dbus method 'getApInfoBySsid' is invalid in func getApInfoBySsid()"; } info = reply.value(); if (info.size() != 2) { return false; } else { return true; } } void MobileHotspotWidget::setUiEnabled(bool enable) { qDebug() << "switch mode change to " << enable; if (enable) { m_pwdNameLine->setEnabled(false); m_freqBandComboBox->setEnabled(false); m_interfaceComboBox->setEnabled(false); m_apNameLine->setEnabled(false); } else { m_pwdNameLine->setEnabled(true); m_freqBandComboBox->setEnabled(true); m_interfaceComboBox->setEnabled(true); m_apNameLine->setEnabled(true); } } void MobileHotspotWidget::setWidgetHidden(bool isHidden) { m_ApNameFrame->setHidden(isHidden); m_passwordFrame->setHidden(isHidden); m_freqBandFrame->setHidden(isHidden); m_interfaceFrame->setHidden(isHidden); switchAndApNameLine->setHidden(isHidden); apNameAndPwdLine->setHidden(isHidden); pwdAndfreqBandLine->setHidden(isHidden); freqBandAndInterfaceLine->setHidden(isHidden); if (isHidden) { m_switchBtn->setChecked(false); m_switchBtn->setCheckable(false); m_interfaceName = ""; m_uuid = ""; } else { m_switchBtn->setCheckable(true); QDBusReply reply = m_interface->call("getWirelessSwitchBtnState"); bool state = reply.value(); onWirelessBtnChanged(state); } resetFrameSize(); } void MobileHotspotWidget::updateBandCombox() { QString tmp = m_freqBandComboBox->currentText(); m_freqBandComboBox->clear(); QDBusReply capReply = m_interface->call("getWirelessDeviceCap"); if (!capReply.isValid()) { qDebug()<<"execute dbus method 'getWirelessDeviceCap' is invalid in func initInterfaceInfo()" << capReply.error().message(); setWidgetHidden(true); return; } m_isUserSelect = false; QMap devCapMap; QVariantMap::const_iterator itemIter = capReply.value().cbegin(); while (itemIter != capReply.value().cend()) { devCapMap.insert(itemIter.key(), itemIter.value().toInt()); itemIter ++; } if (devCapMap[m_interfaceName] & 0x02) { m_freqBandComboBox->addItem("2.4GHz"); } if (devCapMap[m_interfaceName] & 0x04) { m_freqBandComboBox->addItem("5GHz"); } int index = m_freqBandComboBox->findText(tmp); if (index >= 0) { m_freqBandComboBox->setCurrentIndex(index); } m_isUserSelect = true; } QFrame* MobileHotspotWidget::myLine() { QFrame *line = new QFrame(this); line->setMinimumSize(QSize(LINE_MIN_SIZE)); line->setMaximumSize(QSize(LINE_MAX_SIZE)); line->setLineWidth(0); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); return line; } QString MobileHotspotWidget::getHostName() { int count = 0; while (count < 3) { QDBusInterface hostInterface("org.freedesktop.hostname1", "/org/freedesktop/hostname1", "org.freedesktop.hostname1", QDBusConnection::systemBus()); if (hostInterface.isValid()) { return hostInterface.property("Hostname").value(); } else { count++; } } return "default"; } QString MobileHotspotWidget::getSettingPathByUuid() { if (!m_interface->isValid()) { return nullptr; } QDBusReply reply = m_interface->call("getApConnectionPath", m_uuid); if (!reply.isValid()) { return nullptr; } return reply.value(); } QString MobileHotspotWidget::getActivePathByUuid() { if (!m_interface->isValid()) { return nullptr; } QDBusReply reply = m_interface->call("getActiveConnectionPath", m_uuid); if (!reply.isValid()) { return nullptr; } return reply.value(); } void MobileHotspotWidget::initNmDbus() { QString activePath = getActivePathByUuid(); QString settingPath = getSettingPathByUuid(); if (activePath != nullptr) { m_activePathInterface = new QDBusInterface("org.freedesktop.NetworkManager", activePath, "org.freedesktop.NetworkManager.Connection.Active", QDBusConnection::systemBus()); if (m_activePathInterface->isValid()) { m_connectDevPage->setInterface(m_activePathInterface); connect(m_activePathInterface, SIGNAL(NewStaConnected(bool, QString, QString)), m_connectDevPage, SLOT(onStaDevAdded(bool, QString, QString)), Qt::QueuedConnection); connect(m_activePathInterface, SIGNAL(StaRemoved(bool, QString, QString)), m_connectDevPage, SLOT(onStaDevRemoved(bool, QString, QString)), Qt::QueuedConnection); } } if (settingPath != nullptr) { m_settingPathInterface = new QDBusInterface("org.freedesktop.NetworkManager", settingPath, "org.freedesktop.NetworkManager.Settings.Connection", QDBusConnection::systemBus()); if (m_settingPathInterface->isValid()) { m_blacklistPage->setInterface(m_settingPathInterface); } } } void MobileHotspotWidget::initActivePathInterface(QString path) { if (path != nullptr){ m_activePathInterface = new QDBusInterface("org.freedesktop.NetworkManager", path, "org.freedesktop.NetworkManager.Connection.Active", QDBusConnection::systemBus()); if (m_activePathInterface->isValid()) { m_connectDevPage->setInterface(m_activePathInterface); connect(m_activePathInterface, SIGNAL(NewStaConnected(bool, QString, QString)), m_connectDevPage, SLOT(onStaDevAdded(bool, QString, QString)), Qt::QueuedConnection); connect(m_activePathInterface, SIGNAL(StaRemoved(bool, QString, QString)), m_connectDevPage, SLOT(onStaDevRemoved(bool, QString, QString)), Qt::QueuedConnection); } } } void MobileHotspotWidget::deleteActivePathInterface() { if (m_activePathInterface != nullptr){ disconnect(m_activePathInterface); delete m_activePathInterface; m_activePathInterface = nullptr; } } void MobileHotspotWidget::initSettingPathInterface(QString path) { if (path != nullptr){ m_settingPathInterface = new QDBusInterface("org.freedesktop.NetworkManager", path, "org.freedesktop.NetworkManager.Settings.Connection", QDBusConnection::systemBus()); if (m_settingPathInterface->isValid()) { m_blacklistPage->setInterface(m_settingPathInterface); } } } void MobileHotspotWidget::deleteSettingPathInterface() { if (m_settingPathInterface != nullptr){ disconnect(m_settingPathInterface); delete m_settingPathInterface; m_settingPathInterface = nullptr; } } void MobileHotspotWidget::initConnectDevPage() { m_connectDevPage = new ConnectdevPage(this); m_Vlayout->addSpacing(32); m_Vlayout->addWidget(m_connectDevPage); connect(m_switchBtn, &KSwitchButton::stateChanged, m_connectDevPage, &ConnectdevPage::refreshStalist); } void MobileHotspotWidget::initBlackListPage() { m_blacklistPage = new BlacklistPage(this); m_Vlayout->addSpacing(32); m_Vlayout->addWidget(m_blacklistPage); } kylin-nm/plugins/component/0000775000175000017500000000000015167646234014737 5ustar fengfengkylin-nm/plugins/component/SwitchButton/0000775000175000017500000000000015167646234017374 5ustar fengfengkylin-nm/plugins/component/SwitchButton/switchbutton.h0000664000175000017500000000615015167646234022304 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef SWITCHBUTTON_H #define SWITCHBUTTON_H #include #include #include #include #include #include #define OFF_BG_DARK_COLOR "#404040" #define OFF_HOVER_BG_DARK_COLOR "#666666" #define ON_BG_DARK_COLOR "#3790FA" #define ON_HOVER_BG_DARK_COLOR "#40A9FB" #define DISABLE_DARK_COLOR "#474747" #define DISABLE_RECT_DARK_COLOR "#6E6E6E" #define ENABLE_RECT_DARK_COLOR "#FFFFFF" #define OFF_BG_LIGHT_COLOR "#E0E0E0" #define OFF_HOVER_BG_LIGHT_COLOR "#B3B3B3" #define ON_BG_LIGHT_COLOR "#3790FA" #define ON_HOVER_BG_LIGHT_COLOR "#40A9FB" #define DISABLE_LIGHT_COLOR "#E9E9E9" #define DISABLE_RECT_LIGHT_COLOR "#B3B3B3" #define ENABLE_RECT_LIGHT_COLOR "#FFFFFF" class SwitchButton : public QWidget { Q_OBJECT public: SwitchButton(QWidget *parent = 0, bool useDisableStyle = true); ~SwitchButton(); void setChecked(bool checked); void setAnimation(bool on); bool isChecked(); void setDisabledFlag(bool); bool getDisabledFlag(); protected: void mousePressEvent(QMouseEvent *); void resizeEvent(QResizeEvent *); void paintEvent(QPaintEvent *); void enterEvent(QEvent *event); void leaveEvent(QEvent *event); void drawBg(QPainter * painter); void drawSlider(QPainter * painter); void changeColor(const QString &themes); private: bool checked; //切换的判断 bool disabled; void animation(QPainter *painter); QRect rect; bool isMoving; //滑块动作判断 bool isAnimation; // 是否允许动画执行 QColor bgColorOff; QColor bgColorOn; QColor bgHoverOnColor; QColor bgHoverOffColor; QColor bgColorDisabled; QColor sliderColorEnabled; QColor sliderColorDisabled; QColor rectColorEnabled; QColor rectColorDisabled; QColor sliderColorOff; QColor sliderColorOn; QGSettings *m_qtThemeSetting; QGSettings *m_gtkThemeSetting; int space; //滑块离背景间隔 int rectRadius; //圆角角度 int mStep; //移动步长 int mStartX; int mEndX; bool hover; QTimer * mTimer; bool m_useDisableStyle; private Q_SLOTS: void updatevalue(); Q_SIGNALS: void checkedChanged(bool checked); void disabledClick(); }; #endif // SWITCHBUTTON_H kylin-nm/plugins/component/SwitchButton/switchbutton.cpp0000664000175000017500000002173115167646234022641 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "switchbutton.h" #include #define THEME_QT_SCHEMA "org.ukui.style" #define THEME_GTK_SCHEMA "org.mate.interface" #define TIMER_INTERVAL 5 //每隔5ms动画移动一次 #define MOVING_STEPS 40 //动画总共移动40次 SwitchButton::SwitchButton(QWidget *parent, bool useDisableStyle) : QWidget(parent) { // this->resize(QSize(52, 24)); this->setFixedSize(QSize(50, 24)); checked = false; hover = false; disabled = false; isMoving = false; isAnimation = true; m_useDisableStyle = useDisableStyle; space = 4; rectRadius = height()/2; mStep = width()/MOVING_STEPS;//也就是40次动画就可以走完,每次时间间隔是固定的5ms mStartX = 0; mEndX= 0; mTimer = new QTimer(this); mTimer->setInterval(TIMER_INTERVAL);//动画更新时间 connect(mTimer, SIGNAL(timeout()), this, SLOT(updatevalue())); if(QGSettings::isSchemaInstalled(THEME_GTK_SCHEMA) && QGSettings::isSchemaInstalled(THEME_QT_SCHEMA)) { QByteArray qtThemeID(THEME_QT_SCHEMA); QByteArray gtkThemeID(THEME_GTK_SCHEMA); m_gtkThemeSetting = new QGSettings(gtkThemeID,QByteArray(),this); m_qtThemeSetting = new QGSettings(qtThemeID,QByteArray(),this); QString style = m_qtThemeSetting->get("styleName").toString(); changeColor(style); connect(m_qtThemeSetting,&QGSettings::changed, [this] (const QString &key) { QString style = m_qtThemeSetting->get("styleName").toString(); if (key == "styleName") { changeColor(style); } }); } } SwitchButton::~SwitchButton() { } void SwitchButton::paintEvent(QPaintEvent *){ QPainter painter(this); //启用反锯齿 painter.setRenderHint(QPainter::Antialiasing, true); painter.setCompositionMode(QPainter::CompositionMode_Source); drawBg(&painter); if(!isAnimation)//动画如果禁用,则圆形滑块isMoving始终为false isMoving =false; if(isMoving) animation(&painter); drawSlider(&painter); painter.end(); } void SwitchButton::changeColor(const QString &themes) { if (hover) { return ;//在鼠标下,禁止切换颜色鼠标离开时切换颜色 } if (themes == "ukui-dark" || themes == "ukui-black") { bgColorOff = QColor(OFF_BG_DARK_COLOR); bgColorOn = QColor(ON_BG_DARK_COLOR); rectColorEnabled = QColor(ENABLE_RECT_DARK_COLOR); rectColorDisabled = QColor(DISABLE_RECT_DARK_COLOR); sliderColorDisabled = QColor(DISABLE_RECT_DARK_COLOR); sliderColorEnabled = QColor(ENABLE_RECT_DARK_COLOR); bgHoverOnColor = QColor(ON_HOVER_BG_DARK_COLOR); bgHoverOffColor = QColor(OFF_HOVER_BG_DARK_COLOR); bgColorDisabled = QColor(DISABLE_DARK_COLOR); } else { bgColorOff = QColor(OFF_BG_LIGHT_COLOR); bgColorOn = QColor(ON_BG_LIGHT_COLOR); rectColorEnabled = QColor(ENABLE_RECT_LIGHT_COLOR); rectColorDisabled = QColor(DISABLE_RECT_LIGHT_COLOR); sliderColorDisabled = QColor(DISABLE_RECT_LIGHT_COLOR); sliderColorEnabled = QColor(ENABLE_RECT_LIGHT_COLOR); bgHoverOnColor = QColor(ON_HOVER_BG_LIGHT_COLOR); bgHoverOffColor = QColor(OFF_HOVER_BG_LIGHT_COLOR); bgColorDisabled = QColor(DISABLE_LIGHT_COLOR); } } //动画绘制 void SwitchButton::animation(QPainter *painter){ painter->save(); int h = height(); int w = width(); painter->setPen(Qt::NoPen); //颜色设置 if(checked){ //开关在左侧时 painter->setBrush(bgColorOn); rect.setRect(0,0,h+mStartX,h); }else{ painter->setBrush(bgColorOff); rect.setRect(mStartX,0,w-mStartX,h); } painter->drawRoundedRect(rect,rectRadius,rectRadius); painter->restore(); } //绘制背景 void SwitchButton::drawBg(QPainter *painter){ int w = width(); int h = height(); painter->save(); painter->setPen(Qt::NoPen); if (disabled && m_useDisableStyle) { painter->setPen(Qt::NoPen); painter->setBrush(bgColorDisabled); } else { if(checked){ if(isMoving){ painter->setBrush(bgColorOff); rect.setRect(mStartX,0,w-mStartX,h); }else { painter->setBrush(bgColorOn); rect.setRect(0, 0, w, h); } }else{ if(isMoving){ painter->setBrush(bgColorOn); rect.setRect(0,0,mStartX+h,h); } else { painter->setBrush(bgColorOff); rect.setRect(0, 0, w, h); } } } //半径为高度的一半 painter->drawRoundedRect(rect,rectRadius,rectRadius); painter->restore(); } //绘制滑块,也就是圆形按钮 void SwitchButton::drawSlider(QPainter *painter){ painter->save(); painter->setPen(Qt::NoPen); if (!disabled || !m_useDisableStyle){ painter->setBrush(sliderColorEnabled); } else painter->setBrush(sliderColorDisabled); if (disabled) { if (!checked){ QRect smallRect(8, height() / 2 - 2, 10 , 4); painter->drawRoundedRect(smallRect,3,3); }else{ QRect smallRect(width() - 8 * 2, height() / 2 - 2, 10 , 4); painter->drawRoundedRect(smallRect,3,3); } } QRect rect(0, 0, width(), height()); int sliderWidth = rect.height() - space * 2; QRect sliderRect(mStartX + space, space, sliderWidth, sliderWidth); painter->drawEllipse(sliderRect); painter->restore(); } void SwitchButton::mousePressEvent(QMouseEvent *){ qDebug()<start(); isMoving = true; } } void SwitchButton::resizeEvent(QResizeEvent *){ //每次开始的x坐标都是跳过圆角,从直线的地方开始计算 mStep = width() / MOVING_STEPS; if (checked){ //circle out // startX = width() - height() + space; //circle in mStartX = width() - height(); } else mStartX = 0; rectRadius = height()/2; update(); } void SwitchButton::enterEvent(QEvent *event) { bgColorOn = bgHoverOnColor; bgColorOff = bgHoverOffColor; hover = true; update(); return QWidget::enterEvent(event); } void SwitchButton::leaveEvent(QEvent *event) { hover = false; QString style = m_qtThemeSetting->get("styleName").toString(); changeColor(style); update(); return QWidget::leaveEvent(event); } //根据事件向左还是向右移动 void SwitchButton::updatevalue(){ if (checked) if (mStartX < mEndX-mStep){ mStartX = mStartX + mStep; } else{ mStartX = mEndX; mTimer->stop(); isMoving = false; } else{ if (mStartX > mEndX+mStep){ mStartX = mStartX - mStep; } else{ mStartX = mEndX; mTimer->stop(); isMoving = false; } } update(); } void SwitchButton::setChecked(bool checked){ if (this->checked != checked){ this->checked = checked; Q_EMIT checkedChanged(checked); update(); } mStep = width() / MOVING_STEPS; if (checked){ //circle out // endX = width() - height() + space; //circle in mEndX = width() - height(); } else{ mEndX = 0; } mTimer->start(); isMoving = true; } bool SwitchButton::isChecked(){ return this->checked; } void SwitchButton::setDisabledFlag(bool value) { disabled = value; update(); } bool SwitchButton::getDisabledFlag() { return disabled; } void SwitchButton::setAnimation(bool on){ isAnimation = on; } kylin-nm/plugins/component/DrownLabel/0000775000175000017500000000000015167646234016770 5ustar fengfengkylin-nm/plugins/component/DrownLabel/drownlabel.h0000664000175000017500000000260215167646234021272 0ustar fengfeng /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef DROWNLABEL_H #define DROWNLABEL_H #include #include #include #include class DrownLabel : public QLabel { Q_OBJECT public: explicit DrownLabel(QString devName, QWidget * parent = nullptr); ~DrownLabel(); void setDropDownStatus(bool status); QString m_devName; bool isChecked = true; private: void loadPixmap(bool isChecked); protected: virtual void mouseReleaseEvent(QMouseEvent * event); Q_SIGNALS: void labelClicked(); }; #endif // DROWNLABEL_H kylin-nm/plugins/component/DrownLabel/drownlabel.cpp0000664000175000017500000000316415167646234021631 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "drownlabel.h" #include "deviceframe.h" #define ICONSIZE 16,16 DrownLabel::DrownLabel(QString devName, QWidget * parent) : QLabel(parent) { m_devName = devName; setFixedSize(36,36); loadPixmap(isChecked); this->setProperty("useIconHighlightEffect", 0x2); } DrownLabel::~DrownLabel() { } void DrownLabel::setDropDownStatus(bool status) { isChecked = status; loadPixmap(isChecked); } void DrownLabel::loadPixmap(bool isChecked) { if (isChecked) { setPixmap(QIcon::fromTheme("ukui-up-symbolic").pixmap(ICONSIZE)); } else { setPixmap(QIcon::fromTheme("ukui-down-symbolic").pixmap(ICONSIZE)); } } void DrownLabel::mouseReleaseEvent(QMouseEvent *event) { emit labelClicked(); QWidget::mouseReleaseEvent(event); } kylin-nm/plugins/component/InfoButton/0000775000175000017500000000000015167646234017026 5ustar fengfengkylin-nm/plugins/component/InfoButton/infobutton.h0000664000175000017500000000310415167646234021364 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef INFOBUTTON_H #define INFOBUTTON_H #include #include #include class InfoButton : public QPushButton { Q_OBJECT public: explicit InfoButton(QWidget * parent = nullptr); ~InfoButton() = default; protected: void paintEvent(QPaintEvent *event); void enterEvent(QEvent *event); void leaveEvent(QEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); private: void initUI(); private: QColor m_backgroundColor; QColor m_foregroundColor; //监听主题的Gsettings QGSettings * m_styleGsettings = nullptr; private slots: void onGSettingChaned(const QString &key); }; #endif // INFOBUTTON_H kylin-nm/plugins/component/InfoButton/infobutton.cpp0000664000175000017500000000720115167646234021721 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "infobutton.h" #include #include #include #include #define BUTTON_SIZE 36,36 #define ICON_SIZE 16,16 #define BACKGROUND_COLOR QColor(0,0,0,0) #define FOREGROUND_COLOR_NORMAL qApp->palette().text().color() #define FOREGROUND_COLOR_HOVER QColor(55,144,250,255) #define FOREGROUND_COLOR_PRESS QColor(36,109,212,255) #define OUTER_PATH 8,8,16,16 #define INNER_PATH 9,9,14,14 #define TEXT_POS 14,5,16,16,0 #define BUTTON_SIZE 36,36 #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" InfoButton::InfoButton(QWidget *parent) : QPushButton(parent) { this->setFixedSize(BUTTON_SIZE); initUI(); const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { m_styleGsettings = new QGSettings(style_id); connect(m_styleGsettings, &QGSettings::changed, this, &InfoButton::onGSettingChaned); } else { qDebug() << "Gsettings interface \"org.ukui.style\" is not exist!"; } } void InfoButton::initUI() { this->setFixedSize(BUTTON_SIZE); m_backgroundColor = BACKGROUND_COLOR; m_foregroundColor = FOREGROUND_COLOR_NORMAL; } void InfoButton::onGSettingChaned(const QString &key) { if (key == COLOR_THEME) { m_foregroundColor = FOREGROUND_COLOR_NORMAL; this->repaint(); } } void InfoButton::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); pal.setColor(QPalette::Base, m_backgroundColor); pal.setColor(QPalette::Text, m_foregroundColor); QPainterPath cPath; cPath.addRect(0, 0, ICON_SIZE); cPath.addEllipse(0, 0, ICON_SIZE); QPainterPath outerPath; outerPath.addEllipse(OUTER_PATH); QPainterPath innerPath; innerPath.addEllipse(INNER_PATH); outerPath -= innerPath; QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); painter.setBrush(pal.color(QPalette::Base)); painter.drawPath(cPath); painter.fillPath(outerPath, pal.color(QPalette::Text)); painter.setPen(m_foregroundColor); QFont font("Noto Sans CJK SC", 11, QFont::Normal, false); painter.setFont(font); painter.drawText(TEXT_POS, "i"); } void InfoButton::enterEvent(QEvent *event) { m_foregroundColor = FOREGROUND_COLOR_HOVER; this->repaint(); } void InfoButton::leaveEvent(QEvent *event) { m_foregroundColor = FOREGROUND_COLOR_NORMAL; this->repaint(); } void InfoButton::mousePressEvent(QMouseEvent *event) { m_foregroundColor = FOREGROUND_COLOR_PRESS; this->repaint(); return QPushButton::mousePressEvent(event); } void InfoButton::mouseReleaseEvent(QMouseEvent *event) { m_foregroundColor = FOREGROUND_COLOR_HOVER; this->repaint(); return QPushButton::mouseReleaseEvent(event); } kylin-nm/plugins/component/infobutton.pri0000664000175000017500000000024315167646234017641 0ustar fengfeng#LIBINTERFACE_NAME = $$qtLibraryTarget(infobutton) SOURCES += \ $$PWD/InfoButton/infobutton.cpp \ HEADERS += \ $$PWD/InfoButton/infobutton.h \ kylin-nm/plugins/component/addbtn.pri0000664000175000017500000000032615167646234016710 0ustar fengfeng#LIBINTERFACE_NAME = $$qtLibraryTarget(addnetbtn) SOURCES += \ $$PWD/AddBtn/addnetbtn.cpp \ $$PWD/AddBtn/grayinfobutton.cpp HEADERS += \ $$PWD/AddBtn/addnetbtn.h \ $$PWD/AddBtn/grayinfobutton.h kylin-nm/plugins/component/AddBtn/0000775000175000017500000000000015167651420016064 5ustar fengfengkylin-nm/plugins/component/AddBtn/addnetbtn.h0000664000175000017500000000334715167651420020207 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef ADDNETBTN_H #define ADDNETBTN_H #include #include #include #include #include #include class AddNetBtn : public QPushButton { Q_OBJECT public: AddNetBtn(bool isWlan, QWidget *parent = nullptr); ~AddNetBtn(); void setTextLabel(const QString str); enum CornerType { All, BottomRight }; // 设置是否使用圆角 void setUseRoundedCorners(bool useRounded); void setCornerType(CornerType type); protected: virtual void leaveEvent(QEvent * event); virtual void enterEvent(QEnterEvent * event); void paintEvent(QPaintEvent *event); private: QLabel *m_textLabel; bool m_useRoundedCorners = true; // 默认使用圆角 CornerType m_cornerType = All; Q_SIGNALS: void enterWidget(); void leaveWidget(); }; #endif // ADDNETBTN_H kylin-nm/plugins/component/AddBtn/grayinfobutton.h0000664000175000017500000000217515167646234021323 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef GRAYINFOBUTTON_H #define GRAYINFOBUTTON_H #include #include class GrayInfoButton : public QPushButton { Q_OBJECT public: explicit GrayInfoButton(QWidget * parent = nullptr); ~GrayInfoButton() = default; }; #endif // GRAYINFOBUTTON_H kylin-nm/plugins/component/AddBtn/grayinfobutton.cpp0000664000175000017500000000232315167646234021651 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "grayinfobutton.h" #include #define BUTTON_SIZE 36,36 #define ICON_SIZE 16,16 GrayInfoButton::GrayInfoButton(QWidget *parent): QPushButton(parent) { this->setFixedSize(BUTTON_SIZE); this->setIcon(QIcon::fromTheme("preferences-system-details-symbolic")); this->setProperty("useButtonPalette", true); this->setFlat(true); } kylin-nm/plugins/component/AddBtn/addnetbtn.cpp0000664000175000017500000000743015167651420020537 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "addnetbtn.h" #include #include #include #include #include #include #define RADIUS 6.0 AddNetBtn::AddNetBtn(bool isWlan, QWidget *parent) : QPushButton(parent) { this->setObjectName("this"); this->setMinimumSize(QSize(580, 60)); this->setMaximumSize(QSize(16777215, 60)); this->setProperty("useButtonPalette", true); this->setFlat(true); QHBoxLayout *addLyt = new QHBoxLayout; QLabel *iconLabel = new QLabel(this); m_textLabel = new QLabel(this); if (isWlan) { m_textLabel->setText(tr("Add Others")); addLyt->addSpacing(8); addLyt->addWidget(m_textLabel); } else { m_textLabel->setText(tr("Add WiredNetork")); QIcon mAddIcon = QIcon::fromTheme("list-add-symbolic"); iconLabel->setPixmap(mAddIcon.pixmap(mAddIcon.actualSize(QSize(16, 16)))); iconLabel->setProperty("useIconHighlightEffect", 0x2); // iconLabel->setProperty("iconHighlightEffectMode", 1); addLyt->addStretch(); addLyt->addWidget(iconLabel); addLyt->addWidget(m_textLabel); } addLyt->addStretch(); this->setLayout(addLyt); } AddNetBtn::~AddNetBtn() { } void AddNetBtn::enterEvent(QEnterEvent *event){ Q_EMIT enterWidget(); QPushButton::enterEvent(event); } void AddNetBtn::leaveEvent(QEvent *event){ Q_EMIT leaveWidget(); QPushButton::leaveEvent(event); } void AddNetBtn::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); painter.setBrush(this->palette().base().color()); QPalette pal = qApp->palette(); QColor color = pal.color(QPalette::Button); color.setAlphaF(0.5); pal.setColor(QPalette::Button, color); this->setPalette(pal); QRect rect = this->rect(); QPainterPath path; //设置起点 path.moveTo(rect.topLeft().x(), rect.topLeft().y()); path.lineTo(rect.bottomLeft().x(), rect.bottomLeft().y() - RADIUS); //绘制圆角 圆弧以外切圆的270度位置为起点,逆时针画圆弧运行90度结束 path.arcTo(QRect(QPoint(rect.bottomLeft().x(), rect.bottomLeft().y() - (RADIUS * 2)), QSize(RADIUS * 2, RADIUS * 2)), 180, 90); path.lineTo(rect.bottomRight().x() - RADIUS, rect.bottomRight().y()); //画圆弧 path.arcTo(QRect(QPoint(rect.bottomRight().x() - (RADIUS * 2), rect.bottomRight().y() - (RADIUS * 2)), QSize(RADIUS * 2, RADIUS * 2)), 270, 90); path.lineTo(rect.topRight()); path.lineTo(rect.topLeft()); painter.drawPath(path); QPushButton::paintEvent(event); } void AddNetBtn::setUseRoundedCorners(bool useRounded) { m_useRoundedCorners = useRounded; update(); } void AddNetBtn::setCornerType(CornerType type) { m_cornerType = type; update(); } void AddNetBtn::setTextLabel(const QString str) { m_textLabel->setText(str); } kylin-nm/plugins/component/switchbutton.pri0000664000175000017500000000025415167646234020211 0ustar fengfeng #LIBINTERFACE_NAME = $$qtLibraryTarget(switchbutton) SOURCES += \ $$PWD/SwitchButton/switchbutton.cpp \ HEADERS += \ $$PWD/SwitchButton/switchbutton.h \ kylin-nm/plugins/component/drownlabel.pri0000664000175000017500000000023315167646234017602 0ustar fengfeng#LIBINTERFACE_NAME = $$qtLibraryTarget(drownlabel) SOURCES += \ $$PWD/DrownLabel/drownlabel.cpp \ HEADERS += \ $$PWD/DrownLabel/drownlabel.h \ kylin-nm/src-vpn/0000775000175000017500000000000015167651420012635 5ustar fengfengkylin-nm/src-vpn/kylin-vpn.desktop0000664000175000017500000000103315167646234016163 0ustar fengfeng[Desktop Entry] Encoding=UTF-8 Name=Kylin VPN Name[zh_CN]=麒麟VPN设置工具 Name[zh_HK]=麒麟VPN設置工具 Name[zh_TW]=麒麟VPN設置工具 Icon=gnome-dev-ethernet Comment=Beautiful Network Config Applet Comment[zh_CN]=麒麟VPN设置工具,提供查看和简单设置功能,拥有美观的界面和舒适的操作. Keywords=applet;vpn;network;network-manager; Exec=/usr/bin/kylin-vpn StartupNotify=false Terminal=false Type=Application OnlyShowIn=UKUI X-UKUI-AutoRestart=true NoDisplay=true X-UKUI-Autostart-Phase=Application kylin-nm/src-vpn/src-vpn.pro0000664000175000017500000000543715167651420014760 0ustar fengfeng#------------------------------------------------- # # Project created by QtCreator 2018-10-19T15:29:47 # #------------------------------------------------- QT += core gui dbus concurrent network greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = kylin-vpn TEMPLATE = app CONFIG += c++14 qt warn_on link_pkgconfig no_keywords #CONFIG += release PKGCONFIG +=gio-2.0 glib-2.0 gio-unix-2.0 libnm libnma libsecret-1 gtk+-3.0 gsettings-qt6 libcap kysdk-applications PKGCONFIG +=kysdk-sysinfo KF6WindowSystem INCLUDEPATH += /usr/include/KF6/NetworkManagerQt \ LIBS += -L/usr/lib/ -lX11 -lKF6NetworkManagerQt -lukui-log4qt -lkysdk-ukuiwindowhelper #LIBS += -lkysec target.path = /usr/bin target.source += $$TARGET desktop.path = /etc/xdg/autostart/ desktop.files = kylin-vpn.desktop gschema.files = org.ukui.kylin-vpn.switch.gschema.xml gschema.path = /usr/share/glib-2.0/schemas/ qm_files.path = /usr/share/kylin-nm/kylin-vpn/ qm_files.files = translations/*.qm INSTALLS += target \ desktop \ gschema \ qm_files \ # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 # QMAKE_CXXFLAGS += -Wno-unused-parameter QMAKE_CPPFLAGS *= $(shell dpkg-buildflags --get CPPFLAGS) QMAKE_CFLAGS *= $(shell dpkg-buildflags --get CFLAGS) QMAKE_CXXFLAGS *= $(shell dpkg-buildflags --get CXXFLAGS) QMAKE_LFLAGS *= $(shell dpkg-buildflags --get LDFLAGS) include(singleapplication/qt-single-application.pri) include(backend/backend.pri) include(frontend/frontend.pri) SOURCES += \ main.cpp unix { UI_DIR = .ui MOC_DIR = .moc OBJECTS_DIR = .obj } DISTFILES += \ org.ukui.kylin-vpn.switch.gschema.xml TRANSLATIONS += \ translations/kylin-vpn_zh_Hant.ts \ translations/kylin-vpn_zh_CN.ts \ translations/kylin-vpn_ug.ts \ translations/kylin-vpn_tr.ts \ translations/kylin-vpn_mn.ts \ translations/kylin-vpn_ky.ts \ translations/kylin-vpn_kk.ts \ translations/kylin-vpn_fr.ts \ translations/kylin-vpn_es.ts \ translations/kylin-vpn_de.ts \ translations/kylin-vpn_bo.ts\ translations/kylin-vpn_bo_CN.ts CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } kylin-nm/src-vpn/translations/0000775000175000017500000000000015167651420015356 5ustar fengfengkylin-nm/src-vpn/translations/kylin-vpn_fr.ts0000664000175000017500000010642215167651420020351 0ustar fengfeng SinglePage Settings Paramètres Kylin VPN Kylin VPN kylin vpn applet desktop message Kylin VPN applet desktop message VpnAdvancedPage MPPE encryption algorithm: Algorithme de chiffrement MPPE : Use Stateful encryption Utiliser le chiffrement avec état Send PPP echo packets Envoyer des paquets d’écho PPP Authentication Mode: Mode d’authentification : PAP authentication Authentification PAP CHAP authentication Authentification CHAP MSCHAP authentication Authentification MSCHAP MSCHAP2 authentication MSCHAP2 authentification EAP authentication Authentification EAP Compression Mode: Mode de compression : Allow BSD data compression Autoriser la compression des données BSD Allow Default data compression Autoriser la compression des données par défaut Allow TCP header compression Autoriser la compression de l’en-tête TCP Use protocol field compression negotiation Utiliser la négociation de compression de champ de protocole Use Address/Control compression Utiliser la compression d’adresse/contrôle All Available Tous disponibles 128-bit 128 bits 40-bit 40 bits Use custom gateway port Utiliser un port de passerelle personnalisé Use compression Utiliser la compression Use a TCP connection Utiliser une connexion TCP Set virtual device type Définir le type d’appareil virtuel Set virtual device name Définir le nom de l’appareil virtuel Limit TCP Maximum Segment Size(MSS) Taille maximale du segment TCP limite (MSS) Randomize remote hosts Randomiser les hôtes distants IPv6 tun link Liaison tun IPv6 Specify ping interval Spécifier l’intervalle ping Specify exit or restart ping Spécifier la sortie ou le redémarrage ping Specify max routes Spécifier le nombre maximal d’itinéraires Infinite retry on error Nouvelle tentative infinie en cas d’erreur Use custom key size Utiliser une taille de clé personnalisée Choose Choisir Use custom renegotiation interval Utiliser un intervalle de renégociation personnalisé Use custom tunnel Maximum Transmission Umit(MTU) Utiliser un tunnel personnalisé Maximum Transmission Umit (MTU) Use custom UDP fragment size Utiliser une taille de fragment UDP personnalisée Accept authenticated packets from any address (Float) Accepter les paquets authentifiés à partir de n’importe quelle adresse (Float) Subject Match Correspondance du sujet Key File Fichier clé Key Direction Direction clé Server Address Adresse du serveur Port Port Proxy USername Proxy USername Proxy Password Mot de passe proxy General Généralités TLS settings Paramètres TLS Server Certificate Check Vérification du certificat du serveur Use the previous authentication end (server) certificate Utiliser le certificat d’extrémité (serveur) d’authentification précédent Verify peer (server) certificate nsCertType specification Vérifier la spécification nsCertType du certificat homologue (serveur) Mode Mode Proxies Procurations Proxy Type Proxy Type Security Sécurité HMAC Authentication Authentification HMAC Input content Contenu d’entrée No Non Self-adaption Auto-adaptation Automatic Automatique Exit Sortie Restart Redémarrer Don't verify certificate identification Ne pas vérifier l’identification du certificat Verify the entire subject exactly Vérifiez exactement l’ensemble du sujet Verify name exactly Vérifier le nom exactement Verify name by prefix Vérifier le nom par préfixe Server Serveur Client Client None Aucun TLS-Certification Certification TLS TLS-Encryption Cryptage TLS Not Required Non requis Default Faire défaut Options: Options: Request an inner IP address Demander une adresse IP interne Enforce UDP encapsulation Appliquer l’encapsulation UDP Use IP compression Utiliser la compression IP Enable custom password suggestions Activer les suggestions de mots de passe personnalisés Choose a private key Choisir une clé privée Key Files (*.key *.pem *.der *.p12 *.pfx) Fichiers clés (*.key, *.pem, *.der, *.p12, *.pfx) VpnConfigPage Type Type Name Nom Static Key Clé statique Local IP Adresse IP locale Remote IP IP distante PIN Code PIN Code Password Mot de passe NT Domain Domaine NT Server Address Adresse du serveur Authentication Mode Mode d’authentification CA Certificate Certificat d’autorité de certification User Certificate Certificat d’utilisateur Key Direction Direction clé Private Key Clé privée Private Key Password Mot de passe de clé privée Password Options Options de mot de passe Username Nom d’utilisateur Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. Remarquer: Si la direction de la clé est utilisée, elle doit être opposée au côté VPN utilisé. Si '1' est utilisé, la connexion doit utiliser '0'. Si vous n’êtes pas sûr de la valeur à utiliser, contactez votre administrateur système. Choose Choisir None Aucun Save password only for this user Enregistrer le mot de passe uniquement pour cet utilisateur Save password for all users Enregistrer le mot de passe pour tous les utilisateurs Ask password every time Demander le mot de passe à chaque fois Don't require a password Pas besoin de mot de passe Required Obligatoire Certificate(TLS) Certificat (TLS) Static key Clé statique Password and certificate(TLS) Mot de passe et certificat (TLS) Certificate/Private key Certificat/Clé privée Certificate/ssh-agent Certificat/agent ssh Smart card Carte à puce Choose a private key Choisir une clé privée Key Files (*.key *.pem *.der *.p12 *.pfx) Fichiers clés (*.key, *.pem, *.der, *.p12, *.pfx) Choose a CA certificate Choisir un certificat d’autorité de certification CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Fichiers CA (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate Choisir un certificat d’utilisateur Choose a Static key Choisir une clé statique VpnDetail VPN IPv4 IPv6 Advanced Avancé Auto Connection Connexion automatique Cancel Annuler Confirm Confirmer VpnIpv4Page IPv4 Config Configuration IPv4 Address Adresse Netmask Masque de réseau Default Gateway Passerelle par défaut DNS Server Serveur DNS Search Domain Domaine de recherche DHCP Client ID DHCP Client ID Auto(DHCP) Auto (DHCP) Manual Manuelle VpnIpv6Page IPv6 Config Configuration IPv6 Address Adresse Netmask Masque de réseau Default Gateway Passerelle par défaut DNS Server Serveur DNS Search Domain Domaine de recherche Auto(DHCP) Auto (DHCP) Manual Manuelle VpnListItem Not connected Non connecté Disconnect Déconnecter Connect Relier VpnPage VPN VPN Settings Paramètres VPN vpnAddPage create VPN créer un VPN VPN Type VPN Type VPN Name Nom du VPN Required Obligatoire VPN Server Serveur VPN Auto Connection Connexion automatique Confirm Confirmer Cancel Annuler vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool Outil VPN kylin-nm/src-vpn/translations/kylin-vpn_zh_Hant.ts0000664000175000017500000010400215167651420021325 0ustar fengfeng SinglePage Settings 設置 Kylin VPN VPN 工具 kylin vpn applet desktop message VPN 設定桌面提示 VpnAdvancedPage MPPE encryption algorithm: MPPE 加密演演算法: Use Stateful encryption 使用有狀態加密 Send PPP echo packets 發送 PPP 回顯包 Authentication Mode: 認證方式: PAP authentication PAP 認證 CHAP authentication CHAP 認證 MSCHAP authentication MSCHAP 認證 MSCHAP2 authentication MSCHAP2 認證 EAP authentication EAP 認證 Compression Mode: 壓縮方式: Allow BSD data compression 允許 BSD 壓縮 Allow Default data compression 允許 Default 壓縮 Allow TCP header compression 允許 TCP 頭壓縮 Use protocol field compression negotiation 使用協定域壓縮協商 Use Address/Control compression 使用位址/控制壓縮 All Available 任意 128-bit 128位 40-bit 40位 Use custom gateway port 使用自定義閘道埠 Use compression 使用壓縮 Use a TCP connection 使用 TCP 連接 Set virtual device type 設置虛擬設備類型 Set virtual device name 設置虛擬設備名稱 Limit TCP Maximum Segment Size(MSS) 限制 TCP 最大段尺寸(MSS) Randomize remote hosts 隨機化遠端主機 IPv6 tun link IPv6 tun 連接 Specify ping interval 指定 Ping 週期 Specify exit or restart ping 指定退出或重啟的 Ping Specify max routes 指定路由上限 Infinite retry on error 出錯時無限重試 Use custom key size 使用自訂金鑰大小 Choose 選擇 Use custom renegotiation interval 使用自定義重協商間隔 Use custom tunnel Maximum Transmission Umit(MTU) 使用自訂隧道最大單元傳輸(MTU) Use custom UDP fragment size 使用自訂 UDP 分片大小 Accept authenticated packets from any address (Float) 接受來自任何位址(Float)已通過身份驗證的數據包 Subject Match 主題匹配 Key File 金鑰檔案 Key Direction 金鑰方向 Server Address 伺服器位址 Port Proxy USername 代理使用者名 Proxy Password 代理密碼 General 常規 TLS settings TLS 設置 Server Certificate Check 伺服器證書檢驗 Use the previous authentication end (server) certificate 使用前面驗證端(伺服器)證書 Verify peer (server) certificate nsCertType specification 驗證對等點(伺服器)證書 nsCertType 指定 Mode 模式 Proxies 代理 Proxy Type 代理類型 Security 安全 HMAC Authentication HMAC 認證 Input content 輸入內容 No Self-adaption 自適應 Automatic 自動 Exit 退出 Restart 重啟 Don't verify certificate identification 不驗證證書標識 Verify the entire subject exactly 確切地驗證整個主題 Verify name exactly 精確驗證名稱 Verify name by prefix 按前綴驗證名稱 Server 伺服器 Client 用戶端 None TLS-Certification TLS-認證 TLS-Encryption TLS-加密 Not Required 不需要 Default 預設 Options: 選項: Request an inner IP address 請求內部IP位址 Enforce UDP encapsulation 強制 UDP 封裝 Use IP compression 使用IP壓縮 Enable custom password suggestions 啟用自訂密碼建議 Choose a private key 選擇私鑰 Key Files (*.key *.pem *.der *.p12 *.pfx) 私鑰檔 (*.key *.pem *.der *.p12.pfx) VpnConfigPage Type 類型 Name 名稱 Static Key 靜態金鑰 Local IP 本地IP位址 Remote IP 遠端IP位址 PIN Code PIN 碼 Password 密碼 NT Domain NT域 Server Address 伺服器位址 Authentication Mode 認證方式 CA Certificate CA 證書 User Certificate 用戶證書 Key Direction 金鑰方向 Private Key 私鑰 Private Key Password 私有金鑰密碼 Password Options 密碼選項 Username 使用者名 Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. 注意: 如果使用了金鑰方向,它必須和使用的VPN端相反。 如果使用了“1”,連接必須要使用“0”。 如果不確定使用哪個值,請聯繫您的系統管理員。 Choose 選擇 None Save password only for this user 僅對當前使用者保存密碼 Save password for all users 為所有使用者保存密碼 Ask password every time 每次都詢問 Don't require a password 不需要密碼 Required 必填 Certificate(TLS) 憑證(TLS) Static key 靜態金鑰 Password and certificate(TLS) 密碼與憑證(TLS) Certificate/Private key 證書/私鑰 Certificate/ssh-agent 證書/ ssh-agent Smart card 智慧卡 Choose a private key 選擇私鑰 Key Files (*.key *.pem *.der *.p12 *.pfx) 私鑰檔 (*.key *.pem *.der *.p12.pfx) Choose a CA certificate 選擇 CA 證書 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA檔 (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate 選擇用戶證書 Choose a Static key 選擇靜態金鑰 VpnDetail VPN IPv4 IPv6 Advanced 高級 Auto Connection 自動連接 Cancel 取消 Confirm 確定 VpnIpv4Page IPv4 Config IPv4 配置 Address 位址 Netmask 子網掩碼 Default Gateway 默認閘道 DNS Server DNS 伺服器 Search Domain 搜索域 DHCP Client ID DHCP 用戶端 ID Auto(DHCP) 自動 (DHCP) Manual 手動 VpnIpv6Page IPv6 Config IPv6 配置 Address 位址 Netmask 子網掩碼 Default Gateway 默認閘道 DNS Server DNS 伺服器 Search Domain 搜索域 Auto(DHCP) 自動 (DHCP) Manual 手動 VpnListItem Not connected 未連接 Disconnect 斷開 Connect 連接 VpnPage VPN VPN Settings VPN 設置 vpnAddPage create VPN 創建 VPN VPN Type VPN 類型 VPN Name VPN 名稱 Required 必填 VPN Server 伺服器位址 Auto Connection 自動連接 Confirm 確定 Cancel 取消 vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool VPN 工具 kylin-nm/src-vpn/translations/kylin-vpn_ms.ts0000664000175000017500000010444515167651420020364 0ustar fengfeng SinglePage Settings Kylin VPN kylin vpn applet desktop message VpnAdvancedPage MPPE encryption algorithm: Use Stateful encryption Send PPP echo packets Authentication Mode: PAP authentication CHAP authentication MSCHAP authentication MSCHAP2 authentication EAP authentication Compression Mode: Allow BSD data compression Allow Default data compression Allow TCP header compression Use protocol field compression negotiation Use Address/Control compression All Available 128-bit 40-bit Use custom gateway port Use compression Use a TCP connection Set virtual device type Set virtual device name Limit TCP Maximum Segment Size(MSS) Randomize remote hosts IPv6 tun link Specify ping interval Specify exit or restart ping Specify max routes Infinite retry on error Use custom key size Choose Use custom renegotiation interval Use custom tunnel Maximum Transmission Umit(MTU) Use custom UDP fragment size Accept authenticated packets from any address (Float) Subject Match Key File Key Direction Server Address Port Proxy USername Proxy Password General TLS settings Server Certificate Check Use the previous authentication end (server) certificate Verify peer (server) certificate nsCertType specification Mode Proxies Proxy Type Security HMAC Authentication Input content No Self-adaption Automatic Exit Restart Don't verify certificate identification Verify the entire subject exactly Verify name exactly Verify name by prefix Server Client None TLS-Certification TLS-Encryption Not Required Default Options: Request an inner IP address Enforce UDP encapsulation Use IP compression Enable custom password suggestions Choose a private key Key Files (*.key *.pem *.der *.p12 *.pfx) VpnConfigPage Type Name Static Key Local IP Remote IP PIN Code Password NT Domain Server Address Authentication Mode CA Certificate User Certificate Key Direction Private Key Private Key Password Password Options Username Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. Choose None Save password only for this user Save password for all users Ask password every time Don't require a password Required Certificate(TLS) Static key Password and certificate(TLS) Certificate/Private key Certificate/ssh-agent Smart card Choose a private key Key Files (*.key *.pem *.der *.p12 *.pfx) Choose a CA certificate CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate Choose a Static key VpnDetail VPN IPv4 IPv6 Advanced Auto Connection Cancel Confirm VpnIpv4Page IPv4 Config Address Netmask Default Gateway DNS Server Search Domain DHCP Client ID Auto(DHCP) Manual VpnIpv6Page IPv6 Config Address Netmask Default Gateway DNS Server Search Domain Auto(DHCP) Manual VpnListItem Not connected Disconnect Connect VpnPage VPN VPN Settings vpnAddPage create VPN VPN Type VPN Name Required VPN Server Auto Connection Confirm Cancel vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool kylin-nm/src-vpn/translations/kylin-vpn_zh_CN.ts0000664000175000017500000010401415167651420020736 0ustar fengfeng SinglePage Settings 设置 Kylin VPN VPN 工具 kylin vpn applet desktop message VPN 配置桌面提示 VpnAdvancedPage MPPE encryption algorithm: MPPE 加密算法: Use Stateful encryption 使用有状态加密 Send PPP echo packets 发送 PPP 回显包 Authentication Mode: 认证方式: PAP authentication PAP 认证 CHAP authentication CHAP 认证 MSCHAP authentication MSCHAP 认证 MSCHAP2 authentication MSCHAP2 认证 EAP authentication EAP 认证 Compression Mode: 压缩方式: Allow BSD data compression 允许 BSD 压缩 Allow Default data compression 允许 Default 压缩 Allow TCP header compression 允许 TCP 头压缩 Use protocol field compression negotiation 使用协议域压缩协商 Use Address/Control compression 使用地址/控制压缩 All Available 任意 128-bit 128位 40-bit 40位 Use custom gateway port 使用自定义网关端口 Use compression 使用压缩 Use a TCP connection 使用 TCP 连接 Set virtual device type 设置虚拟设备类型 Set virtual device name 设置虚拟设备名称 Limit TCP Maximum Segment Size(MSS) 限制 TCP 最大段尺寸(MSS) Randomize remote hosts 随机化远程主机 IPv6 tun link IPv6 tun 连接 Specify ping interval 指定 Ping 周期 Specify exit or restart ping 指定退出或重启的 Ping Specify max routes 指定路由上限 Infinite retry on error 出错时无限重试 Use custom key size 使用自定义密钥大小 Choose 选择 Use custom renegotiation interval 使用自定义重协商间隔 Use custom tunnel Maximum Transmission Umit(MTU) 使用自定义隧道最大单元传输(MTU) Use custom UDP fragment size 使用自定义 UDP 分片大小 Accept authenticated packets from any address (Float) 接受来自任何地址(Float)已通过身份验证的数据包 Subject Match 主题匹配 Key File 密钥文件 Key Direction 密钥方向 Server Address 服务器地址 Port 端口 Proxy USername 代理用户名 Proxy Password 代理密码 General 常规 TLS settings TLS 设置 Server Certificate Check 服务器证书检验 Use the previous authentication end (server) certificate 使用前面验证端(服务器)证书 Verify peer (server) certificate nsCertType specification 验证对等点(服务器)证书 nsCertType 指定 Mode 模式 Proxies 代理 Proxy Type 代理类型 Security 安全 HMAC Authentication HMAC 认证 Input content 输入内容 No Self-adaption 自适应 Automatic 自动 Exit 退出 Restart 重启 Don't verify certificate identification 不验证证书标识 Verify the entire subject exactly 确切地验证整个主题 Verify name exactly 精确验证名称 Verify name by prefix 按前缀验证名称 Server 服务器 Client 客户端 None TLS-Certification TLS-认证 TLS-Encryption TLS-加密 Not Required 不需要 Default 默认 Options: 选项: Request an inner IP address 请求内部 IP 地址 Enforce UDP encapsulation 强制 UDP 封装 Use IP compression 使用 IP 压缩 Enable custom password suggestions 启用自定义密码建议 Choose a private key 选择私钥 Key Files (*.key *.pem *.der *.p12 *.pfx) 私钥文件 (*.key *.pem *.der *.p12 *.pfx) VpnConfigPage Type 类型 Name 名称 Static Key 静态密钥 Local IP 本地 IP 地址 Remote IP 远程 IP 地址 PIN Code PIN 码 Password 密码 NT Domain NT 域 Server Address 服务器地址 Authentication Mode 认证方式 CA Certificate CA 证书 User Certificate 用户证书 Key Direction 密钥方向 Private Key 私钥 Private Key Password 私有密钥密码 Password Options 密码选项 Username 用户名 Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. 注意: 如果使用了密钥方向,它必须和使用的VPN端相反。如果使用了“1”,连接必须要使用“0”。如果不确定使用哪个值,请联系您的系统管理员。 Choose 选择 None Save password only for this user 仅对当前用户保存密码 Save password for all users 为所有用户保存密码 Ask password every time 每次都询问 Don't require a password 不需要密码 Required 必填 Certificate(TLS) 证书(TLS) Static key 静态密钥 Password and certificate(TLS) 密码和证书(TLS) Certificate/Private key 证书/私钥 Certificate/ssh-agent 证书/ ssh-agent Smart card 智能卡 Choose a private key 选择私钥 Key Files (*.key *.pem *.der *.p12 *.pfx) 私钥文件 (*.key *.pem *.der *.p12 *.pfx) Choose a CA certificate 选择 CA 证书 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA文件 (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate 选择用户证书 Choose a Static key 选择静态密钥 VpnDetail VPN IPv4 IPv6 Advanced 高级 Auto Connection 自动连接 Cancel 取消 Confirm 确定 VpnIpv4Page IPv4 Config IPv4 配置 Address 地址 Netmask 子网掩码 Default Gateway 默认网关 DNS Server DNS 服务器 Search Domain 搜索域 DHCP Client ID DHCP 客户端 ID Auto(DHCP) 自动 (DHCP) Manual 手动 VpnIpv6Page IPv6 Config IPv6 配置 Address 地址 Netmask 子网掩码 Default Gateway 默认网关 DNS Server DNS 服务器 Search Domain 搜索域 Auto(DHCP) 自动 (DHCP) Manual 手动 VpnListItem Not connected 未连接 Disconnect 断开 Connect 连接 VpnPage VPN VPN Settings 更多 VPN 设置 vpnAddPage create VPN 创建 VPN VPN Type VPN 类型 VPN Name VPN 名称 Required 必填 VPN Server 服务器地址 Auto Connection 自动连接 Confirm 确定 Cancel 取消 vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool VPN 工具 kylin-nm/src-vpn/translations/kylin-vpn_ug.ts0000664000175000017500000011357515167651420020364 0ustar fengfeng SinglePage Settings تور تەڭشىكى Kylin VPN ئەسۋابىVPN kylin vpn applet desktop message VPNتەڭشىكىنى ئۈستەل يۈزىدە كۆرسىتىش VpnAdvancedPage MPPE encryption algorithm: MPPE شىفىرلاش ھېسابلاش ئۇسۇلى: Use Stateful encryption ئىشلىتىش ھالىتى شىفىرلاشقان Send PPP echo packets pppقايتىپ كۆرسىتىش بوغچىسىغا يوللاش Authentication Mode: دەلىللەش شەكلى: PAP authentication PAP دەلىللەش CHAP authentication CHAP دەلىللەش MSCHAP authentication MSCHAP دەلىللەش MSCHAP2 authentication MSCHAP2 دەلىللەش EAP authentication EAP دەلىللەش Compression Mode: پىرېسلاش ھالىتى: Allow BSD data compression BSD نى پېرىسلاشقا يول قويۇش Allow Default data compression Defaultنى پېرىسلاشقا يول قويۇش Allow TCP header compression TCP نى پېرىسلاشقا يول قويۇش Use protocol field compression negotiation ئىشلىتىش كېلىشىمى دائىرىسىدىكى پىرېسلاش كېلىشىمى Use Address/Control compression ئادرېس/كونتروللاپ پېرىسلاشنى ئىشلىتىش All Available بارلىق بارلار 128-bit 128 بىتلىق 40-bit 40 بىتلىق Use custom gateway port ئېنىقلىما بېرىش تور ئۆتكىلى ئېغىزىنى ئىشلىتىش Use compression پېرىسلاپ ئىشلىتىش Use a TCP connection TCP ئۇلاش ئۇسۇلىنى قوللىنىش Set virtual device type مەۋھۇم ئۈسكۈنە تىپىنى بەلگىلەش Set virtual device name مەۋھۇم ئۈسكۈنە نامىنى بەلگىلەش Limit TCP Maximum Segment Size(MSS) TCP ئەڭ چوڭ بۆلەك چوڭلۇقىنى چەكلەش(MSS) Randomize remote hosts ئىختىيارىي ھالەتتە باش ئاپپاراتنى يىراقتىن كونترول قىلىش IPv6 tun link IPv6 tunئۇلاش Specify ping interval pingدەۋرىيلىكىنى بەلگىلەش Specify exit or restart ping چېكىنىش ياكى قايتا قوزغالغان ping نى كۆرسىتىپ بېرىش Specify max routes چەكلىك لىنىيەنى كۆرسىتىپ بېرىش Infinite retry on error خاتالىق چىققاندا چەكسىز ھالەتتە قايتا تەكرارلاش Use custom key size ئېنىقلىما بېرىلگەن مەخپىي ئاچقۇچ چوڭ كىچىكلىكىنى ئىشلىتىش Choose تاللاش Use custom renegotiation interval ئۆز ئالدىغا قايتا سۆھبەتلىشىش ئارىلىقىنى ئىشلىتىش Use custom tunnel Maximum Transmission Umit(MTU) خاس تونېلنىڭ ئەڭ چوڭ يوللانما ئۇزىتىش مۇئەسسەسەسى(MTU) نى ئىشلىتىش Use custom UDP fragment size ئېنىقلىما بېرىلگەن UDP پارچىلاش چوڭلۇقىنى ئىشلىتىش Accept authenticated packets from any address (Float) ھەرقانداق ئادرېس قوبۇل قىلىش ( Float ) سالاھىيەت تەكشۈرۈش ئارقىلىق سانلىق مەلۇمات بوغچىسى Subject Match باش تېمىنى ماسلاشتۇرۇش Key File ئاچقۇچلۇق ھۆججەت Key Direction ئاچقۇچلۇق يۆنىلىش Server Address مۇلازىمېتىر ئادرېسى Port ئېغىزى Proxy USername ۋاكالىتەن ئابۇنت نامى Proxy Password ۋاكالىتەن مەخپىي نومۇر General ئادەتتىكى قائىدە TLS settings TLS تەڭشەكلىرى Server Certificate Check مۇلازىمېتىر كىنىشكىسىنى تەكشۈرۈش Use the previous authentication end (server) certificate بۇرۇنقى دەلىللەش ئاخىرى (مۇلازىمېتىر) كىنىشكىسىنى ئىشلىتىش Verify peer (server) certificate nsCertType specification تەڭ نۇقتا (مۇلازىمېتىر) كىنىشكىسى nsCertType نىڭ كونكرېتلىقىنى دەلىللەش Mode ئەندىزە Proxies ۋاكالىتەن Proxy Type ۋاكالىتەن تۈرى Security بىخەتەرلىك HMAC Authentication HMAC دەلىللەش Input content مەزمۇن كىرگۈزۈش No ياق Self-adaption ئۆز-ئۆزىگە ماسلىشىش Automatic ئاپتوماتىك Exit چىقىش ئېغىزى Restart قايتا قوزغىتىش Don't verify certificate identification كىنىشكا سالاھىيەت ئىسپاتلاشنى ئىسپاتلىماڭ Verify the entire subject exactly پۈتۈن تېمىنى تەلتۆكۈس ئېنىقلاش Verify name exactly نامىنى ئېنىقلاپ دەلىللەش Verify name by prefix نامىنى ئالدى قوشۇلما بويىچە دەلىللەش Server مۇلازىمېتىر Client ئەپ None يوق TLS-Certification TLS-دەلىللەش TLS-Encryption TLS-شىفىرلاش Not Required تەلەپ قىلىنمايدۇ Default ئەسلىدىكى Options: تاللانمىلار: Request an inner IP address ئىچكى IP ئادرېسى ئىلتىماس قىلىش Enforce UDP encapsulation UDP قاپلاشنى ئىجرا قىلىش Use IP compression IP پىرېسلاش ئىشلىتىش Enable custom password suggestions ئۆزى بەلگىلىگەن مەخپىي نومۇر قوزغىتىش تەكلىپى Choose a private key شەخسىي ئاچقۇچ تاللاش Key Files (*.key *.pem *.der *.p12 *.pfx) ئاچقۇچلۇق ھۆججەتلەر (*.key *.pem *.der *.p12 *.pfx) VpnConfigPage Type تۈرى Name ئىسىم-فامىلىسى Static Key تىنچ ھالەتتىكى مەخپىي ئاچقۇچ Local IP يەرلىك ئادرېسIP Remote IP يىراقتىن كونترول قىلىدىغان ئادرېسIP PIN Code PIN كودى Password مەخپىي ئاچقۇچ NT Domain NT دائىرە Server Address مۇلازىمېتىر ئادرېسى Authentication Mode دەلىللەش ئەندىزىسى CA Certificate CA كىنىشكىسى User Certificate ئىشلەتكۈچى كىنىشكىسى Key Direction ئاچقۇچلۇق يۆنىلىش Private Key شەخسىي ئاچقۇچ Private Key Password شەخسىي ئاچقۇچ پارولى Password Options پارول تاللانمىلىرى Username ئابۇنت نامى Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. دىققەت:ئەگەر مەخپىي ئاچقۇچ يۆنىلىشىنى ئىشلەتكەن بولسا، ئۇ چوقۇم ئىشلەتكەن VPN ئۇچى بىلەن قارىمۇقارشى بولۇشى كېرەك. ئەگەر «1» نى ئىشلەتكەن بولسا، ئۇلاشتا چوقۇم «0» نى ئىشلىتىش كېرەك. ئەگەر قايسى قىممەتنى ئىشلىتىشنى جەزملەشتۈرەلمىسىڭىز سىستېما باشقۇرغۇچى بىلەن ئالاقىلىشىڭ. Choose تاللاش None يوق Save password only for this user پەقەت نۆۋەتتىكى ئابۇنت مەخپىي نومۇر ساقلاش Save password for all users بارلىق ئابونتلار ئۈچۈن مەخپىي نومۇر ساقلاش Ask password every time ھەر قېتىم مەخپىي نومۇر سوراش Don't require a password مەخپىي نومۇر تەلەپ قىلماسلىق Required مۇقەررەر تولدۇرۇش Certificate(TLS) كىنىشكا(TLS) Static key تىنچ ھالەتتىكى ئاچقۇچ Password and certificate(TLS) مەخپىي نومۇر ۋە كىنىشكا(TLS) Certificate/Private key كىنىشكا/خۇسۇسىي ئاچقۇچ Certificate/ssh-agent كىنىشكا/ ssh-agent Smart card ئەقلىي ئىقتىدارلىق كارتا Choose a private key شەخسىي ئاچقۇچ تاللاش Key Files (*.key *.pem *.der *.p12 *.pfx) ئاچقۇچلۇق ھۆججەتلەر (*.key *.pem *.der *.p12 *.pfx) Choose a CA certificate CA كىنىشكىسى تاللاش CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA ھۆججەتلىرى (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate ئىشلەتكۈچى كىنىشكىسى تاللاش Choose a Static key تىنچ ھالەتتىكى ئاچقۇچ تاللاش VpnDetail VPN IPv4 IPv6 Advanced يۇقىرى دەرىجە Auto Connection ئاپتوماتىك ئۇلاش Cancel ئەمەلدىن قالدۇرۇش Confirm جەزملەشتۈرۈش VpnIpv4Page IPv4 Config IPv4 تەڭشىكى Address ئادرېس Netmask تارماق تور يوشۇرۇن نومۇرى Default Gateway ئەسلىدىكى تور ئۆتكىلى DNS Server DNS مۇلازىمېتىرى Search Domain تور نامىنى ئىزدەش DHCP Client ID DHCP ئەپ IDسى Auto(DHCP) ئاپتوماتىك(DHCP) Manual قوللانما VpnIpv6Page IPv6 Config IPv6 تەڭشىكى Address ئادرېس Netmask تارماق تور يوشۇرۇن نومۇرى Default Gateway ئەسلىدىكى تور ئۆتكىلى DNS Server DNS مۇلازىمېتىرى Search Domain تور نامىنى ئىزدەش Auto(DHCP) ئاپتوماتىك(DHCP) Manual قوللانما VpnListItem Not connected ئۇلانمىغان Disconnect ئۈزۈۋېتىش Connect ئۇلىنىش VpnPage VPN VPN Settings VPN تەڭشەكلىرى vpnAddPage create VPN VPN قۇرۇش VPN Type VPN تۈرى VPN Name VPN نامى Required مۇقەررەر تولدۇرۇش VPN Server VPN مۇلازىمېتىرى Auto Connection ئاپتوماتىك ئۇلاش Confirm جەزملەشتۈرۈش Cancel ئەمەلدىن قالدۇرۇش vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool vpn قورالى kylin-nm/src-vpn/translations/kylin-vpn_bo.ts0000664000175000017500000010445615167651420020347 0ustar fengfeng SinglePage Settings Kylin VPN kylin vpn applet desktop message VpnAdvancedPage MPPE encryption algorithm: Use Stateful encryption Send PPP echo packets Authentication Mode: PAP authentication CHAP authentication MSCHAP authentication MSCHAP2 authentication EAP authentication Compression Mode: Allow BSD data compression Allow Default data compression Allow TCP header compression Use protocol field compression negotiation Use Address/Control compression All Available 128-bit 40-bit Use custom gateway port Use compression Use a TCP connection Set virtual device type Set virtual device name Limit TCP Maximum Segment Size(MSS) Randomize remote hosts IPv6 tun link Specify ping interval Specify exit or restart ping Specify max routes Infinite retry on error Use custom key size Choose Use custom renegotiation interval Use custom tunnel Maximum Transmission Umit(MTU) Use custom UDP fragment size Accept authenticated packets from any address (Float) Subject Match Key File Key Direction Server Address Port Proxy USername Proxy Password General TLS settings Server Certificate Check Use the previous authentication end (server) certificate Verify peer (server) certificate nsCertType specification Mode Proxies Proxy Type Security HMAC Authentication Input content No Self-adaption Automatic Exit Restart Don't verify certificate identification Verify the entire subject exactly Verify name exactly Verify name by prefix Server Client None TLS-Certification TLS-Encryption Not Required Default Options: Request an inner IP address Enforce UDP encapsulation Use IP compression Enable custom password suggestions Choose a private key Key Files (*.key *.pem *.der *.p12 *.pfx) VpnConfigPage Type Name Static Key Local IP Remote IP PIN Code Password NT Domain Server Address Authentication Mode CA Certificate User Certificate Key Direction Private Key Private Key Password Password Options Username Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. Choose None Save password only for this user Save password for all users Ask password every time Don't require a password Required Certificate(TLS) Static key Password and certificate(TLS) Certificate/Private key Certificate/ssh-agent Smart card Choose a private key Key Files (*.key *.pem *.der *.p12 *.pfx) Choose a CA certificate CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate Choose a Static key VpnDetail VPN IPv4 IPv6 Advanced Auto Connection Cancel Confirm VpnIpv4Page IPv4 Config Address Netmask Default Gateway DNS Server Search Domain DHCP Client ID Auto(DHCP) Manual VpnIpv6Page IPv6 Config Address Netmask Default Gateway DNS Server Search Domain Auto(DHCP) Manual VpnListItem Not connected Disconnect Connect VpnPage VPN VPN Settings vpnAddPage create VPN VPN Type VPN类型 VPN Name Required VPN Server Auto Connection Confirm Cancel vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool kylin-nm/src-vpn/translations/kylin-vpn_mn.ts0000664000175000017500000012443515167651420020360 0ustar fengfeng SinglePage Settings ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠬᠤ Kylin VPN VPN ᠪᠠᠭᠠᠵᠢ kylin vpn applet desktop message VPN ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ ᠰᠢᠷᠡᠭᠡᠨ ᠨᠢᠭᠤᠷ ᠤ᠋ᠨ ᠠᠩᠬᠠᠷᠤᠭᠤᠯᠭ᠎ᠠ VpnAdvancedPage MPPE encryption algorithm: MPPE ᠨᠢᠭᠤᠴᠠᠯᠠᠨ ᠪᠤᠳᠤᠬᠤ ᠠᠷᠭ᠎ᠠ: Use Stateful encryption ᠨᠢᠭᠤᠴᠠᠯᠠᠭᠰᠠᠨ ᠪᠠᠢᠳᠠᠯ ᠳᠦᠯᠦᠪ ᠢ᠋ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ Send PPP echo packets PPP ᠪᠤᠴᠠᠭᠠᠨ ᠢᠯᠡᠷᠡᠬᠦᠯᠬᠦ ᠪᠠᠭᠯᠠᠭ᠎ᠠ ᠵᠢ ᠢᠯᠡᠭᠡᠬᠦ Authentication Mode: ᠬᠡᠷᠡᠴᠢᠯᠡᠬᠦ ᠠᠷᠭ᠎ᠠ: PAP authentication PAP ᠬᠡᠷᠡᠴᠢᠯᠡᠯ CHAP authentication CHAP ᠭᠡᠷᠡᠴᠢᠯᠡᠯ MSCHAP authentication MSCHAP ᠭᠡᠷᠡᠴᠢᠯᠡᠯ MSCHAP2 authentication MSCHAP2 ᠭᠡᠷᠡᠴᠢᠯᠡᠯ EAP authentication EAP ᠭᠡᠷᠡᠴᠢᠯᠡᠯ Compression Mode: ᠠᠪᠴᠢᠭᠤᠯᠬᠤ ᠠᠷᠭ᠎ᠠ: Allow BSD data compression BSD ᠠᠪᠴᠢᠭᠤᠯᠤᠯ ᠢ᠋ ᠵᠦᠪᠰᠢᠶᠡᠷᠡᠬᠦ Allow Default data compression Default ᠠᠪᠴᠢᠭᠤᠯᠤᠯ ᠢ᠋ ᠵᠦᠪᠰᠢᠶᠡᠷᠡᠬᠦ Allow TCP header compression TCP ᠲᠤᠯᠤᠭᠠᠢ ᠠᠪᠴᠢᠭᠤᠯᠤᠯ ᠢ᠋ ᠵᠦᠪᠰᠢᠶᠡᠷᠡᠬᠦ Use protocol field compression negotiation ᠭᠡᠷ᠎ᠡ ᠵᠢᠨ ᠬᠡᠰᠡᠭ ᠤ᠋ᠨ ᠠᠪᠴᠢᠭᠤᠯᠬᠤ ᠵᠦᠪᠰᠢᠯᠴᠡᠯ ᠢ᠋ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ Use Address/Control compression ᠬᠡᠷᠡᠭᠯᠡᠬᠦ ᠬᠠᠶᠢᠭ / ᠠᠪᠴᠢᠭᠤᠯᠤᠯ ᠢ᠋ ᠡᠵᠡᠮᠳᠡᠬᠦ All Available ᠶᠠᠮᠠᠷᠪᠠ 128-bit 128- ᠤᠷᠤᠨ 40-bit 40- ᠤᠷᠤᠨ Use custom gateway port ᠦᠪᠡᠷᠳᠡᠭᠡᠨ ᠳᠤᠭᠳᠠᠭᠠᠭᠰᠠᠨ ᠨᠸᠲ ᠪᠤᠭᠤᠮᠳᠠ ᠵᠢᠨ ᠦᠵᠦᠬᠦᠷ ᠢ᠋ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ Use compression ᠠᠪᠴᠢᠭᠤᠯᠤᠯ ᠢ᠋ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ Use a TCP connection TCP ᠴᠦᠷᠬᠡᠯᠡᠬᠡ ᠵᠢ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ Set virtual device type ᠳᠠᠭᠤᠷᠢᠶᠠᠮᠠᠯ ᠳᠦᠬᠦᠬᠡᠷᠦᠮᠵᠢ ᠵᠢᠨ ᠳᠦᠷᠦᠯ ᠵᠦᠢᠯ ᠢ᠋ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠬᠤ Set virtual device name ᠳᠠᠭᠤᠷᠢᠶᠠᠮᠠᠯ ᠳᠦᠬᠦᠬᠡᠷᠦᠮᠵᠢ ᠵᠢᠨ ᠨᠡᠷᠡᠢᠳᠦᠯ ᠢ᠋ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠬᠤ Limit TCP Maximum Segment Size(MSS) TCP ᠤ᠋ᠨ/ ᠵᠢᠨ ᠬᠠᠮᠤᠭ ᠤ᠋ᠨ ᠶᠡᠬᠡ ᠬᠡᠰᠡᠭ ᠤ᠋ᠨ ᠬᠡᠮᠵᠢᠶ᠎ᠡ ᠵᠢ ᠬᠢᠵᠠᠭᠠᠷᠯᠠᠬᠤ (MSS) Randomize remote hosts ᠳᠠᠰᠢᠷᠠᠮᠴᠢᠯᠠᠭᠰᠠᠨ ᠠᠯᠤᠰ ᠡᠵᠡᠮᠰᠢᠯ ᠤ᠋ᠨ ᠭᠤᠤᠯ ᠮᠠᠰᠢᠨ IPv6 tun link IPv6 tun ᠴᠦᠷᠬᠡᠯᠡᠬᠡ Specify ping interval ping ᠤ᠋ᠨ/ ᠵᠢᠨ ᠦᠶᠡᠯᠡᠯ ᠢ᠋ ᠳᠤᠭᠳᠠᠬᠤ Specify exit or restart ping ᠪᠤᠴᠠᠵᠤ ᠭᠠᠷᠤᠭᠰᠠᠨ ᠪᠤᠶᠤ ᠳᠠᠬᠢᠨ ᠡᠬᠢᠯᠡᠭᠰᠡᠨ ping ᠢ᠋/ ᠵᠢ ᠳᠤᠭᠳᠠᠬᠤ Specify max routes ᠵᠠᠮᠴᠢᠯᠠᠭᠤᠷ ᠤ᠋ᠨ ᠳᠡᠭᠡᠳᠦ ᠬᠢᠵᠠᠭᠠᠷ ᠢ᠋ ᠳᠤᠭᠳᠠᠬᠤ Infinite retry on error ᠠᠯᠳᠠᠭ᠎ᠠ ᠭᠠᠷᠬᠤ ᠦᠶ᠎ᠡ ᠳ᠋ᠤ᠌ ᠬᠢᠵᠠᠭᠠᠷ ᠦᠬᠡᠢ ᠳᠠᠬᠢᠵᠤ ᠳᠤᠷᠰᠢᠬᠤ Use custom key size ᠦᠪᠡᠷᠳᠡᠭᠡᠨ ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠤᠭᠰᠠᠨ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠤ᠋ᠨ ᠬᠡᠮᠵᠢᠶ᠎ᠡ ᠵᠢ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ Choose ᠰᠤᠩᠭᠤᠬᠤ Use custom renegotiation interval ᠦᠪᠡᠷᠳᠡᠭᠡᠨ ᠳᠤᠭᠳᠠᠭᠠᠭᠰᠠᠨ ᠳᠠᠬᠢᠨ ᠵᠦᠪᠰᠢᠯᠴᠡᠬᠦ ᠵᠠᠭᠠᠭ ᠢ᠋ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ Use custom tunnel Maximum Transmission Umit(MTU) ᠦᠪᠡᠷᠳᠡᠭᠡᠨ ᠳᠤᠭᠳᠠᠭᠠᠭᠰᠠᠨ ᠰᠤᠪᠠᠭ ᠤ᠋ᠨ ᠬᠠᠮᠤᠭ ᠤ᠋ᠨ ᠶᠡᠬᠡ ᠨᠢᠭᠡᠴᠢ ᠵᠢᠨ ᠳᠠᠮᠵᠢᠭᠤᠯᠭ᠎ᠠ ᠵᠢ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ (MTU) Use custom UDP fragment size ᠦᠪᠡᠷᠳᠡᠭᠡᠨ ᠳᠤᠭᠳᠠᠭᠠᠭᠰᠠᠨ UDP ᠬᠤᠪᠢᠶᠠᠷᠢ ᠬᠡᠰᠡᠭ ᠤ᠋ᠨ ᠬᠡᠮᠵᠢᠶ᠎ᠡ ᠵᠢ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ Accept authenticated packets from any address (Float) ᠶᠠᠮᠠᠷᠪᠠ ᠬᠠᠶᠢᠭ (Float) ᠵᠢᠡᠷ ᠢᠷᠡᠭᠰᠡᠨ ᠨᠢᠭᠡᠨᠳᠡ ᠪᠡᠶ᠎ᠡ ᠵᠢᠨ ᠭᠠᠷᠤᠯ ᠢ᠋ ᠪᠠᠳᠤᠯᠠᠭᠠᠵᠢᠭᠤᠯᠤᠭᠰᠠᠨ ᠳ᠋ᠠᠢᠲ᠋ᠠ ᠪᠠᠭᠯᠠᠭ᠎ᠠ ᠵᠢ ᠬᠦᠯᠢᠶᠡᠵᠤ ᠠᠪᠤᠨ᠎ᠠ Subject Match ᠭᠤᠤᠯ ᠰᠡᠳᠦᠪ ᠠᠪᠴᠠᠯᠳᠤᠬᠤ Key File ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠤ᠋ᠨ ᠹᠠᠢᠯ Key Direction ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠤ᠋ᠨ ᠴᠢᠭᠯᠡᠯ Server Address ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ ᠤ᠋ᠨ ᠬᠠᠶᠢᠭ Port ᠦᠵᠦᠬᠦᠷ Proxy USername ᠤᠷᠤᠯᠠᠭᠴᠢ ᠬᠡᠷᠡᠭᠡᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠡᠷ᠎ᠡ Proxy Password ᠤᠷᠤᠯᠠᠭᠴᠢ ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ General ᠳᠦᠷᠢᠮᠵᠢᠯ TLS settings TLS ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Server Certificate Check ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ ᠤ᠋ᠨ ᠦᠨᠡᠮᠯᠡᠯ ᠢ᠋ ᠰᠢᠯᠭᠠᠨ ᠪᠠᠢᠴᠠᠭᠠᠬᠤ Use the previous authentication end (server) certificate ᠡᠮᠦᠨᠡᠬᠢ ᠪᠠᠳᠤᠯᠠᠭᠠᠵᠢᠭᠤᠯᠬᠤ ᠦᠵᠦᠬᠦᠷ ᠤ᠋ᠨ ᠦᠨᠡᠮᠯᠡᠯ ( ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ) ᠢ᠋ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ Verify peer (server) certificate nsCertType specification ᠳᠡᠩᠴᠡᠬᠦᠦ ᠴᠡᠭ ( ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ) ᠤ᠋ᠨ ᠦᠨᠡᠮᠯᠡᠯ nsCertType ᠢ᠋/ ᠵᠢ ᠪᠠᠳᠤᠯᠠᠭᠠᠵᠢᠭᠤᠯᠵᠤ ᠳᠤᠭᠳᠠᠬᠤ Mode ᠮᠤᠳ᠋ Proxies ᠤᠷᠤᠯᠠᠭᠴᠢ Proxy Type ᠤᠷᠤᠯᠠᠭᠴᠢ ᠵᠢᠨ ᠳᠦᠷᠦᠯ ᠵᠦᠢᠯ Security ᠠᠮᠤᠷ ᠳᠦᠪᠰᠢᠨ HMAC Authentication HMAC ᠭᠡᠷᠡᠴᠢᠯᠡᠯ Input content ᠤᠷᠤᠭᠤᠯᠬᠤ ᠠᠭᠤᠯᠭ᠎ᠠ No ᠪᠢᠰᠢ/ ᠦᠬᠡᠢ Self-adaption ᠦᠪᠡᠷᠳᠡᠭᠡᠨ ᠵᠤᠬᠢᠴᠠᠬᠤ Automatic ᠠᠦ᠋ᠲ᠋ᠣ᠋ Exit ᠪᠤᠴᠠᠵᠤ ᠭᠠᠷᠬᠤ Restart ᠳᠠᠬᠢᠨ ᠡᠬᠢᠯᠡᠬᠦ Don't verify certificate identification ᠦᠨᠡᠮᠯᠡᠯ ᠤ᠋ᠨ ᠳᠡᠮᠳᠡᠭ ᠢ᠋ ᠪᠠᠳᠤᠯᠠᠭᠠᠵᠢᠭᠤᠯᠬᠤ ᠦᠬᠡᠢ Verify the entire subject exactly ᠪᠦᠬᠦᠢᠯᠡ ᠭᠤᠤᠯ ᠰᠡᠳᠦᠪ ᠢ᠋ ᠪᠠᠳᠤᠳᠠᠢ ᠪᠠᠳᠤᠯᠠᠭᠠᠵᠢᠭᠤᠯᠬᠤ Verify name exactly ᠨᠡᠷᠡᠢᠳᠦᠯ ᠢ᠋ ᠤᠨᠤᠪᠴᠢᠳᠠᠢ ᠪᠠᠳᠤᠯᠠᠭᠠᠵᠢᠭᠤᠯᠬᠤ Verify name by prefix ᠤᠭᠳᠤᠪᠤᠷᠢ ᠪᠡᠷ ᠨᠡᠷᠡᠢᠳᠦᠯ ᠢ᠋ ᠪᠠᠳᠤᠯᠠᠭᠠᠵᠢᠭᠤᠯᠬᠤ Server ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ Client ᠬᠡᠷᠡᠭᠡᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠦᠵᠦᠬᠦᠷ None ᠪᠠᠢᠬᠤ ᠦᠬᠡᠢ TLS-Certification TLS- ᠭᠡᠷᠡᠴᠢᠯᠡᠯ TLS-Encryption TLS- ᠨᠢᠭᠤᠴᠠᠯᠠᠬᠤ Not Required ᠱᠠᠭᠠᠷᠳᠠᠬᠤ ᠦᠬᠡᠢ Default ᠠᠶᠠᠳᠠᠯ Options: ᠰᠤᠩᠭᠤᠭᠳᠠᠬᠤᠨ: Request an inner IP address ᠳᠤᠳᠤᠭᠠᠳᠤ IP ᠬᠠᠶᠢᠭ ᠢ᠋ ᠭᠤᠶᠤᠴᠢᠯᠠᠬᠤ Enforce UDP encapsulation ᠠᠯᠪᠠ ᠪᠡᠷ UDP ᠪᠢᠳᠡᠬᠦᠮᠵᠢᠯᠡᠬᠦ Use IP compression IP ᠠᠪᠴᠢᠭᠤᠯᠤᠯ ᠢ᠋ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ Enable custom password suggestions ᠦᠪᠡᠷᠳᠡᠭᠡᠨ ᠳᠤᠭᠳᠠᠭᠠᠬᠰᠠᠨ ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ ᠤ᠋ᠨ ᠰᠠᠨᠠᠭᠤᠯᠤᠮᠵᠢ ᠵᠢ ᠡᠬᠢᠯᠡᠬᠦᠯᠬᠦ Choose a private key ᠬᠤᠪᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠢ᠋ ᠰᠤᠩᠭᠤᠬᠤ Key Files (*.key *.pem *.der *.p12 *.pfx) ᠬᠤᠪᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠤ᠋ᠨ ᠹᠠᠢᠯ (*.key *.pem *.der *.p12 *.pfx) VpnConfigPage Type ᠳᠦᠷᠦᠯ ᠵᠦᠢᠯ Name ᠨᠡᠷᠡᠢᠳᠦᠯ Static Key ᠳᠠᠢᠪᠤᠩ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ Local IP ᠲᠤᠰ ᠭᠠᠵᠠᠷ ᠤ᠋ᠨ IP ᠬᠠᠶᠢᠭ Remote IP ᠠᠯᠤᠰ ᠡᠵᠡᠮᠰᠢᠯ ᠤ᠋ᠨ IP ᠬᠠᠶᠢᠭ PIN Code PIN ᠺᠤᠳ᠋ Password ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ NT Domain NT ᠬᠡᠰᠡᠭ Server Address ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ ᠤ᠋ᠨ ᠬᠠᠶᠢᠭ Authentication Mode ᠬᠡᠷᠡᠴᠢᠯᠡᠬᠦ ᠠᠷᠭ᠎ᠠ CA Certificate CA ᠦᠨᠡᠮᠯᠡᠯ User Certificate ᠬᠡᠷᠡᠭᠡᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠦᠨᠡᠮᠯᠡᠯ Key Direction ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠤ᠋ᠨ ᠴᠢᠭᠯᠡᠯ Private Key ᠬᠤᠪᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ Private Key Password ᠬᠤᠪᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠤ᠋ᠨ ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ Password Options ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ ᠤ᠋ᠨ ᠰᠤᠩᠭᠤᠭᠳᠠᠬᠤᠨ Username ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠡᠷ᠎ᠡ Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. ᠠᠩᠬᠠᠷᠤᠭᠠᠷᠠᠢ: ᠬᠡᠷᠪᠡ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠤ᠋ᠨ ᠴᠢᠭᠯᠡᠯ ᠢ᠋ ᠬᠡᠷᠡᠭᠯᠡᠭᠰᠡᠨ ᠪᠤᠯ᠂ ᠲᠡᠷᠡ ᠨᠢ ᠡᠷᠬᠡᠪᠰᠢ ᠬᠡᠷᠡᠭᠯᠡᠭᠰᠡᠨ VPN ᠦᠵᠦᠬᠦᠷ ᠲᠠᠢ ᠡᠰᠡᠷᠬᠦ ᠪᠠᠢᠬᠤ ᠬᠡᠷᠡᠭᠳᠡᠢ᠃ ᠬᠡᠷᠪᠡ '1' ᠢ᠋/ ᠵᠢ ᠬᠡᠷᠡᠭᠯᠡᠭᠰᠡᠨ ᠪᠤᠯ᠂ ᠴᠦᠷᠬᠡᠯᠡᠭᠡ ᠨᠢ ᠡᠷᠬᠡᠪᠰᠢ '0' ᠢ᠋/ ᠵᠢ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ ᠬᠡᠷᠡᠭᠳᠡᠢ᠃ ᠬᠡᠷᠪᠡ ᠠᠯᠢ ᠵᠢ ᠨᠢ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ ᠪᠡᠨ ᠳᠤᠭᠳᠠᠵᠤ ᠴᠢᠳᠠᠭ᠎ᠠ ᠦᠬᠡᠢ ᠪᠤᠯ᠂ ᠲᠠ ᠰᠢᠰᠲ᠋ᠧᠮ ᠤ᠋ᠨ ᠬᠠᠮᠢᠶᠠᠷᠤᠭᠴᠢ ᠲᠠᠢ ᠪᠡᠨ ᠬᠠᠷᠢᠯᠴᠠᠭᠠᠷᠠᠢ. Choose ᠰᠤᠩᠭᠤᠬᠤ None ᠪᠠᠢᠬᠤ ᠦᠬᠡᠢ Save password only for this user ᠵᠦᠪᠬᠡᠨ ᠤᠳᠤᠬᠠᠨ ᠤ᠋ ᠬᠡᠷᠡᠭᠡᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ ᠢ᠋ ᠬᠠᠳᠠᠭᠠᠯᠠᠨ᠎ᠠ Save password for all users ᠪᠦᠬᠦᠢᠯᠡ ᠬᠡᠷᠡᠭᠡᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ ᠢ᠋ ᠬᠠᠳᠠᠭᠠᠯᠠᠨ᠎ᠠ Ask password every time ᠤᠳᠠᠭ᠎ᠠ ᠪᠦᠷᠢ ᠠᠰᠠᠭᠤᠨ ᠯᠠᠪᠯᠠᠬᠤ Don't require a password ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ ᠬᠡᠷᠡᠭ ᠦᠬᠡᠢ Required ᠡᠷᠬᠡᠪᠰᠢ ᠳᠠᠭᠯᠠᠬᠤ Certificate(TLS) ᠦᠨᠡᠮᠯᠡᠯ (TLS) Static key ᠳᠠᠢᠪᠤᠩ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ Password and certificate(TLS) ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ ᠬᠢᠬᠡᠳ ᠦᠨᠡᠮᠯᠡᠯ (TLS) Certificate/Private key ᠦᠨᠡᠮᠯᠡᠯ / ᠬᠤᠪᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ Certificate/ssh-agent ᠦᠨᠡᠮᠯᠡᠯ /ssh-agent Smart card ᠤᠶᠤᠯᠢᠭ ᠺᠠᠷᠲ Choose a private key ᠬᠤᠪᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠢ᠋ ᠰᠤᠩᠭᠤᠬᠤ Key Files (*.key *.pem *.der *.p12 *.pfx) ᠬᠤᠪᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠤ᠋ᠨ ᠹᠠᠢᠯ (*.key *.pem *.der *.p12 *.pfx) Choose a CA certificate CA ᠦᠨᠡᠮᠯᠡᠯ ᠢ᠋ ᠰᠤᠩᠭᠤᠬᠤ CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA ᠹᠠᠢᠯ (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate ᠬᠡᠷᠡᠭᠡᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠦᠨᠡᠮᠯᠡᠯ ᠢ᠋ ᠰᠤᠩᠭᠤᠬᠤ Choose a Static key ᠳᠠᠢᠪᠤᠩ ᠨᠢᠭᠤᠴᠠ ᠳᠦᠯᠬᠢᠬᠦᠷ ᠢ᠋ ᠰᠤᠩᠭᠤᠬᠤ VpnDetail VPN vpn IPv4 ipv4 IPv6 ipv6 Advanced ᠦᠨᠳᠦᠷ ᠳᠡᠰ Auto Connection ᠠᠦ᠋ᠲ᠋ᠣ᠋ ᠴᠦᠷᠬᠡᠯᠡᠬᠦ Cancel ᠦᠭᠡᠢᠰᠬᠡᠬᠦ Confirm ᠪᠠᠳᠤᠯᠠᠬᠤ VpnIpv4Page IPv4 Config IPv4 ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Address ᠬᠠᠶᠢᠭ Netmask ᠬᠤᠪᠢᠶᠠᠷᠢ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠳᠠᠯᠳᠠᠯᠠᠯ ᠺᠤᠳ᠋ Default Gateway ᠠᠶᠠᠳᠠᠯ ᠨᠸᠲ ᠪᠤᠭᠤᠮᠳᠠ DNS Server DNS ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ Search Domain ᠬᠠᠢᠬᠤ ᠬᠡᠰᠡᠭ DHCP Client ID DHCP ᠬᠡᠷᠡᠭᠡᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠦᠵᠦᠬᠦᠷ ID Auto(DHCP) ᠠᠦ᠋ᠲ᠋ᠣ᠋ (DHCP) Manual ᠠᠦ᠋ᠲ᠋ᠣ᠋ ᠪᠤᠰᠤ VpnIpv6Page IPv6 Config IPv6 ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Address ᠬᠠᠶᠢᠭ Netmask ᠬᠤᠪᠢᠶᠠᠷᠢ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠳᠠᠯᠳᠠᠯᠠᠯ ᠺᠤᠳ᠋ Default Gateway ᠠᠶᠠᠳᠠᠯ ᠨᠸᠲ ᠪᠤᠭᠤᠮᠳᠠ DNS Server DNS ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ Search Domain ᠬᠠᠢᠬᠤ ᠬᠡᠰᠡᠭ Auto(DHCP) ᠠᠦ᠋ᠲ᠋ᠣ᠋ (DHCP) Manual ᠠᠦ᠋ᠲ᠋ᠣ᠋ ᠪᠤᠰᠤ VpnListItem Not connected ᠴᠦᠷᠬᠡᠯᠡᠭᠡ ᠦᠬᠡᠢ Disconnect ᠳᠠᠰᠤᠯᠬᠤ Connect ᠴᠦᠷᠬᠡᠯᠡᠬᠦ VpnPage VPN vpn VPN Settings VPN ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ vpnAddPage create VPN VPN ᠪᠠᠢᠭᠤᠯᠬᠤ VPN Type VPN ᠳᠦᠷᠦᠯ ᠵᠦᠢᠯ VPN Name VPN ᠨᠡᠷᠡᠢᠳᠦᠯ Required ᠡᠷᠬᠡᠪᠰᠢ ᠳᠠᠭᠯᠠᠬᠤ VPN Server ᠦᠢᠯᠡᠴᠢᠯᠡᠬᠦᠷ ᠤ᠋ᠨ ᠬᠠᠶᠢᠭ VPN vpn Auto Connection ᠠᠦ᠋ᠲ᠋ᠣ᠋ ᠴᠦᠷᠬᠡᠯᠡᠬᠦ Confirm ᠪᠠᠳᠤᠯᠠᠬᠤ Cancel ᠦᠬᠡᠢᠰᠬᠡᠬᠦ vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool vpn ᠪᠠᠭᠠᠵᠢ kylin-nm/src-vpn/translations/kylin-vpn_vi.ts0000664000175000017500000010661115167651420020360 0ustar fengfeng SinglePage Settings Mục cài đặt Kylin VPN Kylin VPN kylin vpn applet desktop message Thông báo trên màn hình nền của VPN Kylin VpnAdvancedPage MPPE encryption algorithm: Thuật toán mã hóa MPPE: Use Stateful encryption Sử dụng mã hóa trạng thái Send PPP echo packets Gửi gói tin PPP echo Authentication Mode: Chế độ xác thực: PAP authentication Xác thực PAP CHAP authentication Xác thực CHAP MSCHAP authentication Xác thực MSCHAP MSCHAP2 authentication Xác thực MSCHAP2 EAP authentication Xác thực EAP Compression Mode: Phương thức nén: Allow BSD data compression Cho phép nén dữ liệu BSD Allow Default data compression Cho phép nén dữ liệu mặc định Allow TCP header compression Cho phép nén tiêu đề TCP Use protocol field compression negotiation Sử dụng đàm phán nén trường giao thức Use Address/Control compression Sử dụng địa chỉ/điều khiển nén All Available Tùy ý 128-bit 128 bit 40-bit 40 bit Use custom gateway port Sử dụng cổng gateway tùy chỉnh Use compression Sử dụng nén Use a TCP connection Sử dụng kết nối TCP Set virtual device type Đặt loại thiết bị ảo Set virtual device name Đặt tên thiết bị ảo Limit TCP Maximum Segment Size(MSS) Giới hạn kích thước phân đoạn TCP tối đa (MSS) Randomize remote hosts Ngẫu nhiên hóa máy chủ từ xa IPv6 tun link Kết nối IPv6 tun Specify ping interval Chỉ định khoảng thời gian ping Specify exit or restart ping Chỉ định ping thoát hoặc khởi động lại Specify max routes Chỉ định số route tối đa Infinite retry on error Thử lại vô hạn khi lỗi Use custom key size Sử dụng kích thước khóa tùy chỉnh Choose Chọn Use custom renegotiation interval Sử dụng khoảng thời gian đàm phán lại tùy chỉnh Use custom tunnel Maximum Transmission Umit(MTU) Sử dụng đơn vị truyền tối đa (MTU) đường hầm tùy chỉnh Use custom UDP fragment size Sử dụng kích thước phân mảnh UDP tùy chỉnh Accept authenticated packets from any address (Float) Chấp nhận các gói được xác thực từ bất kỳ địa chỉ nào (Float) Subject Match Khớp chủ đề Key File Tập tin chính Key Direction Hướng chính Server Address Địa chỉ máy chủ Port Cổng Proxy USername Proxy USername Proxy Password Mật khẩu Proxy General Tổng quát TLS settings Cài đặt TLS Server Certificate Check Kiểm tra chứng chỉ máy chủ Use the previous authentication end (server) certificate Sử dụng chứng chỉ kết thúc xác thực (máy chủ) trước đó Verify peer (server) certificate nsCertType specification Xác thực chứng chỉ peer (máy chủ) theo nsCertType chỉ định Mode Chế độ Proxies Proxy Proxy Type Loại proxy Security An ninh HMAC Authentication Xác thực HMAC Input content Nội dung nhập No Không Self-adaption Tự thích nghi Automatic Tự động Exit Thoát Restart Khởi động lại Don't verify certificate identification Không xác thực định danh chứng chỉ Verify the entire subject exactly Xác thực toàn bộ chủ đề chính xác Verify name exactly Xác minh tên chính xác Verify name by prefix Xác thực tên theo tiền tố Server Địa chỉ máy chủ Client Khách hàng None Không ai TLS-Certification Chứng nhận TLS TLS-Encryption TLS-Mã hóa Not Required Không yêu cầu Default Mặc định Options: Tùy chọn: Request an inner IP address Yêu cầu địa chỉ IP bên trong Enforce UDP encapsulation Bắt buộc đóng gói UDP Use IP compression Sử dụng nén IP Enable custom password suggestions Bật đề xuất mật khẩu tùy chỉnh Choose a private key Chọn khóa riêng tư Key Files (*.key *.pem *.der *.p12 *.pfx) Tệp khóa (*.key *.pem *.der *.p12 *.pfx) VpnConfigPage Type Kiểu Name Tên card âm thanh Static Key Phím tĩnh Local IP IP cục bộ Remote IP IP từ xa PIN Code Mã PIN Password Mật khẩu NT Domain Miền NT Server Address Địa chỉ máy chủ Authentication Mode Phương thức xác thực CA Certificate Chứng chỉ CA User Certificate Chứng chỉ người dùng Key Direction Hướng khóa Private Key Khóa riêng Private Key Password Mật khẩu khóa riêng tư Password Options Tùy chọn mật khẩu Username Tên người dùng Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. Thông báo: Nếu hướng phím được sử dụng, nó phải ngược lại với phía VPN được sử dụng. Nếu '1' được sử dụng, kết nối phải sử dụng '0'. Nếu bạn không chắc chắn nên sử dụng giá trị nào, vui lòng liên hệ với quản trị viên hệ thống của bạn. Choose Chọn None Không ai Save password only for this user Chỉ lưu mật khẩu cho người dùng hiện tại Save password for all users Lưu mật khẩu cho tất cả người dùng Ask password every time Hỏi mỗi lần Don't require a password Không yêu cầu mật khẩu Required Bắt buộc điền Certificate(TLS) Chứng chỉ (TLS) Static key Phím tĩnh Password and certificate(TLS) Mật khẩu và chứng chỉ (TLS) Certificate/Private key Chứng chỉ/Khóa riêng Certificate/ssh-agent Chứng chỉ/ssh-agent Smart card Thẻ thông minh Choose a private key Chọn khóa riêng tư Key Files (*.key *.pem *.der *.p12 *.pfx) Các tệp chính (*.key *.pem *.der *.p12 *.pfx) Choose a CA certificate Chọn chứng chỉ CA CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Tệp CA (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate Chọn chứng chỉ người dùng Choose a Static key Chọn khóa tĩnh VpnDetail VPN IPv4 IPv6 Advanced Chế độ cao cấp Auto Connection Tự động kết nối Cancel Hủy Confirm Lưu sửa đổi VpnIpv4Page IPv4 Config Cấu hình IPv4 Address Địa chỉ Netmask Mặt nạ mạng Default Gateway Cổng mặc định DNS Server Máy chủ DNS Search Domain Miền tìm kiếm DHCP Client ID ID Client của DHCP Auto(DHCP) Tự động (DHCP) Manual Sách hướng dẫn VpnIpv6Page IPv6 Config Cấu hình IPv6 Address Địa chỉ Netmask Mặt nạ mạng Default Gateway Cổng mặc định DNS Server Máy chủ DNS Search Domain Tên miền tìm kiếm Auto(DHCP) Tự động (DHCP) Manual Cẩm nang VpnListItem Not connected Chưa kết nối Disconnect Ngắt kết nối Connect Kết nối VpnPage VPN VPN Settings Cài đặt VPN vpnAddPage create VPN Tạo VPN VPN Type Loại VPN VPN Name Tên VPN Required Bắt buộc điền VPN Server Địa chỉ máy chủ Auto Connection Kết nối tự động Confirm Lưu sửa đổi Cancel Hủy vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool Công cụ VPN kylin-nm/src-vpn/translations/kylin-vpn_tr.ts0000664000175000017500000010445615167651420020374 0ustar fengfeng SinglePage Settings Kylin VPN kylin vpn applet desktop message VpnAdvancedPage MPPE encryption algorithm: Use Stateful encryption Send PPP echo packets Authentication Mode: PAP authentication CHAP authentication MSCHAP authentication MSCHAP2 authentication EAP authentication Compression Mode: Allow BSD data compression Allow Default data compression Allow TCP header compression Use protocol field compression negotiation Use Address/Control compression All Available 128-bit 40-bit Use custom gateway port Use compression Use a TCP connection Set virtual device type Set virtual device name Limit TCP Maximum Segment Size(MSS) Randomize remote hosts IPv6 tun link Specify ping interval Specify exit or restart ping Specify max routes Infinite retry on error Use custom key size Choose Use custom renegotiation interval Use custom tunnel Maximum Transmission Umit(MTU) Use custom UDP fragment size Accept authenticated packets from any address (Float) Subject Match Key File Key Direction Server Address Port Proxy USername Proxy Password General TLS settings Server Certificate Check Use the previous authentication end (server) certificate Verify peer (server) certificate nsCertType specification Mode Proxies Proxy Type Security HMAC Authentication Input content No Self-adaption Automatic Exit Restart Don't verify certificate identification Verify the entire subject exactly Verify name exactly Verify name by prefix Server Client None TLS-Certification TLS-Encryption Not Required Default Options: Request an inner IP address Enforce UDP encapsulation Use IP compression Enable custom password suggestions Choose a private key Key Files (*.key *.pem *.der *.p12 *.pfx) VpnConfigPage Type Name Static Key Local IP Remote IP PIN Code Password NT Domain Server Address Authentication Mode CA Certificate User Certificate Key Direction Private Key Private Key Password Password Options Username Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. Choose None Save password only for this user Save password for all users Ask password every time Don't require a password Required Certificate(TLS) Static key Password and certificate(TLS) Certificate/Private key Certificate/ssh-agent Smart card Choose a private key Key Files (*.key *.pem *.der *.p12 *.pfx) Choose a CA certificate CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate Choose a Static key VpnDetail VPN IPv4 IPv6 Advanced Auto Connection Cancel Confirm VpnIpv4Page IPv4 Config Address Netmask Default Gateway DNS Server Search Domain DHCP Client ID Auto(DHCP) Manual VpnIpv6Page IPv6 Config Address Netmask Default Gateway DNS Server Search Domain Auto(DHCP) Manual VpnListItem Not connected Disconnect Connect VpnPage VPN VPN Settings vpnAddPage create VPN VPN Type VPN类型 VPN Name Required VPN Server Auto Connection Confirm Cancel vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool kylin-nm/src-vpn/translations/kylin-vpn_kk.ts0000664000175000017500000011312615167651420020346 0ustar fengfeng SinglePage Settings تور تەڭگەرگٸش Kylin VPN اسباپبٸVPN kylin vpn applet desktop message VPNتەڭگەرگٸشتٸ ۇستەل بەتىندە كورسەتۋ VpnAdvancedPage MPPE encryption algorithm: MPPE سيفىرلاستىرۋ ەسەپتەۋگە ٴتاسٸلٸ: Use Stateful encryption ٸستەتۋ كۇيى سيفرلاسقان Send PPP echo packets pppقايتپ كورسەتۋ سومكاسىنا جولداۋ Authentication Mode: دالەلدەۋ پىشىنى: PAP authentication PAP دالەلدەۋ CHAP authentication CHAP دالەلدەۋ MSCHAP authentication MSCHAP دالەلدەۋ MSCHAP2 authentication MSCHAP2 دالەلدەۋ EAP authentication EAP دالەلدەۋ Compression Mode: پىرېسلاش كۇيى: Allow BSD data compression BSD نى پېرىسلاشقا جول قويۋ Allow Default data compression Defaultنى پېرىسلاشقا جول قويۋ Allow TCP header compression TCP نى پېرىسلاشقا جول قويۋ Use protocol field compression negotiation ٸستەتۋ كەلىسىمى ساباعىنداعى پىرېسلاش كەلىسىمى Use Address/Control compression ٵدىرىس/كونتروللاپ پېرىسلاشنى ٸستەتۋ All Available بارلٸق بارلار 128-bit 128 بەتالىق 40-bit 40 بەتالىق Use custom gateway port انٸقتاما بەرۋ تور وتكەلى اۋزىن ٸستەتۋ Use compression پېرىسلاپ ٸستەتۋ Use a TCP connection TCP اۋلاۋ تاسٸلدٸ قولدانۋ Set virtual device type جاساندى اسباب تيبىن بەلگٸلەۋ Set virtual device name جاساندى اسباب اتاعىن بەلگٸلەۋ Limit TCP Maximum Segment Size(MSS) TCP ەڭ ۇلكەن بولٸك ۇلكەنلۇقىنى شەكتەۋ(MSS) Randomize remote hosts ەركىن كۇيدە باس اپپاراتىن جىراقتان مەڭگەرۋ ەتۋ IPv6 tun link IPv6 tunاۋلاۋ Specify ping interval pingدەۋرىيلىكىنى بەلگٸلەۋ Specify exit or restart ping شەگىنۋ ياكي قاتە قوزعالعان ping نى كورسەتىپ بەرۋ Specify max routes شەكتى لەنيانى كورسەتىپ بەرۋ Infinite retry on error قاتەلىك شىققاندا باساسٸز كۇيدە قاتە قايتالاۋ Use custom key size انٸقتاما بەرٸلگەن قۇپيا كىلت ۇلكەن كىشكەنەلىگىن ٸستەتۋ Choose تالداۋ Use custom renegotiation interval ٶز الدىنا قاتە سۇحباتتاسۋ ارالىعىن ٸستەتۋ Use custom tunnel Maximum Transmission Umit(MTU) ەرەكشە تۇنەلدىڭ ەڭ ۇلكەن جولدانبا ۇزاتۋ مۇئەسسەسەسى(MTU) نى ٸستەتۋ Use custom UDP fragment size انٸقتاما بەرٸلگەن UDP پارشالاۋ ۇلكەندىگىن ٸستەتۋ Accept authenticated packets from any address (Float) ٴارقانداي ٵدىرىس قابىلداۋ ەتۋ ( Float ) ازاماتتىق تەكسەرۋ ارقىلى ساندىق مالىمەت بوقشاسٸ Subject Match باس تاقٸرٸبٸن سايكەستىرۋ Key File شەشۋشٸ حۇجات Key Direction شەشۋشٸ باعىت Server Address قىزىمەت وتەۋى ٵدىرىسى Port اۋٸزٸ Proxy USername ۋاكىلەتىنەن ابونت مى Proxy Password ۋاكىلەتىنەن قۇپيا نومەر General ادەتتەگٸ تارتىپ TLS settings TLS تەڭشەۋلەرى Server Certificate Check قىزىمەت وتەۋى كنەشكاسن تەكسەرۋ Use the previous authentication end (server) certificate بۇرٸنعٸ دالەلدەۋ سوڭىن (قىزىمەت وتەۋى) كنەشكاسن ٸستەتۋ Verify peer (server) certificate nsCertType specification تەڭ نۇكتە (قىزىمەت وتەۋى) كناشكاسى nsCertType نىڭ كونكرېتلىقىنى دالەلدەۋ Mode فورٸم Proxies ۋاكىلەتىنەن Proxy Type ۋاكىلەتىنەن تۇرى Security حاۋىپسىزدىك HMAC Authentication HMAC دالەلدەۋ Input content مازمۇن كىرگىزۋ No جوق Self-adaption ٶز-ٶزىگە سايكەسۋ Automatic اۆتوماتتى Exit شىعۋ اۋٸزٸ Restart قاتە قوزعالتۋ Don't verify certificate identification كناشكا ازاماتتىق دالەلدەۋدى ئىسپاتلىماڭ Verify the entire subject exactly پۇتٸن تاقٸرٸبٸن شٸنٸندا انىقتاۋ Verify name exactly اتاعىن انىقتاپ دالەلدەۋ Verify name by prefix اتاعىن الدى قوسىلما بويىنشا دالەلدەۋ Server قىزىمەت وتەۋى Client جيۋ None جوق TLS-Certification TLS-دالەلدەۋ TLS-Encryption TLS-سيفىرلاستىرۋ Not Required تالاپ ورىندالمايدى Default وز قالپٸ Options: تالدانبالار: Request an inner IP address ٸشكٸ IP ٵدىرىسى جابلماس ەتۋ Enforce UDP encapsulation UDP قاپتاۋدى اتقار ەتۋ Use IP compression IP پىرېسلاش ٸستەتۋ Enable custom password suggestions ٶزى بەلگىلەەن قۇپيا نومەر قوزعالتۋ ۇسنستى Choose a private key جەكە كىلت تالداۋ Key Files (*.key *.pem *.der *.p12 *.pfx) شەشۋشٸ حۇجاتتار (*.key *.pem *.der *.p12 *.pfx) VpnConfigPage Type تۇرى Name ات-فاميليا Static Key تىنىش كۇيدەگى قۇپيا كىلت Local IP جەرلىك ٵدىرىسIP Remote IP جىراقتان مەڭگەرۋ ىستەيتىن ٵدىرىسIP PIN Code PIN بەلگىسى Password قۇپيا كىلت NT Domain NT كولەم Server Address قىزىمەت وتەۋى ٵدىرىسى Authentication Mode دالەلدەۋ فورماسى CA Certificate CA كناشكاسى User Certificate پايدالانۋشٸ كناشكاسى Key Direction شەشۋشٸ باعىت Private Key جەكە كىلت Private Key Password جەكە كىلت پارولى Password Options پارول تالدانبالارٸ Username ابونت مى Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. ديقات:قيسٸق قۇپيا كىلت باعىتتالۋى ٸستەتكەن بولسا، ول ٴسوزسٸز ٸستەتكەن VPN ولچى مەنەن قاراما﹣قارسى بولۋٸ كەرەك. قيسٸق «1» نى ٸستەتكەن بولسا، وللاشتا ٴسوزسٸز «0» نى ٸستەتۋ كەرەك. قيسٸق قايسى مانىن ٸستەتۋنى جەزملەشتۈرەلمىسىڭىز سەستيما باسقارۋشٸسٸ مەنەن حابارلاسٸڭٸز. Choose تالداۋ None جوق Save password only for this user تەك كەزەكتەگى ابونت قۇپيا نومەر ساقتاۋ Save password for all users بارلٸق ابونتتار ٷشٸن قۇپيا نومەر ساقتاۋ Ask password every time ٵر رەت قۇپيا نومەر سۇراۋ Don't require a password قۇپيا نومەر تالاپ ورىنداماستىق Required ٴسوزسىز تولدٸرعٸش Certificate(TLS) كناشكا(TLS) Static key تىنىش كۇيدەگى كىلت Password and certificate(TLS) قۇپيا نومەر ۋا كناشكا(TLS) Certificate/Private key كناشكا/قاسيەت كىلت Certificate/ssh-agent كناشكا/ ssh-agent Smart card وي قابٸلەتتٸ قاريتا Choose a private key جەكە كىلت تالداۋ Key Files (*.key *.pem *.der *.p12 *.pfx) شەشۋشٸ حۇجاتتار (*.key *.pem *.der *.p12 *.pfx) Choose a CA certificate CA كناشكاسى تالداۋ CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA حۇجاتتارى (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate پايدالانۋشٸ كناشكاسى تالداۋ Choose a Static key تىنىش كۇيدەگى كىلت تالداۋ VpnDetail VPN IPv4 IPv6 Advanced جوعارعى دارەجە بۇلۋ Auto Connection اۆتوماتتى اۋلاۋ Cancel كۇشىنەن قالدىرۋ Confirm تۇراقتاندىرۋ VpnIpv4Page IPv4 Config IPv4 تەڭگەرگٸش Address ٵدىرىس Netmask تارماق تور جاسىرىن نومەرى Default Gateway وز قالپٸ تور وتكەلى DNS Server DNS قىزىمەت وتەۋ تۇرلەرى Search Domain تور اتاعىن ٸزدەۋ DHCP Client ID DHCP جيۋ IDسى Auto(DHCP) اۆتوماتتى(DHCP) Manual قولدانبا VpnIpv6Page IPv6 Config IPv6 تەڭگەرگٸش Address ٵدىرىس Netmask تارماق تور جاسىرىن نومەرى Default Gateway وز قالپٸ تور وتكەلى DNS Server DNS قىزىمەت وتەۋ تۇرلەرى Search Domain تور اتاعىن ٸزدەۋ Auto(DHCP) اۆتوماتتى(DHCP) Manual قولدانبا VpnListItem Not connected جالعانباعان Disconnect ۇزارتىۋ Connect جالعانۋ VpnPage VPN VPN Settings VPN تەڭشەۋلەرى vpnAddPage create VPN VPN قۇرۋ VPN Type VPN تۇرى VPN Name VPN مى Required ٴسوزسىز تولدٸرعٸش VPN Server VPN قىزىمەت وتەۋ تۇرلەرى Auto Connection اۆتوماتتى اۋلاۋ Confirm تۇراقتاندىرۋ Cancel كۇشىنەن قالدىرۋ vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool vpn قۇرالى kylin-nm/src-vpn/translations/kylin-vpn_de.ts0000664000175000017500000010632315167651420020332 0ustar fengfeng SinglePage Settings Einstellungen Kylin VPN Kylin VPN kylin vpn applet desktop message Kylin VPN-Applet-Desktop-Nachricht VpnAdvancedPage MPPE encryption algorithm: MPPE-Verschlüsselungsalgorithmus: Use Stateful encryption Zustandsbehaftete Verschlüsselung verwenden Send PPP echo packets PPP-Echo-Pakete senden Authentication Mode: Authentifizierungsmodus: PAP authentication PAP-Authentifizierung CHAP authentication CHAP-Authentifizierung MSCHAP authentication MSCHAP-Authentifizierung MSCHAP2 authentication MSCHAP2 Authentifizierung EAP authentication EAP-Authentifizierung Compression Mode: Komprimierungs-Modus: Allow BSD data compression BSD-Datenkomprimierung zulassen Allow Default data compression Standard-Datenkomprimierung zulassen Allow TCP header compression TCP-Header-Komprimierung zulassen Use protocol field compression negotiation Verwenden der Protokollfeldkomprimierungsaushandlung Use Address/Control compression Adress-/Steuerungskomprimierung verwenden All Available Alle verfügbaren 128-bit 128-Bit 40-bit 40-Bit Use custom gateway port Verwenden eines benutzerdefinierten Gateway-Ports Use compression Verwenden der Komprimierung Use a TCP connection Verwenden einer TCP-Verbindung Set virtual device type Festlegen des virtuellen Gerätetyps Set virtual device name Festlegen des Namens des virtuellen Geräts Limit TCP Maximum Segment Size(MSS) Maximale TCP-Segmentgröße begrenzen (MSS) Randomize remote hosts Randomisierung von Remote-Hosts IPv6 tun link IPv6-Verbindung Specify ping interval Ping-Intervall angeben Specify exit or restart ping Beenden oder Neustarten des Pings angeben Specify max routes Angeben von max. Routen Infinite retry on error Unendliche Wiederholung bei Fehler Use custom key size Benutzerdefinierte Schlüsselgröße verwenden Choose Wählen Use custom renegotiation interval Benutzerdefiniertes Neuverhandlungsintervall verwenden Use custom tunnel Maximum Transmission Umit(MTU) Benutzerdefinierte maximale Übertragungsumit (MTU) des Tunnels verwenden Use custom UDP fragment size Benutzerdefinierte UDP-Fragmentgröße verwenden Accept authenticated packets from any address (Float) Akzeptieren Sie authentifizierte Pakete von einer beliebigen Adresse (Float) Subject Match Betreff-Übereinstimmung Key File Schlüssel-Datei Key Direction Wichtige Richtung Server Address Server-Adresse Port Hafen Proxy USername Proxy USername Proxy Password Proxy-Passwort General Allgemein TLS settings TLS-Einstellungen Server Certificate Check Überprüfung des Serverzertifikats Use the previous authentication end (server) certificate Verwenden Sie das vorherige Authentifizierungsendzertifikat (Serverzertifikat) Verify peer (server) certificate nsCertType specification Überprüfen der nsCertType-Spezifikation des Peerzertifikats (Serverzertifikats) Mode Modus Proxies Vertretungen Proxy Type Proxy-Typ Security Sicherheit HMAC Authentication HMAC-Authentifizierung Input content Inhalt eingeben No Nein Self-adaption Selbstanpassung Automatic Automatisch Exit Ausgang Restart Neustarten Don't verify certificate identification Zertifikatsidentifikation nicht überprüfen Verify the entire subject exactly Verifizieren Sie den gesamten Betreff genau Verify name exactly Den Namen genau verifizieren Verify name by prefix Überprüfen des Namens anhand des Präfixes Server Server Client Kunde None Nichts TLS-Certification TLS-Zertifizierung TLS-Encryption TLS-Verschlüsselung Not Required Nicht erforderlich Default Vorgabe Options: Optionen: Request an inner IP address Anfordern einer inneren IP-Adresse Enforce UDP encapsulation Erzwingen der UDP-Kapselung Use IP compression IP-Komprimierung verwenden Enable custom password suggestions Benutzerdefinierte Passwortvorschläge aktivieren Choose a private key Wählen Sie einen privaten Schlüssel aus Key Files (*.key *.pem *.der *.p12 *.pfx) Schlüsseldateien (*.key, *.pem, *.der, *.p12, *.pfx) VpnConfigPage Type Art Name Name Static Key Statischer Schlüssel Local IP Lokale IP-Adresse Remote IP Remote-IP PIN Code PIN-Code Password Passwort NT Domain NT-Domäne Server Address Server-Adresse Authentication Mode Authentifizierungsmodus CA Certificate CA-Zertifikat User Certificate Benutzer-Zertifikat Key Direction Wichtige Richtung Private Key Privater Schlüssel Private Key Password Passwort für den privaten Schlüssel Password Options Passwort-Optionen Username Nutzername Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. Bemerken: Wenn die Schlüsselrichtung verwendet wird, muss sie der verwendeten VPN-Seite entgegengesetzt sein. Wenn '1' verwendet wird, muss die Verbindung '0' verwenden. Wenn Sie sich nicht sicher sind, welchen Wert Sie verwenden sollen, wenden Sie sich bitte an Ihren Systemadministrator. Choose Wählen None Nichts Save password only for this user Passwort nur für diesen Benutzer speichern Save password for all users Passwort für alle Benutzer speichern Ask password every time Jedes Mal nach dem Passwort fragen Don't require a password Kein Passwort erforderlich Required Erforderlich Certificate(TLS) Zertifikat (TLS) Static key Statischer Schlüssel Password and certificate(TLS) Passwort und Zertifikat (TLS) Certificate/Private key Zertifikat/Privater Schlüssel Certificate/ssh-agent Zertifikat/SSH-Agent Smart card Chipkarte Choose a private key Wählen Sie einen privaten Schlüssel aus Key Files (*.key *.pem *.der *.p12 *.pfx) Schlüsseldateien (*.key, *.pem, *.der, *.p12, *.pfx) Choose a CA certificate Auswählen eines CA-Zertifikats CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA-Dateien (*.pem, *.der, *.p12, *.crt, *.cer, *.pfx) Choose a User certificate Auswählen eines Benutzerzertifikats Choose a Static key Auswählen eines statischen Schlüssels VpnDetail VPN IPv4 IPv6 Advanced Fortgeschritten Auto Connection Automatische Verbindung Cancel Abbrechen Confirm Bestätigen VpnIpv4Page IPv4 Config IPv4-Konfiguration Address Adresse Netmask Netzmaske Default Gateway Standardgateway DNS Server DNS-Server Search Domain Domain suchen DHCP Client ID DHCP-Client-ID Auto(DHCP) Auto (DHCP) Manual Manuell VpnIpv6Page IPv6 Config IPv6-Konfiguration Address Adresse Netmask Netzmaske Default Gateway Standardgateway DNS Server DNS-Server Search Domain Domain suchen Auto(DHCP) Auto (DHCP) Manual Manuell VpnListItem Not connected Nicht verbunden Disconnect Trennen Connect Verbinden VpnPage VPN VPN Settings VPN-Einstellungen vpnAddPage create VPN VPN erstellen VPN Type VPN-Typ VPN Name VPN-Name Required Erforderlich VPN Server VPN-Server Auto Connection Automatische Verbindung Confirm Bestätigen Cancel Abbrechen vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool VPN-Tool kylin-nm/src-vpn/translations/kylin-vpn_bo_CN.ts0000664000175000017500000012644715167651420020733 0ustar fengfeng SinglePage Settings བཀོད་སྒྲིག་བཅས་བྱ་དགོས། Kylin VPN VPNཡོ་བྱད། kylin vpn applet desktop message vpnཅོག་ངོས་ཀྱི་གསལ་འདེབས་བཀོད་སྒྲིག་བྱེད་པ། VpnAdvancedPage MPPE encryption algorithm: MPPEགསང་སྣོན་རྩིས་ཐབས།: Use Stateful encryption རྣམ་པ་ལྡན་པའི་སྒོ་ནས་ཚགས་དམ་དུ་གཏོང་བ། Send PPP echo packets སྐྱེལ་སྤྲོད་བྱེད་དགོས།PPPཁུག་མ་ཕྱིར་མངོན་པ། Authentication Mode: བདེན་དཔང་ར་སྤྲོད་བྱེད་སྟངས།: PAP authentication PAPདཔང་དངོས་བདེན་པ་ཡིན་པའི CHAP authentication CHAPདཔང་དངོས་བདེན་པ་ཡིན་པའི MSCHAP authentication MSCHAPདཔང་དངོས་བདེན་པ་ཡིན་པའི MSCHAP2 authentication MSCHAP2དཔང་དངོས་བདེན་པ་ཡིན་པའི EAP authentication EAPདཔང་དངོས་བདེན་པ་ཡིན་པའི Compression Mode: ཉུང་འཕྲི་བྱེད་སྟངས།: Allow BSD data compression ཆོག་པ་བྱ་དགོས།BSDཉུང་འཕྲི་བཅས་བྱ་ Allow Default data compression ཆོག་པ་བྱ་དགོས།Defaultཉུང་འཕྲི་བཅས་བྱ་ Allow TCP header compression ཆོག་པ་བྱ་དགོས།TCPམགོ་བོ།ཉུང་འཕྲི་བཅས་བྱ་ Use protocol field compression negotiation གྲོས་མཐུན་གྱི་ཁྱབ་ཁོངས་སྤྱད་དེ་གྲོས་མོལ་ཉུང་འཕྲ Use Address/Control compression ས་གནས་སྤྱོད་པ།/ཉུང་འཕྲི་ཚོད་འཛིན་ All Available རང་སྣང་གང་དྲན་བྱེད་པ 128-bit 128གནས་ས། 40-bit 40གནས་ས། Use custom gateway port རང་ཉིད་ཀྱི་མཚན་ཉིད་འཇོག་པའི་དྲ་བའི་འགག་སྒོ་བེད་སྤྱོད་བྱ་དགོས Use compression བཀོལ་སྤྱོད་ཉུང་འཕྲི་ Use a TCP connection བེད་སྤྱོད།TCPའབྲེལ་མཐུད་བཅས་བྱ་དགོས། Set virtual device type རྟོག་བཟོའི་སྒྲིག་ཆས་ཀྱི་རིགས་བཟོ་བ། Set virtual device name རྟོག་བཟོའི་སྒྲིག་ཆས་ཀྱི་མིང་བཟོ་བ། Limit TCP Maximum Segment Size(MSS) ཚོད་འཛིན།TCPཆེས་ཆེ་བའི་རིང་ཐུང་།(MSS) Randomize remote hosts སྐབས་བསྟུན་ཅན་གྱི་རྒྱང་ཁྲིད་འཕྲུལ་ཆས་གཙོ་བོ། IPv6 tun link IPv6 tunའབྲེལ་མཐུད་བཅས་བྱ་དགོས། Specify ping interval དམིགས་འཛུགས་བྱས་པ།Pingདུས་འཁོར། Specify exit or restart ping ཕྱིར་འཐེན་ནམ་ཡང་ན་བསྐྱར་དུ་སྒོ་འབྱེད་རྒྱུའི་དམིགས་འཛུགས་བྱས་རིགས།Ping Specify max routes དམིགས་འཛུགས་བྱེད་པའི་ལམ་དེ་གོང་ནས་ཚད་བཀག་དགོས། Infinite retry on error ནོར་འཁྲུལ་བྱུང་དུས་ཚོད་ལྟ་ཚད་མེད་བྱེད་དགོས། Use custom key size རང་གི་མཚན་ཉིད་ཀྱི་གསང་བའི་ལྡེ་མིག་ཆེ་ཆུང་སྤྱོད་པ། Choose གདམ་ག་རྒྱག་པ། Use custom renegotiation interval རང་ཉིད་ཀྱི་མཚན་ཉིད་བཞག་ནས་གྲོས་མོལ་བྱེད་པའི་བར་མཚམས་འཇོག་དགོས Use custom tunnel Maximum Transmission Umit(MTU) རང་ཉིད་ཀྱི་མཚན་ཉིད་བཞག་པའི་ཕུག་ལམ་གྱི་ཆེས་ཆེ་བའི་ཚན་པ་བརྒྱུད་གཏོང་བྱེད་པ།(MTU) Use custom UDP fragment size རང་ཉིད་ཀྱི་མཚན་ཉིད་སྤྱད་པ།UDPཆ་བགོས་ཆེ་ཆུང་། Accept authenticated packets from any address (Float) ས་གནས་གང་ནས་ཡོང་བ་དང་ལེན་བྱེད་དགོས།(Float)ཐོབ་ཐང་ཚོད་ལྟསར་སྤྲོད་བྱས་ཟིན་པའི་གྲངས་གཞིའི་ཁུག་མ། Subject Match བརྗོད་བྱ་གཙོ་བོ་ཆ་འགྲིག་པ། Key File གསང་ལྡེའི་ཡིག་ཆ། Key Direction གསང་ལྡེའི་ཁ་ཕྱོགས། Server Address ཞབས་ཞུ་ཡོ་བྱད་ཀྱི་ས་གནས། Port ཁ་བཤད་པ། Proxy USername བེད་སྤྱོད་བྱེད་མཁན་གྱི་ཚབ་ཏུ་མིང་། Proxy Password གསང་གྲངས་ཚབ་སྒྲུབ་བྱེད་པ། General རྒྱུན་སྲོལ། TLS settings TLSབཀོད་སྒྲིག་བཅས་བྱ་དགོས། Server Certificate Check ཞབས་ཞུ་ཡོ་བྱད་དཔང་ཡིག་ལ་ཞིབ་བཤེར་བྱ་དགོས། Use the previous authentication end (server) certificate གོང་དུ་ཚོད་ལྟས་ར་སྤྲོད་བྱ་དགོས།(ཞབས་ཞུའི་ཡོ་བྱད།)དཔང་ཡིག Verify peer (server) certificate nsCertType specification ཚོད་ལྟས་ར་སྤྲོད་བྱེད་པ་སོགས་ཡིན།(ཞབས་ཞུའི་ཡོ་བྱད།)དཔང་ཡིགnsCertTypeདམིགས་འཛུགས་བྱས་པ། Mode མ་དཔེ། Proxies ངོ་ཚབ་ Proxy Type ངོ་ཚབ་ཀྱི་རིགས་དབྱིབས། Security བདེ་འཇགས། HMAC Authentication HMACདཔང་དངོས་བདེན་པ་ཡིན་པའི Input content ནང་དོན་ནང་འཇུག་བྱེད་པ། No དེ་ལྟར་མ་བྱས་ Self-adaption རང་གིས་རང་ལ་འཕྲོད་པར Automatic རང་འགུལ་ཡིན་དགོས། Exit ཕྱིར་འཐེན་བྱ་དགོས། Restart བསྐྱར་དུ་སྒོ་འབྱེད་དགོས། Don't verify certificate identification དཔང་ཡིག་གི་མཚོན་རྟགས་ལ་ཚོད་ལྟས་ར་སྤྲོད་མི་བྱེད། Verify the entire subject exactly བརྗོད་བྱ་གཙོ་བོ་ཡོངས་རྫོགས་ལ་ཚོད་ལྟས་ར་སྤྲོད་གསལ་པོ་བྱས་ Verify name exactly ཞིབ་ཅིང་དག་པའི་སྒོ་ནས་ར་སྤྲོད་བྱས་པའི་མིང་། Verify name by prefix སྔོན་གྱི་缀ཚོད་ལྟས་ར་སྤྲོད་ཀྱི་མིང་ལྟར། Server ཞབས་ཞུའི་ཡོ་བྱད། Client ཚོང་འགྲུལ་པ་སྣེ་ལེན་བྱེད་པ། None མེད། TLS-Certification TLS-དཔང་དངོས་བདེན་པ་ཡིན་པའི TLS-Encryption TLS-ཚགས་དམ་དུ་གཏོང་བ། Not Required དགོས་མཁོ་མེད། Default ཁ་རོག་གེར་ཁས་ལེན Options: རྣམ་གྲངས་འདེམས་པ།: Request an inner IP address ནང་ཁུལ་ལ་རེ་ཞུ་བྱེད་པ།IPས་གནས། Enforce UDP encapsulation བཙན་ཤེད་ཀྱིས་བཙན་ཤེད་བྱེདUDPཐུམ་རྒྱག་པ། Use IP compression བེད་སྤྱོད།IPཉུང་འཕྲི་བཅས་བྱ་ Enable custom password suggestions རང་ཉིད་ཀྱི་མཚན་ཉིད་གསང་བའི་གྲོས་འགོ་འདོན་དགོས། Choose a private key སྒེར་གྱི་ལྡེ་མིག་འདེམས་པ། Key Files (*.key *.pem *.der *.p12 *.pfx) སྒེར་གྱི་ལྡེ་མིག་ཡིག་ཆ།(*.key *.pem *.der *.p12 *.pfx) VpnConfigPage Type རིགས་དབྱིབས། Name མིང་། Static Key ཁ་རོག་གེར་ལྡེ་མིག་ལྟ་བ Local IP ས་གནས་དེ་ག་རེད།IPས་གནས། Remote IP རྒྱང་རིང་།IPས་གནས། PIN Code PINཨང་གྲངས། Password གསང་བའི་ཨང་གྲངས། NT Domain NTས་ཁོངས། Server Address ཞབས་ཞུ་ཡོ་བྱད་ཀྱི་ས་གནས། Authentication Mode བདེན་དཔང་ར་སྤྲོད་བྱེད་སྟངས། CA Certificate CAདཔང་ཡིག User Certificate སྤྱོད་མཁན།དཔང་ཡིག Key Direction གསང་ལྡེའི་ཁ་ཕྱོགས། Private Key སྒེར་གྱི་ལྡེ་མིག Private Key Password སྒེར་ལ་གསང་བའི་གསང་བ་ཡོད། Password Options གསང་བའི་ཐོག་ནས་རྣམ་གྲངས་བདམས་པ། Username སྤྱོད་མཁན་གྱི་མིང་། Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. ཡིད་འཇོག་བྱ་དགོས་ གལ་ཏེ་གསང་བའི་ཁ་ཕྱོགས་སྤྱད་ན་ངེས་པར་དུ་VPNཡི་སྣེ་དང་ལྡོག་དགོས། གལ་ཏེ་"1"བེད་སྤྱོད་བྱས་ན་ངེས་པར་དུ་"0"བེད་སྤྱོད་གཏོང་དགོས། གལ་ཏེ་རིན་ཐང་གང་ཡིན་པ་མི་ཤེས་ན། ཁྱེད་ཀྱི་མ་ལག་དོ་དམ་པ་ལ་འབྲེལ་གཏུག་བྱེད་རོགས། Choose གདམ་ག་རྒྱག་པ། None མེད། Save password only for this user མིག་སྔར་སྤྱོད་མཁན་ཁོ་ནར་གསང་གྲངས་ཉར་ཚགས་བྱས་ཡོད། Save password for all users སྤྱོད་མཁན་ཚང་མར་གསང་གྲངས་ཉར་ཚགས་བྱས་ཡོད། Ask password every time ཚང་མར་འདྲི་རྩད་བྱེད་ཐེངས་རེ་ཡིན། Don't require a password གསང་བ་མི་དགོས། Required ངེས་པར་དུ་སྐོང་དགོས། Certificate(TLS) དཔང་ཡིག(TLS) Static key ཁ་རོག་གེར་ལྡེ་མིག་ལྟ་བ Password and certificate(TLS) གསང་བ་དང་དཔང་ཡིག(TLS) Certificate/Private key དཔང་ཡིག/སྒེར་གྱི་ལྡེ་མིག Certificate/ssh-agent དཔང་ཡིག/ssh-agent Smart card རིག་ནུས་བྱང་བུ། Choose a private key སྒེར་གྱི་ལྡེ་མིག་འདེམས་པ། Key Files (*.key *.pem *.der *.p12 *.pfx) སྒེར་གྱི་ལྡེ་མིག་ཡིག་ཆ།(*.key *.pem *.der *.p12 *.pfx) Choose a CA certificate གདམ་ག་རྒྱག་པ།CAདཔང་ཡིག CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CAཡིག་ཆ། (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate སྤྱོད་མཁན་གྱི་ལག་ཁྱེར་འདེམས་དགོས། Choose a Static key འཇམ་ཐིང་ཐིང་གི་ལྡེ་མིག་འདེམས་ VpnDetail VPN IPv4 IPv6 Advanced མཐོ་རིམ།མཐོ་རིམ་ Auto Connection རང་འགུལ་གྱིས་སྦྲེལ་མཐུད་བྱ་དགོས། Cancel མེད་པར་བཟོ་དགོས། Confirm གཏན་འཁེལ་བྱ། VpnIpv4Page IPv4 Config IPv4བཀོད་སྒྲིག་བཅས་བྱ་དགོས། Address ས་གནས། Netmask དྲ་བ་འགེབས་པ། Default Gateway དྲ་རྒྱའི་འགག་སྒོ་ཁས་ལེན་བྱེད་དགོས། DNS Server DNSཞབས་ཞུའི་ཡོ་བྱད། Search Domain ས་ཁོངས་འཚོལ་ཞིབ་བྱ། DHCP Client ID DHCPཚོང་འགྲུལ་པ་སྣེ་ལེན་བྱེད་པ།ID Auto(DHCP) རང་འགུལ་ཡིན་དགོས།(DHCP) Manual ལག་པ་འགུལ་དགོས། VpnIpv6Page IPv6 Config IPv6བཀོད་སྒྲིག་བཅས་བྱ་དགོས། Address ས་གནས། Netmask དྲ་བ་འགེབས་པ། Default Gateway དྲ་རྒྱའི་འགག་སྒོ་ཁས་ལེན་བྱེད་དགོས། DNS Server DNSཞབས་ཞུའི་ཡོ་བྱད། Search Domain ས་ཁོངས་འཚོལ་ཞིབ་བྱ། Auto(DHCP) རང་འགུལ་ཡིན་དགོས།(DHCP) Manual ལག་པ་འགུལ་དགོས། VpnListItem Not connected འབྲེལ་མཐུད་མ་བྱས་པ། Disconnect བར་མཚམས་ཆད་པ་རེད། Connect འབྲེལ་མཐུད་བཅས་བྱ་དགོས། VpnPage VPN VPN Settings VPNབཀོད་སྒྲིག་བཅས་བྱ་དགོས། vpnAddPage create VPN གསར་འཛུགས་བྱ་དགོས།VPN VPN Type VPNརིགས་དབྱིབས། VPN Name VPNམིང་། Required ངེས་པར་དུ་སྐོང་དགོས། VPN Server ཞབས་ཞུ་ཡོ་བྱད་ཀྱི་ས་གནས། Auto Connection རང་འགུལ་གྱིས་སྦྲེལ་མཐུད་བྱ་དགོས། Confirm གཏན་འཁེལ་བྱ། Cancel མེད་པར་བཟོ་དགོས། vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool VPNཡོ་བྱད། kylin-nm/src-vpn/translations/kylin-vpn_ky.ts0000664000175000017500000011411415167651420020362 0ustar fengfeng SinglePage Settings تور تەڭشەگى Kylin VPN اسپاپVPN kylin vpn applet desktop message VPNتەڭشەگىن شىرە بەتىندە كۅرسۅتۉۉ VpnAdvancedPage MPPE encryption algorithm: MPPE سىيفىرلوو ەسەپتۅۅ ارعاسى: Use Stateful encryption ىشتەتىش ابالى سىيفىرلاشقان Send PPP echo packets pppقايتۇۇ كۅرسۅتۉۉ بوقچوسۇنا جولدوو Authentication Mode: دالىلدۅ كەبەتەسى ، تۇرپاتى : PAP authentication PAP دالىلدۅ CHAP authentication CHAP دالىلدۅ MSCHAP authentication MSCHAP دالىلدۅ MSCHAP2 authentication MSCHAP2 دالىلدۅ EAP authentication EAP دالىلدۅ Compression Mode: پىرىستوو ابالى: Allow BSD data compression BSD نى پېرىسلاشقا جول قويۇش Allow Default data compression Defaultنى پېرىسلاشقا جول قويۇش Allow TCP header compression TCP نى پېرىسلاشقا جول قويۇش Use protocol field compression negotiation ىشتەتىش كەلىشىمى چۅلكۅمۉندۅگۉ پىرىستوو كەلىشىمى Use Address/Control compression دايىن وردۇ/كونتروللاپ پېرىسلاشنى ىشتەتىش All Available باردىق بارلار 128-bit 128 بىتتۉ 40-bit 40 بىتتۉ Use custom gateway port انىقتاما بەرۉۉ تور ۅتكۅلۉ ووزۇن ىشتەتىش Use compression پىرىستاپ ىشتەتىش Use a TCP connection TCP ۇلوو ىڭعايىن قولدونۇش Set virtual device type جورۇما شايمان تىبىن بەلگىلۅۅ Set virtual device name جورۇما شايمان اتاعىن بەلگىلۅۅ Limit TCP Maximum Segment Size(MSS) TCP ەڭ چوڭ بۅلۉك چوڭدۇعۇن چەكتۅۅ (MSS) Randomize remote hosts ۅز ەركىنچە ابالدا باش اپاراتتى ىرااقتان تىزگىندۅۅ جاسوو ،اتقارۇۇ IPv6 tun link IPv6 tunۇلوو Specify ping interval pingدەۋرىيلىكىنى بەلگىلۅۅ Specify exit or restart ping جانىش ، قايتىش كۅرۉنۉشتۅرۉ قايرا قوزعولعون ping نى كۅرسۅتۉپ بەرۉۉ Specify max routes چەكتۉۉ لىنىيانى كۅرسۅتۉپ بەرۉۉ Infinite retry on error قاتاالىق چىققاندا چەكسىز ابالدا قايرا قايتالوو Use custom key size انىقتاما بەرىلگەن جاشىرۇۇن اچقىچ چوڭ كىچىكتىگىن ىشتەتىش Choose تانداش Use custom renegotiation interval ۅز الدىنا قايرا سۆھبەتلىشىش ارالىعىن ىشتەتىش Use custom tunnel Maximum Transmission Umit(MTU) قاسىيەت تونەلىنىن ەڭ چوڭ جولدونمو ۇزاتىش مۇئەسسەسەسى(MTU) نى ىشتەتىش Use custom UDP fragment size انىقتاما بەرىلگەن UDP مايدالاش چوڭدۇعۇن ىشتەتىش Accept authenticated packets from any address (Float) ارقانداي دايىن وردۇ قابىلدوو جاسوو ،اتقارۇۇ ( Float ) اتۇۇلدۇق تەكشەرىش ارقىلۇۇ ساندۇۇ بايانداما بوقچوسۇ Subject Match باش سىيۇجەتتى شايكەشتىرىپ Key File تۉيۉندۉۉ ۅجۅت Key Direction تۉيۉندۉۉ باعىت Server Address مۇلازىمەتىر دايىن وردۇ Port ووزۇ Proxy USername ۋاكالەتەن كەرەكتۅۅچۉ ناامى Proxy Password ۋاكالەتەن جاشىرۇۇن نومۇر General اداتتاعى ەرەجە TLS settings TLS تەڭشەكتەرى Server Certificate Check مۇلازىمەتىر كەنشكەسىن تەكشەرىش Use the previous authentication end (server) certificate مۇرۇنقۇ دالىلدۅ سوڭۇ ( مۇلازىمەتىر) كەنشكەسىن ىشتەتىش Verify peer (server) certificate nsCertType specification تەڭ تۉيۉن ( مۇلازىمەتىر) كەنىشكەسى nsCertType نىڭ كونكرېتلىقىنى دالىلدۅ Mode ۉلگۉ Proxies ۋاكالەتەن Proxy Type ۋاكالەتەن تۉرۉ Security قووپسۇزدۇق HMAC Authentication HMAC دالىلدۅ Input content مازمۇن كىرگىزۉۉ No جوق Self-adaption ۅز-ۅزىگە شايكەشۉۉ Automatic اپتوماتتىك Exit سىندىرۇۇ ووزۇ Restart قايرا قوزعوتۇۇ Don't verify certificate identification كەنىشكە اتۇۇلدۇق دالىلدۅۅنۉ ئىسپاتلىماڭ Verify the entire subject exactly پۉتۉن سىيۇجەتتى بىر وتولۇ انىقتاش Verify name exactly اتاعىن انىقتاپ دالىلدۅ Verify name by prefix اتاعىن الدى قوشۇلما بويۇنچا دالىلدۅ Server مۇلازىمەتىر Client ئەپ None جوق TLS-Certification TLS-دالىلدۅ TLS-Encryption TLS-سىيفىرلوو Not Required تالاپ قىلىنبايت Default العاچىنداعى Options: تاندالباعاندار: Request an inner IP address ىچكى IP دايىن وردۇ ۅتۉنۉچ جاسوو ،اتقارۇۇ Enforce UDP encapsulation UDP قاپتوونۇ اتقارماق جاسوو ،اتقارۇۇ Use IP compression IP پىرىستوو ىشتەتىش Enable custom password suggestions ۅزۉ كۅرسۅتۉلگۅن جاشىرۇۇن نومۇر قوزعوتۇۇ سۇنۇشۇ Choose a private key جەكەلىك اچقىچ تانداش Key Files (*.key *.pem *.der *.p12 *.pfx) تۉيۉندۉۉ ۅجۅتتۅر (*.key *.pem *.der *.p12 *.pfx) VpnConfigPage Type تۉرۉ Name ات-تەك اتى Static Key تىنچ ، تىم تىرس ابالىنداعى جاشىرۇۇن اچقىچ Local IP جەردىك دايىن وردۇIP Remote IP ىرااقتان تىزگىندۅۅ جاسايتۇرعان دايىن وردۇIP PIN Code PIN قۇپۇيا نومۇرۇ Password جاشىرۇۇن اچقىچ NT Domain NT گۅۅلۅم Server Address مۇلازىمەتىر دايىن وردۇ Authentication Mode دالىلدۅ ۉلگۉسۉ CA Certificate CA كەنىشكەسى User Certificate ىشتەتۉۉچۉ كەنىشكەسى Key Direction تۉيۉندۉۉ باعىت Private Key جەكەلىك اچقىچ Private Key Password جەكەلىك اچقىچ پارولۇ Password Options پارول تاندالمالارى Username كەرەكتۅۅچۉ ناامى Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. دىققات:ەگەر جاشىرۇۇن اچقىچ باعىتىن ىشتەتكەن بولسو، ال سۅزسۉز ىشتەتكەن VPN ال چى مەنەن قاراما قارشى بولۇۇسۇ كەرەك. ەگەر «1» نى ىشتەتكەن بولسو، ال لاشتا سۅزسۉز «0» نى ىشتەتىش كەرەك. ەگەر قايسى نارقتۇۇنۇ ىشتەتىش نى جەزملەشتۈرەلمىسىڭىز ساامالىق باشقارعۇۇچۇ مەنەن بايلانىش جاساڭ. Choose تانداش None جوق Save password only for this user جالاڭ عانا گەزەكتەكى كەرەكتۅۅچۉ جاشىرۇۇن نومۇر ساقتوو Save password for all users باردىق ابونتتار ۉچۉن جاشىرۇۇن نومۇر ساقتوو Ask password every time ار بىر ىرەت جاشىرۇۇن نومۇر سۇروو Don't require a password جاشىرۇۇن نومۇر تالاپ قىلبوو Required مۉلدۅ تولتۇرۇ Certificate(TLS) كەنىشكە(TLS) Static key تىنچ ، تىم تىرس ابالىنداعى اچقىچ Password and certificate(TLS) جاشىرۇۇن نومۇر جانا كەنىشكە(TLS) Certificate/Private key كەنىشكە/جەكە اچقىچ Certificate/ssh-agent كەنىشكە/ ssh-agent Smart card روحىي جۅندۅمدۉلۉك كارتوچكا Choose a private key جەكەلىك اچقىچ تانداش Key Files (*.key *.pem *.der *.p12 *.pfx) تۉيۉندۉۉ ۅجۅتتۅر (*.key *.pem *.der *.p12 *.pfx) Choose a CA certificate CA كەنىشكەسى تانداش CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA ۅجۅتتۅرۉ (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate ىشتەتۉۉچۉ كەنىشكەسى تانداش Choose a Static key تىنچ ، تىم تىرس ابالىنداعى اچقىچ تانداش VpnDetail VPN IPv4 IPv6 Advanced جوعورۇ چەك Auto Connection اپتوماتتىك ۇلوو Cancel ارعادان قالتىرىش Confirm بەكىتۉۉ VpnIpv4Page IPv4 Config IPv4 تەڭشەگى Address دايىن وردۇ Netmask بۅلۉمچۅ تور جاشىرىن نومۇرۇ Default Gateway العاچىنداعى تور ۅتكۅلۉ DNS Server DNS سان قاينارى Search Domain تور اتاعىن ىزدۅۅ DHCP Client ID DHCP ئەپ IDسى Auto(DHCP) اپتوماتتىك(DHCP) Manual قولدونمو VpnIpv6Page IPv6 Config IPv6 تەڭشەگى Address دايىن وردۇ Netmask بۅلۉمچۅ تور جاشىرىن نومۇرۇ Default Gateway العاچىنداعى تور ۅتكۅلۉ DNS Server DNS سان قاينارى Search Domain تور اتاعىن ىزدۅۅ Auto(DHCP) اپتوماتتىك(DHCP) Manual قولدونمو VpnListItem Not connected ۇلانباعان Disconnect ۉزۉپ اتۇۇ Connect ۇلانۇۇ VpnPage VPN VPN Settings VPN تەڭشەكتەرى vpnAddPage create VPN VPN قۇرۇۇ VPN Type VPN تۉرۉ VPN Name VPN ناامى Required مۉلدۅ تولتۇرۇ VPN Server VPN سان قاينارى Auto Connection اپتوماتتىك ۇلوو Confirm بەكىتۉۉ Cancel ارعادان قالتىرىش vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool vpn قۇرالى kylin-nm/src-vpn/translations/kylin-vpn_es.ts0000664000175000017500000010632015167651420020346 0ustar fengfeng SinglePage Settings Configuración Kylin VPN Kylin VPN kylin vpn applet desktop message Mensaje de escritorio del applet de VPN de Kylin VpnAdvancedPage MPPE encryption algorithm: Algoritmo de encriptación MPPE: Use Stateful encryption Usar el cifrado con estado Send PPP echo packets Envío de paquetes de eco PPP Authentication Mode: Modo de autenticación: PAP authentication Autenticación PAP CHAP authentication Autenticación CHAP MSCHAP authentication Autenticación MSCHAP MSCHAP2 authentication Autenticación MSCHAP2 EAP authentication Autenticación EAP Compression Mode: Modo de compresión: Allow BSD data compression Permitir la compresión de datos BSD Allow Default data compression Permitir la compresión de datos predeterminada Allow TCP header compression Permitir la compresión de encabezados TCP Use protocol field compression negotiation Uso de la negociación de compresión de campos de protocolo Use Address/Control compression Usar compresión de dirección/control All Available Todo disponible 128-bit 128 bits 40-bit 40 bits Use custom gateway port Usar puerto de puerta de enlace personalizado Use compression Usar compresión Use a TCP connection Usar una conexión TCP Set virtual device type Establecer el tipo de dispositivo virtual Set virtual device name Establecer el nombre del dispositivo virtual Limit TCP Maximum Segment Size(MSS) Limitar el tamaño máximo de segmento TCP (MSS) Randomize remote hosts Aleatorización de hosts remotos IPv6 tun link Enlace de tun IPv6 Specify ping interval Especificar intervalo de ping Specify exit or restart ping Especificar el ping de salida o reinicio Specify max routes Especificar el número máximo de rutas Infinite retry on error Reintento infinito en caso de error Use custom key size Usar un tamaño de clave personalizado Choose Elegir Use custom renegotiation interval Usar intervalo de renegociación personalizado Use custom tunnel Maximum Transmission Umit(MTU) Usar Umit de transmisión máxima de túnel personalizado (MTU) Use custom UDP fragment size Usar un tamaño de fragmento UDP personalizado Accept authenticated packets from any address (Float) Aceptar paquetes autenticados desde cualquier dirección (flotante) Subject Match Coincidencia de sujeto Key File Archivo de claves Key Direction Dirección clave Server Address Dirección del servidor Port Puerto Proxy USername Proxy USername Proxy Password Contraseña de proxy General General TLS settings Configuración de TLS Server Certificate Check Comprobación de certificados de servidor Use the previous authentication end (server) certificate Usar el certificado final de autenticación (servidor) anterior Verify peer (server) certificate nsCertType specification Comprobación de la especificación nsCertType del certificado del mismo nivel (servidor) Mode Modo Proxies Proxies Proxy Type Tipo de proxy Security Seguridad HMAC Authentication Autenticación HMAC Input content Contenido de entrada No No Self-adaption Autoadaptación Automatic Automático Exit Salida Restart Reanudar Don't verify certificate identification No verificar la identificación del certificado Verify the entire subject exactly Verifique todo el sujeto exactamente Verify name exactly Verifique el nombre exactamente Verify name by prefix Verificar el nombre por prefijo Server Servidor Client Cliente None Ninguno TLS-Certification Certificación TLS TLS-Encryption Cifrado TLS Not Required No es necesario Default Predeterminado Options: Opciones: Request an inner IP address Solicitar una dirección IP interna Enforce UDP encapsulation Aplicación de la encapsulación UDP Use IP compression Usar la compresión IP Enable custom password suggestions Habilitar sugerencias de contraseñas personalizadas Choose a private key Elegir una clave privada Key Files (*.key *.pem *.der *.p12 *.pfx) Archivos de claves (*.key, *.pem, *.der, *.p12, *.pfx) VpnConfigPage Type Tipo Name Nombre Static Key Clave estática Local IP Local IP Remote IP IP remota PIN Code Código PIN Password Contraseña NT Domain Dominio NT Server Address Dirección del servidor Authentication Mode Modo de autenticación CA Certificate Certificado de CA User Certificate Certificado de usuario Key Direction Dirección clave Private Key Clave privada Private Key Password Contraseña de clave privada Password Options Opciones de contraseña Username Nombre de usuario Notice: If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. Notar: Si se utiliza la dirección de la clave, debe ser opuesta al lado de la VPN utilizado. Si se usa '1', la conexión debe usar '0'. Si no está seguro de qué valor utilizar, póngase en contacto con el administrador del sistema. Choose Elegir None Ninguno Save password only for this user Guardar contraseña solo para este usuario Save password for all users Guardar contraseña para todos los usuarios Ask password every time Pregunte la contraseña cada vez Don't require a password No requiere una contraseña Required Obligatorio Certificate(TLS) Certificado (TLS) Static key Clave estática Password and certificate(TLS) Contraseña y certificado (TLS) Certificate/Private key Certificado/Clave privada Certificate/ssh-agent Certificado/ssh-agente Smart card Tarjeta inteligente Choose a private key Elegir una clave privada Key Files (*.key *.pem *.der *.p12 *.pfx) Archivos de claves (*.key, *.pem, *.der, *.p12, *.pfx) Choose a CA certificate Elección de un certificado de CA CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Archivos CA (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a User certificate Elegir un certificado de usuario Choose a Static key Elegir una clave estática VpnDetail VPN IPv4 IPv6 Advanced Avanzado Auto Connection Conexión automática Cancel Cancelar Confirm Confirmar VpnIpv4Page IPv4 Config Configuración de IPv4 Address Dirección Netmask Máscara de red Default Gateway Puerta de enlace predeterminada DNS Server Servidor DNS Search Domain Dominio de búsqueda DHCP Client ID ID de cliente DHCP Auto(DHCP) Automático (DHCP) Manual Manual VpnIpv6Page IPv6 Config Configuración de IPv6 Address Dirección Netmask Máscara de red Default Gateway Puerta de enlace predeterminada DNS Server Servidor DNS Search Domain Dominio de búsqueda Auto(DHCP) Automático (DHCP) Manual Manual VpnListItem Not connected No conectado Disconnect Desconectar Connect Conectar VpnPage VPN VPN Settings Configuración de VPN vpnAddPage create VPN crear VPN VPN Type Tipo de VPN VPN Name Nombre de la VPN Required Obligatorio VPN Server Servidor VPN Auto Connection Conexión automática Confirm Confirmar Cancel Cancelar vpnConfigPage VPN Type VPN类型 vpnObject VPN Tool Herramienta VPN kylin-nm/src-vpn/main.cpp0000664000175000017500000001324015167651420014265 0ustar fengfeng/* * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see #include #include "qt-single-application.h" #include #include #include #include #include #if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)) #include "xatom-helper.h" #endif #include "vpnobject.h" #define LOG_IDENT "kylin_vpn" const QString QT_TRANSLATE_FILE = "/usr/share/qt6/translations/qt_zh_CN.qm"; void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); QByteArray currentDateTime = QDateTime::currentDateTime().toString().toLocal8Bit(); bool showDebug = true; QString logFilePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + "/.config/ukui/kylin-nm.log"; FILE *log_file = nullptr; if (showDebug) { log_file = fopen(logFilePath.toLocal8Bit().constData(), "a+"); } const char *file = context.file ? context.file : ""; const char *function = context.function ? context.function : ""; switch (type) { case QtDebugMsg: if (!log_file) { break; } fprintf(log_file, "Debug: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); break; case QtInfoMsg: fprintf(log_file? log_file: stdout, "Info: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); break; case QtWarningMsg: fprintf(log_file? log_file: stderr, "Warning: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); break; case QtCriticalMsg: fprintf(log_file? log_file: stderr, "Critical: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); break; case QtFatalMsg: fprintf(log_file? log_file: stderr, "Fatal: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); break; } if (log_file) fclose(log_file); } int main(int argc, char *argv[]) { initUkuiLog4qt("kylin-vpn"); #if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)) QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); #endif QString id = QString("kylin-vpn"+ QLatin1String(getenv("DISPLAY"))); QtSingleApplication a(id, argc, argv); QApplication::setQuitOnLastWindowClosed(false); QDBusInterface interface("com.kylin.kylinvpn", "/com/kylin/kylinvpn", "com.kylin.kylinvpn", QDBusConnection::sessionBus()); if(interface.isValid()) { return 0; } QThread *thread = new QThread(); KyNetworkResourceManager *p_networkResource = KyNetworkResourceManager::getInstance(); p_networkResource->moveToThread(thread); QObject::connect(thread, &QThread::started, p_networkResource, &KyNetworkResourceManager::onInitNetwork); QObject::connect(&a,&QtSingleApplication::aboutToQuit, thread, &QThread::quit); QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater); QObject::connect(thread, &QThread::finished, [=](){ qDebug() << "release" ; p_networkResource->Release(); }); thread->start(); // Internationalization QString locale = QLocale::system().name(); QTranslator trans_global; qDebug() << "QLocale " << QLocale(); if (trans_global.load(QLocale(), "kylin-vpn", "_", "/usr/share/kylin-nm/kylin-vpn/")) { a.installTranslator(&trans_global); qDebug()<<"Translations load success"; } else { qWarning() << "Translations load fail"; } QTranslator qtBaseTranslator; if (qtBaseTranslator.load(QLocale(), "qt", "_", "/usr/share/qt6/translations/")) { a.installTranslator(&qtBaseTranslator); qDebug()<<"QtBase Translations load success"; } else { qWarning() << "QtBase Translations load fail"; } while (!p_networkResource->NetworkManagerIsInited()) { ::usleep(1000); } vpnObject vpnobject; a.setActivationWindow(&vpnobject); vpnobject.setProperty("useStyleWindowManager", false); //禁用拖动 a.setWindowIcon(QIcon::fromTheme("network-vpn-symbolic")); VpnDbusAdaptor vpnAdaptor(&vpnobject); Q_UNUSED(vpnAdaptor); auto connection = QDBusConnection::sessionBus(); if (!connection.registerService("com.kylin.kylinvpn") || !connection.registerObject("/com/kylin/kylinvpn", &vpnobject)) { qCritical() << "QDbus register service failed reason:" << connection.lastError(); } return a.exec(); } kylin-nm/src-vpn/translate_generation.sh0000775000175000017500000000056615167651420017413 0ustar fengfeng#!/bin/bash export PATH="/usr/lib/qt6/bin:$PATH" ts_list=(`ls translations/*.ts`) source /etc/os-release version=(`echo $ID`) for ts in "${ts_list[@]}" do printf "\nprocess ${ts}\n" if [ "$version" == "fedora" ] || [ "$version" == "opensuse-leap" ] || [ "$version" == "opensuse-tumbleweed" ];then lrelease-qt5 "${ts}" else lrelease "${ts}" fi done kylin-nm/src-vpn/singleapplication/0000775000175000017500000000000015167651420016342 5ustar fengfengkylin-nm/src-vpn/singleapplication/qt-single-application.cpp0000664000175000017500000003016415167651420023256 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ** ****************************************************************************/ #include "qt-single-application.h" #include "qt-local-peer.h" #include #include #include #include #include #include #include #include "../vpnobject.h" /*! \class QtSingleApplication qtsingleapplication.h \brief The QtSingleApplication class provides an API to detect and communicate with running instances of an application. This class allows you to create applications where only one instance should be running at a time. I.e., if the user tries to launch another instance, the already running instance will be activated instead. Another usecase is a client-server system, where the first started instance will assume the role of server, and the later instances will act as clients of that server. By default, the full path of the executable file is used to determine whether two processes are instances of the same application. You can also provide an explicit identifier string that will be compared instead. The application should create the QtSingleApplication object early in the startup phase, and call isRunning() to find out if another instance of this application is already running. If isRunning() returns false, it means that no other instance is running, and this instance has assumed the role as the running instance. In this case, the application should continue with the initialization of the application user interface before entering the event loop with exec(), as normal. The messageReceived() signal will be emitted when the running application receives messages from another instance of the same application. When a message is received it might be helpful to the user to raise the application so that it becomes visible. To facilitate this, QtSingleApplication provides the setActivationWindow() function and the activateWindow() slot. If isRunning() returns true, another instance is already running. It may be alerted to the fact that another instance has started by using the sendMessage() function. Also data such as startup parameters (e.g. the name of the file the user wanted this new instance to open) can be passed to the running instance with this function. Then, the application should terminate (or enter client mode). If isRunning() returns true, but sendMessage() fails, that is an indication that the running instance is frozen. Here's an example that shows how to convert an existing application to use QtSingleApplication. It is very simple and does not make use of all QtSingleApplication's functionality (see the examples for that). \code // Original int main(int argc, char **argv) { QApplication app(argc, argv); MyMainWidget mmw; mmw.show(); return app.exec(); } // Single instance int main(int argc, char **argv) { QtSingleApplication app(argc, argv); if (app.isRunning()) return !app.sendMessage(someDataString); MyMainWidget mmw; app.setActivationWindow(&mmw); mmw.show(); return app.exec(); } \endcode Once this QtSingleApplication instance is destroyed (normally when the process exits or crashes), when the user next attempts to run the application this instance will not, of course, be encountered. The next instance to call isRunning() or sendMessage() will assume the role as the new running instance. For console (non-GUI) applications, QtSingleCoreApplication may be used instead of this class, to avoid the dependency on the QtGui library. \sa QtSingleCoreApplication */ void QtSingleApplication::sysInit(const QString &appId) { m_activateWindow = 0; m_peer = new QtLocalPeer(this, appId); connect(m_peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::messageReceived); } /*! Creates a QtSingleApplication object. The application identifier will be QCoreApplication::applicationFilePath(). \a argc, \a argv, and \a GUIenabled are passed on to the QAppliation constructor. If you are creating a console application (i.e. setting \a GUIenabled to false), you may consider using QtSingleCoreApplication instead. */ QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled) : QApplication(argc, argv, GUIenabled) { sysInit(); } /*! Creates a QtSingleApplication object with the application identifier \a appId. \a argc and \a argv are passed on to the QAppliation constructor. */ QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv) : QApplication(argc, argv) { sysInit(appId); } #if QT_VERSION < 0x050000 /*! Creates a QtSingleApplication object. The application identifier will be QCoreApplication::applicationFilePath(). \a argc, \a argv, and \a type are passed on to the QAppliation constructor. */ QtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type) : QApplication(argc, argv, type) { sysInit(); } # if defined(Q_WS_X11) /*! Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier will be QCoreApplication::applicationFilePath(). \a dpy, \a visual, and \a cmap are passed on to the QApplication constructor. */ QtSingleApplication::QtSingleApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE cmap) : QApplication(dpy, visual, cmap) { sysInit(); } /*! Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier will be QCoreApplication::applicationFilePath(). \a dpy, \a argc, \a argv, \a visual, and \a cmap are passed on to the QApplication constructor. */ QtSingleApplication::QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) : QApplication(dpy, argc, argv, visual, cmap) { sysInit(); } /*! Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier will be \a appId. \a dpy, \a argc, \a argv, \a visual, and \a cmap are passed on to the QApplication constructor. */ QtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) : QApplication(dpy, argc, argv, visual, cmap) { sysInit(appId); } # endif // Q_WS_X11 #endif // QT_VERSION < 0x050000 /*! Returns true if another instance of this application is running; otherwise false. This function does not find instances of this application that are being run by a different user (on Windows: that are running in another session). \sa sendMessage() */ bool QtSingleApplication::isRunning() { return m_peer->isClient(); } /*! Tries to send the text \a message to the currently running instance. The QtSingleApplication object in the running instance will emit the messageReceived() signal when it receives the message. This function returns true if the message has been sent to, and processed by, the current instance. If there is no instance currently running, or if the running instance fails to process the message within \a timeout milliseconds, this function return false. \sa isRunning(), messageReceived() */ bool QtSingleApplication::sendMessage(const QString &message, int timeout) { return m_peer->sendMessage(message, timeout); } /*! Returns the application identifier. Two processes with the same identifier will be regarded as instances of the same application. */ QString QtSingleApplication::id() const { return m_peer->applicationId(); } /*! Sets the activation window of this application to \a aw. The activation window is the widget that will be activated by activateWindow(). This is typically the application's main window. If \a activateOnMessage is true (the default), the window will be activated automatically every time a message is received, just prior to the messageReceived() signal being emitted. \sa activateWindow(), messageReceived() */ void QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage) { m_activateWindow = aw; if (activateOnMessage) connect(m_peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow); else disconnect(m_peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow); } /*! Returns the applications activation window if one has been set by calling setActivationWindow(), otherwise returns 0. \sa setActivationWindow() */ QWidget* QtSingleApplication::activationWindow() const { return m_activateWindow; } /*! De-minimizes, raises, and activates this application's activation window. This function does nothing if no activation window has been set. This is a convenience function to show the user that this application instance has been activated when he has tried to start another instance. This function should typically be called in response to the messageReceived() signal. By default, that will happen automatically, if an activation window has been set. \sa setActivationWindow(), messageReceived(), initialize() */ void QtSingleApplication::activateWindow() { if (m_activateWindow) { if(this->applicationState() & Qt::ApplicationInactive) { m_activateWindow->setWindowState(m_activateWindow->windowState() & ~Qt::WindowMinimized); m_activateWindow->raise(); m_activateWindow->showNormal(); m_activateWindow->activateWindow(); } else { m_activateWindow->setWindowState(m_activateWindow->windowState() & Qt::WindowMinimized); m_activateWindow->hide(); } } } /*! \fn void QtSingleApplication::messageReceived(const QString& message) This signal is emitted when the current instance receives a \a message from another instance of this application. \sa sendMessage(), setActivationWindow(), activateWindow() */ /*! \fn void QtSingleApplication::initialize(bool dummy = true) \obsolete */ kylin-nm/src-vpn/singleapplication/qt-locked-file-unix.cpp0000664000175000017500000000662115167646234022643 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include #include #include #include #include "qt-locked-file.h" bool QtLockedFile::lock(LockMode mode, bool block) { if(!isOpen()) { qWarning("QtLockedFile::lock(): file is not opened"); return false; } if(mode == NoLock) return unlock(); if(mode == m_lock_mode) return true; if(m_lock_mode != NoLock) unlock(); struct flock fl; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK; int cmd = block ? F_SETLKW : F_SETLK; int ret = fcntl(handle(), cmd, &fl); if(ret == -1) { if(errno != EINTR && errno != EAGAIN) qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); return false; } m_lock_mode = mode; return true; } bool QtLockedFile::unlock() { if(!isOpen()) { qWarning("QtLockedFile::unlock(): file is not opened"); return false; } if(!isLocked()) return true; struct flock fl; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_type = F_UNLCK; int ret = fcntl(handle(), F_SETLKW, &fl); if(ret == -1) { qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); return false; } m_lock_mode = NoLock; return true; } QtLockedFile::~QtLockedFile() { if(isOpen()) unlock(); } kylin-nm/src-vpn/singleapplication/qt-single-application.pri0000664000175000017500000000131115167646234023265 0ustar fengfengINCLUDEPATH += $$PWD DEPENDPATH += $$PWD QT *= network greaterThan(QT_MAJOR_VERSION, 4): QT *= widgets qtsingleapplication-uselib:!qtsingleapplication-buildlib { LIBS += -L$$QTSINGLEAPPLICATION_LIBDIR -l$$QTSINGLEAPPLICATION_LIBNAME } else { SOURCES += HEADERS += } win32 { contains(TEMPLATE, lib):contains(CONFIG, shared):DEFINES += QT_QTSINGLEAPPLICATION_EXPORT else:qtsingleapplication-uselib:DEFINES += QT_QTSINGLEAPPLICATION_IMPORT } HEADERS += \ $$PWD/qt-local-peer.h \ $$PWD/qt-locked-file.h \ $$PWD/qt-single-application.h SOURCES += \ $$PWD/qt-local-peer.cpp \ $$PWD/qt-locked-file-unix.cpp \ $$PWD/qt-single-application.cpp \ $$PWD/qt-locked-file.cpp kylin-nm/src-vpn/singleapplication/qt-single-application.h0000664000175000017500000000772715167646234022743 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ** ****************************************************************************/ #ifndef QTSINGLEAPPLICATION_H #define QTSINGLEAPPLICATION_H #include class QtLocalPeer; #if defined(Q_OS_WIN) # if !defined(QT_QTSINGLEAPPLICATION_EXPORT) && !defined(QT_QTSINGLEAPPLICATION_IMPORT) # define QT_QTSINGLEAPPLICATION_EXPORT # elif defined(QT_QTSINGLEAPPLICATION_IMPORT) # if defined(QT_QTSINGLEAPPLICATION_EXPORT) # undef QT_QTSINGLEAPPLICATION_EXPORT # endif # define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllimport) # elif defined(QT_QTSINGLEAPPLICATION_EXPORT) # undef QT_QTSINGLEAPPLICATION_EXPORT # define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllexport) # endif #else # define QT_QTSINGLEAPPLICATION_EXPORT #endif class QT_QTSINGLEAPPLICATION_EXPORT QtSingleApplication : public QApplication { Q_OBJECT public: QtSingleApplication(int &argc, char **argv, bool GUIenabled = true); QtSingleApplication(const QString &id, int &argc, char **argv); #if QT_VERSION < 0x050000 QtSingleApplication(int &argc, char **argv, Type type); # if defined(Q_WS_X11) QtSingleApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0); QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); # endif // Q_WS_X11 #endif // QT_VERSION < 0x050000 bool isRunning(); QString id() const; void setActivationWindow(QWidget* aw, bool activateOnMessage = true); QWidget* activationWindow() const; // Obsolete: void initialize(bool dummy = true) { isRunning(); Q_UNUSED(dummy) } public Q_SLOTS: bool sendMessage(const QString &message, int timeout = 5000); void activateWindow(); Q_SIGNALS: void messageReceived(const QString &message); private: void sysInit(const QString &appId = QString()); QtLocalPeer *m_peer; QWidget *m_activateWindow; }; #endif // QTSINGLEAPPLICATION_H kylin-nm/src-vpn/singleapplication/qt-local-peer.cpp0000664000175000017500000001612615167651420021521 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ** ****************************************************************************/ #include "qt-local-peer.h" #include #include #include #include #if defined(Q_OS_UNIX) #include #include #include #endif namespace QtLP_Private { #include "qt-locked-file.cpp" #include "qt-locked-file-unix.cpp" } const char* QtLocalPeer::ack = "ack"; QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId) : QObject(parent), id(appId) { QString prefix = id; if(id.isEmpty()) { id = QCoreApplication::applicationFilePath(); #if defined(Q_OS_WIN) id = id.toLower(); #endif prefix = id.section(QLatin1Char('/'), -1); //完整路径按‘/’分隔后取最后一个字段 } prefix.remove(QRegularExpression("[^a-zA-Z]")); //去掉名称中的非字母 prefix.truncate(6); //取前六位 QByteArray idc = id.toUtf8(); quint16 idNum = qChecksum(idc.constData(), idc.size()); socketName = QLatin1String("qtsingleapp-") + prefix + QLatin1Char('-') + QString::number(idNum, 16); #if defined(Q_OS_WIN) if(!pProcessIdToSessionId) { QLibrary lib("kernel32"); pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId"); } if(pProcessIdToSessionId) { DWORD sessionId = 0; pProcessIdToSessionId(GetCurrentProcessId(), &sessionId); socketName += QLatin1Char('-') + QString::number(sessionId, 16); } #else socketName += QLatin1Char('-') + QString::number(::getuid(), 16); #endif server = new QLocalServer(this); QString lockName = QDir(QDir::tempPath()).absolutePath() + QLatin1Char('/') + socketName + QLatin1String("-lockfile"); //tmp目录下的锁文件 lockFile.setFileName(lockName); lockFile.open(QIODevice::ReadWrite); } bool QtLocalPeer::isClient() { if(lockFile.isLocked()) return false; if(!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false)) return true; //由于文件锁的存在,仅当本进程第一次启动时能执行到此并使server进行监听和关联槽函数 bool res = server->listen(socketName); #if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0)) // ### Workaround if(!res && server->serverError() == QAbstractSocket::AddressInUseError) { QFile::remove(QDir::cleanPath(QDir::tempPath()) + QLatin1Char('/') + socketName); res = server->listen(socketName); } #endif if(!res) qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString())); QObject::connect(server, &QLocalServer::newConnection, this, &QtLocalPeer::receiveConnection); return false; } bool QtLocalPeer::sendMessage(const QString &message, int timeout) { if(!isClient()) return false; QLocalSocket socket; bool connOk = false; for(int i = 0; i < 2; i++) { // Try twice, in case the other instance is just starting up socket.connectToServer(socketName); connOk = socket.waitForConnected(timeout / 2); if(connOk || i) break; int ms = 250; #if defined(Q_OS_WIN) Sleep(DWORD(ms)); #else struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; nanosleep(&ts, NULL); #endif } if(!connOk) return false; QByteArray uMsg(message.toUtf8()); QDataStream ds(&socket); ds.writeBytes(uMsg.constData(), uMsg.size()); bool res = socket.waitForBytesWritten(timeout); if(res) { res &= socket.waitForReadyRead(timeout); // wait for ack if(res) res &= (socket.read(qstrlen(ack)) == ack); } return res; } /** * @brief QtLocalPeer::receiveConnection 当新进程启动时,会尝试连接此进程server,server接收到newConnection信号并触发此槽函数 */ void QtLocalPeer::receiveConnection() { QLocalSocket* socket = server->nextPendingConnection(); //获取新进程的socket if(!socket) return; while(true) { if(socket->state() == QLocalSocket::UnconnectedState) { qWarning("QtLocalPeer: Peer disconnected"); delete socket; return; } if(socket->bytesAvailable() >= qint64(sizeof(quint32))) break; socket->waitForReadyRead(); } QDataStream ds(socket); QByteArray uMsg; quint32 remaining; ds >> remaining; uMsg.resize(remaining); int got = 0; char* uMsgBuf = uMsg.data(); do { got = ds.readRawData(uMsgBuf, remaining); remaining -= got; uMsgBuf += got; } while(remaining && got >= 0 && socket->waitForReadyRead(2000)); if(got < 0) { qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); delete socket; return; } QString message(QString::fromUtf8(uMsg)); socket->write(ack, qstrlen(ack)); socket->waitForBytesWritten(1000); socket->waitForDisconnected(1000); // make sure client reads ack delete socket; Q_EMIT messageReceived(message); //获取新进程的启动信息并作为信号发送给前端 } kylin-nm/src-vpn/singleapplication/qt-locked-file.cpp0000664000175000017500000001401415167646234021655 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qt-locked-file.h" /*! \class QtLockedFile \brief The QtLockedFile class extends QFile with advisory locking functions. A file may be locked in read or write mode. Multiple instances of \e QtLockedFile, created in multiple processes running on the same machine, may have a file locked in read mode. Exactly one instance may have it locked in write mode. A read and a write lock cannot exist simultaneously on the same file. The file locks are advisory. This means that nothing prevents another process from manipulating a locked file using QFile or file system functions offered by the OS. Serialization is only guaranteed if all processes that access the file use QLockedFile. Also, while holding a lock on a file, a process must not open the same file again (through any API), or locks can be unexpectedly lost. The lock provided by an instance of \e QtLockedFile is released whenever the program terminates. This is true even when the program crashes and no destructors are called. */ /*! \enum QtLockedFile::LockMode This enum describes the available lock modes. \value ReadLock A read lock. \value WriteLock A write lock. \value NoLock Neither a read lock nor a write lock. */ /*! Constructs an unlocked \e QtLockedFile object. This constructor behaves in the same way as \e QFile::QFile(). \sa QFile::QFile() */ QtLockedFile::QtLockedFile() : QFile() { #ifdef Q_OS_WIN wmutex = 0; rmutex = 0; #endif m_lock_mode = NoLock; } /*! Constructs an unlocked QtLockedFile object with file \a name. This constructor behaves in the same way as \e QFile::QFile(const QString&). \sa QFile::QFile() */ QtLockedFile::QtLockedFile(const QString &name) : QFile(name) { #ifdef Q_OS_WIN wmutex = 0; rmutex = 0; #endif m_lock_mode = NoLock; } /*! Opens the file in OpenMode \a mode. This is identical to QFile::open(), with the one exception that the Truncate mode flag is disallowed. Truncation would conflict with the advisory file locking, since the file would be modified before the write lock is obtained. If truncation is required, use resize(0) after obtaining the write lock. Returns true if successful; otherwise false. \sa QFile::open(), QFile::resize() */ bool QtLockedFile::open(OpenMode mode) { if(mode & QIODevice::Truncate) { qWarning("QtLockedFile::open(): Truncate mode not allowed."); return false; } return QFile::open(mode); } /*! Returns \e true if this object has a in read or write lock; otherwise returns \e false. \sa lockMode() */ bool QtLockedFile::isLocked() const { return m_lock_mode != NoLock; } /*! Returns the type of lock currently held by this object, or \e QtLockedFile::NoLock. \sa isLocked() */ QtLockedFile::LockMode QtLockedFile::lockMode() const { return m_lock_mode; } /*! \fn bool QtLockedFile::lock(LockMode mode, bool block = true) Obtains a lock of type \a mode. The file must be opened before it can be locked. If \a block is true, this function will block until the lock is aquired. If \a block is false, this function returns \e false immediately if the lock cannot be aquired. If this object already has a lock of type \a mode, this function returns \e true immediately. If this object has a lock of a different type than \a mode, the lock is first released and then a new lock is obtained. This function returns \e true if, after it executes, the file is locked by this object, and \e false otherwise. \sa unlock(), isLocked(), lockMode() */ /*! \fn bool QtLockedFile::unlock() Releases a lock. If the object has no lock, this function returns immediately. This function returns \e true if, after it executes, the file is not locked by this object, and \e false otherwise. \sa lock(), isLocked(), lockMode() */ /*! \fn QtLockedFile::~QtLockedFile() Destroys the \e QtLockedFile object. If any locks were held, they are released. */ kylin-nm/src-vpn/singleapplication/qt-locked-file.h0000664000175000017500000000636015167646234021327 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QTLOCKEDFILE_H #define QTLOCKEDFILE_H #include #ifdef Q_OS_WIN #include #endif #if defined(Q_OS_WIN) # if !defined(QT_QTLOCKEDFILE_EXPORT) && !defined(QT_QTLOCKEDFILE_IMPORT) # define QT_QTLOCKEDFILE_EXPORT # elif defined(QT_QTLOCKEDFILE_IMPORT) # if defined(QT_QTLOCKEDFILE_EXPORT) # undef QT_QTLOCKEDFILE_EXPORT # endif # define QT_QTLOCKEDFILE_EXPORT __declspec(dllimport) # elif defined(QT_QTLOCKEDFILE_EXPORT) # undef QT_QTLOCKEDFILE_EXPORT # define QT_QTLOCKEDFILE_EXPORT __declspec(dllexport) # endif #else # define QT_QTLOCKEDFILE_EXPORT #endif namespace QtLP_Private { class QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile { public: enum LockMode { NoLock = 0, ReadLock, WriteLock }; QtLockedFile(); QtLockedFile(const QString &name); ~QtLockedFile(); bool open(OpenMode mode); bool lock(LockMode mode, bool block = true); bool unlock(); bool isLocked() const; LockMode lockMode() const; private: #ifdef Q_OS_WIN Qt::HANDLE wmutex; Qt::HANDLE rmutex; QVector rmutexes; QString mutexname; Qt::HANDLE getMutexHandle(int idx, bool doCreate); bool waitMutex(Qt::HANDLE mutex, bool doBlock); #endif LockMode m_lock_mode; }; } #endif kylin-nm/src-vpn/singleapplication/qt-local-peer.h0000664000175000017500000000527215167646234021175 0ustar fengfeng/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) ** 2020 KylinSoft Co., Ltd. ** Contact: http://www.qt-project.org/legal ** ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ** ****************************************************************************/ #ifndef QTLOCALPEER_H #define QTLOCALPEER_H #include #include #include #include "qt-locked-file.h" class QtLocalPeer : public QObject { Q_OBJECT public: QtLocalPeer(QObject *parent = 0, const QString &appId = QString()); bool isClient(); bool sendMessage(const QString &message, int timeout); QString applicationId() const { return id; } Q_SIGNALS: void messageReceived(const QString &message); protected Q_SLOTS: void receiveConnection(); protected: QString id; QString socketName; QLocalServer* server; QtLP_Private::QtLockedFile lockFile; private: static const char* ack; }; #endif // QTLOCALPEER_H kylin-nm/src-vpn/org.ukui.kylin-vpn.switch.gschema.xml0000664000175000017500000000053115167646234021764 0ustar fengfeng false vpnicon visible vpnicon visible.true is visible,false is invisible. kylin-nm/src-vpn/vpnqrc.qrc0000664000175000017500000000024315167646234014663 0ustar fengfeng translations/kylin-vpn_zh_CN.qm translations/kylin-vpn_bo_CN.qm kylin-nm/src-vpn/frontend/0000775000175000017500000000000015167651420014454 5ustar fengfengkylin-nm/src-vpn/frontend/vpnobject.cpp0000664000175000017500000001315415167651420017156 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #include "vpnobject.h" #include #include "ukuistylehelper/ukuistylehelper.h" vpnObject::vpnObject(QMainWindow *parent) : QMainWindow(parent) { initUI(); initTrayIcon(); initDbusConnnect(); m_uwin = new UkuiWindowHelper(this); m_uwin->setBlurEffect(QRegion()); m_uwin->setSkipTaskBar(true); m_uwin->setWindowRole(UkuiWindowHelper::WindowRole::SystemWindow); } vpnObject::~vpnObject() { if (m_vpnGsettings != nullptr) { delete m_vpnGsettings; m_vpnGsettings = nullptr; } if (m_uwin) { delete m_uwin; } } void vpnObject::initUI() { m_vpnPage = new VpnPage(nullptr); //kf6 qt6 崩溃 by mq //kdk::UkuiStyleHelper::self()->removeHeader(m_vpnPage); m_vpnPage->update(); } void vpnObject::initTrayIcon() { m_vpnTrayIcon = new QSystemTrayIcon(this); m_vpnTrayIcon->setToolTip(QString(tr("VPN Tool"))); m_vpnTrayIcon->setIcon(QIcon::fromTheme("network-vpn-symbolic")); m_vpnTrayIcon->setVisible(true); initVpnIconVisible(); connect(m_vpnTrayIcon, &QSystemTrayIcon::activated, this, &vpnObject::onTrayIconActivated); } void vpnObject::initVpnIconVisible() { if (QGSettings::isSchemaInstalled(QByteArray(GSETTINGS_VPNICON_VISIBLE))) { m_vpnGsettings = new QGSettings(QByteArray(GSETTINGS_VPNICON_VISIBLE)); if (m_vpnGsettings->keys().contains(QString(VISIBLE))) { m_vpnTrayIcon->setVisible(m_vpnGsettings->get(VISIBLE).toBool()); connect(m_vpnGsettings, &QGSettings::changed, this, [=]() { m_vpnTrayIcon->setVisible(m_vpnGsettings->get(VISIBLE).toBool()); }); } } } /** * @brief vpnObject::onTrayIconActivated 点击托盘图标的槽函数 */ void vpnObject::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) { switch(reason) { case QSystemTrayIcon::Trigger: if(m_vpnPage->isActiveWindow()) { m_vpnPage->hide(); } else { onShowMainWindow(); } break; default: break; } } void vpnObject::getVirtualList(QVector &vector) { vector.clear(); if (nullptr != m_vpnPage) { m_vpnPage->getVirtualList(vector); } } //Vpn连接删除 void vpnObject::deleteVpn(const QString &connUuid) { m_vpnPage->deleteVpn(connUuid); } //Vpn连接断开 void vpnObject::activateVpn(const QString& connUuid) { m_vpnPage->activateVpn(connUuid); } void vpnObject::deactivateVpn(const QString& connUuid) { m_vpnPage->deactivateVpn(connUuid); } void vpnObject::showDetailPage(const QString& connUuid) { m_vpnPage->showDetailPage(connUuid); } void vpnObject::onShowMainWindow() { m_vpnPage->showUI(); } void vpnObject::initDbusConnnect() { connect(m_vpnPage, &VpnPage::activateFailed, this, &vpnObject::activateFailed); connect(m_vpnPage, &VpnPage::deactivateFailed, this, &vpnObject::deactivateFailed); connect(m_vpnPage, &VpnPage::vpnAdd, this, &vpnObject::vpnAdd); connect(m_vpnPage, &VpnPage::vpnRemove, this, &vpnObject::vpnRemove); connect(m_vpnPage, &VpnPage::vpnUpdate, this, &vpnObject::vpnUpdate); connect(m_vpnPage, &VpnPage::vpnActiveConnectionStateChanged, this, &vpnObject::vpnActiveConnectionStateChanged); //模式切换 QDBusConnection::sessionBus().connect(QString("com.kylin.statusmanager.interface"), QString("/"), QString("com.kylin.statusmanager.interface"), QString("mode_change_signal"), this, SLOT(onTabletModeChanged(bool))); } void vpnObject::onTabletModeChanged(bool mode) { qDebug() << "TabletMode change" << mode; Q_UNUSED(mode) //模式切换时,隐藏主界面 m_vpnPage->hide(); } bool vpnObject::launchApp(QString desktopFile) { QDBusInterface appManagerDbusInterface(KYLIN_APP_MANAGER_NAME, KYLIN_APP_MANAGER_PATH, KYLIN_APP_MANAGER_INTERFACE, QDBusConnection::sessionBus()); if (!appManagerDbusInterface.isValid()) { qWarning()<<"appManagerDbusInterface init error"; return false; } else { QDBusReply reply = appManagerDbusInterface.call("LaunchApp", desktopFile); return reply; } } void vpnObject::runExternalApp() { if (!launchApp("nm-connection-editor.desktop")){ QString cmd = "nm-connection-editor"; QProcess process(this); process.startDetached(cmd); } } void vpnObject::showVpnAddWidget() { #ifdef VPNDETAIL if (m_vpnAddPage == nullptr) { m_vpnAddPage = new vpnAddPage(); connect(m_vpnAddPage, &vpnAddPage::closed, [&] () {m_vpnAddPage = nullptr;}); m_vpnAddPage->show(); m_vpnAddPage->centerToScreen(); } m_vpnAddPage->raise(); #else runExternalApp(); return; #endif } kylin-nm/src-vpn/frontend/frontend.pri0000664000175000017500000000037015167646234017016 0ustar fengfengINCLUDEPATH += $$PWD include(../../src/frontend/tools/tools.pri) include(list-items/list-items.pri) include(vpndetails/vpndetails.pri) include(single-pages/single-pages.pri) HEADERS += \ $$PWD/vpnobject.h SOURCES += \ $$PWD/vpnobject.cpp kylin-nm/src-vpn/frontend/vpndetails/0000775000175000017500000000000015167651420016625 5ustar fengfengkylin-nm/src-vpn/frontend/vpndetails/vpnipv6page.cpp0000664000175000017500000002564315167651420021610 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #include "vpnipv6page.h" #include "math.h" #include #define NO_LAYOUT_MARGINS 0, 0, 0, 0 #define NO_SPACE 0 #define HLAYOUT_SPACING 16 #define VLAYOUT_SPACING 24 #define AUTO_CONFIG 0 #define MANUAL_CONFIG 1 #define LOG_FLAG "[VPN IPv6Page]" VpnIpv6Page::VpnIpv6Page(QWidget *parent) : QFrame(parent) { initUI(); initConnect(); } void VpnIpv6Page::setVpnIpv6Info(const KyVpnConfig &vpnInfo) { if (vpnInfo.m_ipv6ConfigIpType == CONFIG_IP_DHCP) { m_ipv6ConfigCombox->setCurrentIndex(AUTO_CONFIG); } else { m_ipv6ConfigCombox->setCurrentIndex(MANUAL_CONFIG); if (!vpnInfo.m_ipv6Address.isEmpty()) { m_ipv6addressEdit->setText(vpnInfo.m_ipv6Address.at(0).ip().toString()); m_netMaskEdit->setText(vpnInfo.m_ipv6Address.at(0).netmask().toString()); m_gateWayEdit->setText(vpnInfo.m_ipv6Address.at(0).gateway().toString()); } } } void VpnIpv6Page::setDns(const QString &firstDns) { m_dnsServerEdit->setText(firstDns); } void VpnIpv6Page::setSearchDomain(const QString &searchDomain) { m_searchDomainEdit->setText(searchDomain); } bool VpnIpv6Page::checkIsChanged(const KyVpnConfig &vpnInfo) { bool isChanged = false; if (m_ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { if (vpnInfo.m_ipv6ConfigIpType != CONFIG_IP_DHCP) { qDebug() << LOG_FLAG << "ipv6ConfigType change to Auto"; isChanged = true; } } else { if (vpnInfo.m_ipv6ConfigIpType != CONFIG_IP_MANUAL) { qDebug() << LOG_FLAG << "ipv6ConfigType change to Manual"; isChanged = true; } if (!vpnInfo.m_ipv6Address.isEmpty()) { if(vpnInfo.m_ipv6Address.at(0).ip().toString() != m_ipv6addressEdit->text() || vpnInfo.m_ipv6Address.at(0).netmask().toString() != m_netMaskEdit->text() || vpnInfo.m_ipv6Address.at(0).gateway().toString() != m_gateWayEdit->text()) { isChanged = true; } } } if (!vpnInfo.m_ipv6Dns.isEmpty() && vpnInfo.m_ipv6Dns.at(0).toString() != m_dnsServerEdit->text()) { isChanged = true; } if (!vpnInfo.m_ipv6DnsSearch.isEmpty() && vpnInfo.m_ipv6DnsSearch.at(0) != m_searchDomainEdit->text()) { isChanged = true; } return isChanged; } void VpnIpv6Page::updateVpnIpv6Info(KyVpnConfig &vpnInfo) { if (m_ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { QString ipv6address(""); QString netMask(""); QString gateWay(""); vpnInfo.setIpConfigType(IPADDRESS_V6, CONFIG_IP_DHCP); qDebug() << LOG_FLAG << "IPv6 method" << vpnInfo.m_ipv6ConfigIpType; qDebug() << LOG_FLAG << "Update IPv6 info finished"; } else { QString ipv6address =m_ipv6addressEdit->text(); QString netMask = m_netMaskEdit->text(); QString gateWay = m_gateWayEdit->text(); qDebug() << ipv6address << netMask << gateWay; vpnInfo.setIpConfigType(IPADDRESS_V6, CONFIG_IP_MANUAL); vpnInfo.dumpInfo(); qDebug() << LOG_FLAG << "Update IPv6 info finished"; } QList ipv6DnsList; ipv6DnsList.clear(); if (!m_dnsServerEdit->text().isEmpty()) { ipv6DnsList.append(QHostAddress(m_dnsServerEdit->text())); } vpnInfo.m_ipv6DnsSearch.clear(); vpnInfo.m_ipv6DnsSearch.append(m_searchDomainEdit->text()); } void VpnIpv6Page::initUI() { /**********控件**********/ m_configLabel = new QLabel(this); m_addressLabel = new QLabel(this); m_maskLabel = new QLabel(this); m_gateWayLabel = new QLabel(this); m_dnsServerLabel = new QLabel(this); m_searchDomainLabel = new QLabel(this); m_ipv6ConfigCombox =new QComboBox(this); m_ipv6addressEdit = new QLineEdit(this); m_netMaskEdit = new QLineEdit(this); m_gateWayEdit = new QLineEdit(this); m_dnsServerEdit = new QLineEdit(this); m_searchDomainEdit = new QLineEdit(this); /**********布局**********/ QFormLayout *mainLayout = new QFormLayout(this); mainLayout->setContentsMargins(NO_LAYOUT_MARGINS); mainLayout->setHorizontalSpacing(HLAYOUT_SPACING); mainLayout->setVerticalSpacing(VLAYOUT_SPACING); mainLayout->addRow(m_configLabel, m_ipv6ConfigCombox); mainLayout->addRow(m_addressLabel, m_ipv6addressEdit); mainLayout->addRow(m_maskLabel, m_netMaskEdit); mainLayout->addRow(m_gateWayLabel, m_gateWayEdit); mainLayout->addRow(m_dnsServerLabel, m_dnsServerEdit); mainLayout->addRow(m_searchDomainLabel, m_searchDomainEdit); /**********控件显示**********/ m_configLabel->setText(tr("IPv6 Config")); m_addressLabel->setText(tr("Address")); m_maskLabel->setText(tr("Netmask")); m_gateWayLabel->setText(tr("Default Gateway")); m_dnsServerLabel->setText(tr("DNS Server")); m_searchDomainLabel->setText(tr("Search Domain")); //搜索域 m_ipv6ConfigCombox->addItem(tr("Auto(DHCP)"), AUTO_CONFIG); //"自动(DHCP)" m_ipv6ConfigCombox->addItem(tr("Manual"), MANUAL_CONFIG); //"手动" // IP的正则格式限制 QRegularExpression ipv6_rx("^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$"); QRegularExpressionValidator *ipv6ExpVal = new QRegularExpressionValidator(ipv6_rx, this); m_ipv6addressEdit->setValidator(ipv6ExpVal); m_gateWayEdit->setValidator(ipv6ExpVal); m_dnsServerEdit->setValidator(ipv6ExpVal); QRegularExpression prefix_rx("\\b(?:(?:12[0-8]|1[0-1][0-9]|^[1-9][0-9]?$)\\.){3}(?:12[0-8]|1[0-1][0-9]|^[1-9][0-9]?$)\\b"); m_netMaskEdit->setValidator(new QRegularExpressionValidator(prefix_rx,this)); } void VpnIpv6Page::initConnect() { if (m_ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { setManualEnabled(false); } else if (m_ipv6ConfigCombox->currentIndex() == MANUAL_CONFIG) { setManualEnabled(true); } connect(m_ipv6ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(onConfigChanged(int))); connect(m_ipv6ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfConfirmBtn())); connect(m_ipv6addressEdit, &QLineEdit::textChanged, this, &VpnIpv6Page::setEnableOfConfirmBtn); connect(m_netMaskEdit, &QLineEdit::textChanged, this, &VpnIpv6Page::setEnableOfConfirmBtn); connect(m_gateWayEdit, &QLineEdit::textChanged, this, &VpnIpv6Page::setEnableOfConfirmBtn); connect(m_dnsServerEdit, &QLineEdit::textChanged, this, &VpnIpv6Page::setEnableOfConfirmBtn); connect(m_searchDomainEdit, &QLineEdit::textChanged, this, &VpnIpv6Page::setEnableOfConfirmBtn); } void VpnIpv6Page::setManualEnabled(bool state) { m_addressLabel->setEnabled(state); m_maskLabel->setEnabled(state); m_gateWayLabel->setEnabled(state); m_ipv6addressEdit->setEnabled(state); m_netMaskEdit->setEnabled(state); m_gateWayEdit->setEnabled(state); } bool VpnIpv6Page::getIpv6EditState(QString text) { if (text.isEmpty()) { return true; } QRegularExpression rx("^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$"); // 进行匹配并返回结果 QRegularExpressionMatch match = rx.match(text); return match.hasMatch(); } bool VpnIpv6Page::checkConfirmBtnIsEnabled() { if (m_ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { return true; } else { if (m_ipv6addressEdit->text().isEmpty() || !getIpv6EditState(m_ipv6addressEdit->text())) { qDebug() << "IPv6 address empty or invalid"; return false; } if (m_netMaskEdit->text().isEmpty()) { qDebug() << "IPv6 netMask empty or invalid"; return false; } if (m_gateWayEdit->text().isEmpty() || !getIpv6EditState(m_gateWayEdit->text())) { qDebug() << "IPv6 gateway empty or invalid"; return false; } } return true; } void VpnIpv6Page::setEnableOfConfirmBtn() { Q_EMIT setIpv6PageState(checkConfirmBtnIsEnabled()); } void VpnIpv6Page::onConfigChanged(int index) { if (index == AUTO_CONFIG) { m_ipv6addressEdit->clear(); m_netMaskEdit->clear(); m_gateWayEdit->clear(); setManualEnabled(false); } else if (index == MANUAL_CONFIG) { setManualEnabled(true); } } kylin-nm/src-vpn/frontend/vpndetails/vpnadvancedpage.cpp0000664000175000017500000017740515167651420022475 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #include "vpnadvancedpage.h" #include #include #include #define NO_LAYOUT_MARGINS 0, 0, 0, 0 #define NO_SPACE 0 #define LAYOUT_SPACING_SMALL 8 #define HOR_LAYOUT_SPACING 24 #define LAYOUT_ADD_SPACING 16 #define VLAYOUT_ADD_SPACING 24 #define LISTWIDGET_HEIGHT 184 #define LISTWIDGET_HEIGHT_SMALL 112 #define MIN_EDIT_WIDTH 150 #define FIX_EDIT_WIDTH 200 #define MIN_LABEL_WIDTH 140 #define MAX_LABEL_WIDTH 240 #define ONE_LABEL_WIDTH 440 #define MAX_MRU_LENGTH 4 #define ITEM_HEIGHT 36 #define COMP_MODE_PROTOCOL 3 #define COMP_MODE_ADDRESS 4 #define LOG_FLAG "[VPN AdvancedPage]" VpnAdvancedPage::VpnAdvancedPage(QWidget *parent) : QFrame(parent) { initUi(); initConnect(); initDefalutCheckState(); } void VpnAdvancedPage::setL2tpOrPptpAdiaInfo(const KyVpnConfig &vpnInfo) { //L2TP PPTP共有 m_mppeECheckbox->setChecked(vpnInfo.m_mppeEnable); if (m_mppeECheckbox->isChecked()) { m_mppeECombox->setCurrentIndex((int)vpnInfo.m_mppeEncryptMethod); } else { m_mppeECombox->setEnabled(false); } m_useStatefulECheckbox->setChecked(vpnInfo.m_isAllowStatefulEncryption); m_useStatefulECheckbox->setEnabled(vpnInfo.m_mppeEnable); m_papAuthCheckbox->setEnabled(!vpnInfo.m_mppeEnable); m_chapAuthCheckbox->setEnabled(!vpnInfo.m_mppeEnable); m_eapAuthCheckbox->setEnabled(!vpnInfo.m_mppeEnable); m_sendPppEchoPkgCheckbox->setChecked(vpnInfo.m_sendPppPackage); //Auth Methods m_papAuthCheckbox->setChecked(vpnInfo.m_authMethods.testFlag(KYAUTH2_PAP)); m_chapAuthCheckbox->setChecked(vpnInfo.m_authMethods.testFlag(KYAUTH2_CHAP)); m_mschapAuthCheckbox->setChecked(vpnInfo.m_authMethods.testFlag(KYAUTH2_MSCHAP)); m_mschap2AuthCheckbox->setChecked(vpnInfo.m_authMethods.testFlag(KYAUTH2_MSCHAPV2)); m_eapAuthCheckbox->setChecked(vpnInfo.m_authMethods.testFlag(KYAUTH2_EAP)); //Compress Methods m_bsdCompModeCheckbox->setChecked(vpnInfo.m_compressMethods.testFlag(KYCOMP_BSD)); m_defaultCompModeCheckbox->setChecked(vpnInfo.m_compressMethods.testFlag(KYCOMP_DEFLATE)); m_tcpCompModeCheckbox->setChecked(vpnInfo.m_compressMethods.testFlag(KYCOMP_TCP)); //L2TP if (vpnInfo.m_vpnType == KYVPNTYPE_L2TP) { m_protocolCompModeCheckbox->setChecked(vpnInfo.m_compressMethods.testFlag(KYCOMP_PROTO)); m_addressCompModeCheckbox->setChecked(vpnInfo.m_compressMethods.testFlag(KYCOMP_ADDR)); m_mruEdit->setText(vpnInfo.m_mru); m_mtuEdit->setText(vpnInfo.m_mtu); } } void VpnAdvancedPage::setOpenVpnAdiaInfo(const KyVpnConfig &vpnInfo) { //General m_customGatewayPortCheckbox->setChecked(vpnInfo.m_useAssignPort); m_gatewayPortEdit->setText(vpnInfo.m_assignPort); m_customRenegotiaInrCheckbox->setChecked(vpnInfo.m_useRenegSeconds); m_renogotiaInrEdit->setText(vpnInfo.m_renegSeconds); m_compressionCheckbox->setChecked(vpnInfo.m_useCompress); m_compressionCombox->setCurrentIndex((int)vpnInfo.m_openvpnCompress); m_tcpConnCheckbox->setChecked(vpnInfo.m_useTcpLink); m_setVDevTypeCheckbox->setChecked(vpnInfo.m_setDevType); m_setVDevTypeCombox->setCurrentIndex((int)vpnInfo.m_devType); m_setVDevNameCheckbox->setChecked(vpnInfo.m_setDevName); m_setVDevNameEdit->setText(vpnInfo.m_devName); m_customMtuCheckbox->setChecked(vpnInfo.m_useTunnelMtu); m_customMtuEdit->setText(vpnInfo.m_tunnelMtu); m_customUdpFragSizeCheckbox->setChecked(vpnInfo.m_useFragmentSize); m_customUdpFragSizeEdit->setText(vpnInfo.m_fragmentSize); m_tcpMssCheckbox->setChecked(vpnInfo.m_mssfix); m_randomRemoteHostCheckbox->setChecked(vpnInfo.m_remoteRandom); m_ipv6TunLinkCheckbox->setChecked(vpnInfo.m_ipv6TunLink); m_specPingInrCheckbox->setChecked(vpnInfo.m_setPingCycle); m_specPingInrEdit->setText(vpnInfo.m_pingCycle); m_specExitPingCheckbox->setChecked(vpnInfo.m_usePingMethod); m_specExitRestarCombox->setCurrentIndex((int)vpnInfo.m_pingMethod); m_specExRePingEdit->setText(vpnInfo.m_pingMethodTime); m_acceptAuthedPaksCheckbox->setChecked(vpnInfo.m_float); m_specMaxRouteCheckbox->setChecked(vpnInfo.m_setMaxRoute); m_specMaxRouteEdit->setText(vpnInfo.m_maxRoute); //TLS settings m_serverCertCheckCombox->setCurrentIndex((int)vpnInfo.m_checkServerCa); m_subjectMatchEdit->setText(vpnInfo.m_verifyName); m_usePreviousCertCheckbox->setChecked(vpnInfo.m_useRemoteCertTls); m_usePreviousCertCombox->setCurrentIndex((int)vpnInfo.m_remoteCertType); m_verifyPeerCertCheckbox->setChecked(vpnInfo.m_useNsCertTls); m_verifyPeerCertCombox->setCurrentIndex((int)vpnInfo.m_nsCertType); m_tlsModeCombox->setCurrentIndex(vpnInfo.m_vpnTlsMode); m_keyPathEdit->setText(vpnInfo.m_vpnKeyFile); if (vpnInfo.m_vpnTlsMode == KYVPNTLS_AUTHENTICATION) { if (vpnInfo.m_vpnTlsTaDir == KEY_DIRECTION_ZERO) { m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_ZERO_INDEX); } else if (vpnInfo.m_vpnTlsTaDir == KEY_DIRECTION_ONE) { m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_ONE_INDEX); } else { m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_NONE_INDEX); } } else { m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_NONE_INDEX); } //Proxies m_proxyTypeCombox->setCurrentIndex((int)vpnInfo.m_vpnProxyType); m_proxyServerAddEdit->setText(vpnInfo.m_vpnProxyServer); m_proxyPortEdit->setText(vpnInfo.m_vpnProxyPort); m_infiniteRetryCheckbox->setChecked(vpnInfo.m_vpnProxyRetry); m_proxyUsernameEdit->setText(vpnInfo.m_vpnProxyName); m_proxyPwdEdit->setText(vpnInfo.m_vpnProxyPasswd); //Security m_customKeySizeCheckbox->setChecked(vpnInfo.m_useKeysize); m_customKeySizeEdit->setText(vpnInfo.m_keySize); m_hmacAuthCombox->setCurrentIndex((int)vpnInfo.m_hmacAuthMethod); } void VpnAdvancedPage::setStrongSwanAdiaInfo(const KyVpnConfig &vpnInfo) { m_requestInIPCheckbox->setChecked(vpnInfo.m_virtual); m_udpEncapCheckbox->setChecked(vpnInfo.m_encap); m_ipCompCheckbox->setChecked(vpnInfo.m_ipcomp); m_enablCustomCheckbox->setChecked(vpnInfo.m_proposal); if (vpnInfo.m_proposal) { m_ikeEdit->setText(vpnInfo.m_ike); m_espEdit->setText(vpnInfo.m_esp); } } bool VpnAdvancedPage::checkIsChanged(const KyVpnConfig &vpnInfo, VpnType &vpnType) { bool isChanged = false; switch (vpnType) { case L2TP: if (checkL2tpIsChanged(vpnInfo)) { isChanged = true; } break; case PPTP: if (checkPptpIsChanged(vpnInfo)) { isChanged = true; } break; case OPEN_VPN: if (checkOpenVpnIsChanged(vpnInfo)) { isChanged = true; } break; case STRONG_SWAN: if (checkStrongSwanIsChanged(vpnInfo)) { isChanged = true; } break; default: qDebug() << LOG_FLAG << "Unknow VPN Type" << vpnType; break; } return isChanged; } bool VpnAdvancedPage::checkL2tpIsChanged(const KyVpnConfig &vpnInfo) { bool isChanged = false; if (vpnInfo.m_mppeEnable != m_mppeECheckbox->isChecked() || m_mppeECombox->currentData().toInt() != vpnInfo.m_mppeEncryptMethod || vpnInfo.m_isAllowStatefulEncryption != m_useStatefulECheckbox->isChecked() || vpnInfo.m_sendPppPackage != m_sendPppEchoPkgCheckbox->isChecked()) { isChanged = true; } if (vpnInfo.m_authMethods.testFlag(KYAUTH2_PAP) != m_papAuthCheckbox->isChecked() || vpnInfo.m_authMethods.testFlag(KYAUTH2_CHAP) != m_chapAuthCheckbox->isChecked() || vpnInfo.m_authMethods.testFlag(KYAUTH2_MSCHAP) != m_mschapAuthCheckbox->isChecked() || vpnInfo.m_authMethods.testFlag(KYAUTH2_MSCHAPV2) != m_mschap2AuthCheckbox->isChecked() || vpnInfo.m_authMethods.testFlag(KYAUTH2_EAP) != m_eapAuthCheckbox->isChecked()) { isChanged = true; } if (vpnInfo.m_compressMethods.testFlag(KYCOMP_BSD) != m_bsdCompModeCheckbox->isChecked() || vpnInfo.m_compressMethods.testFlag(KYCOMP_DEFLATE) != m_defaultCompModeCheckbox->isChecked() || vpnInfo.m_compressMethods.testFlag(KYCOMP_TCP) != m_tcpCompModeCheckbox->isChecked() || vpnInfo.m_compressMethods.testFlag(KYCOMP_PROTO) != m_protocolCompModeCheckbox->isChecked() || vpnInfo.m_compressMethods.testFlag(KYCOMP_ADDR) != m_addressCompModeCheckbox->isChecked()) { isChanged = true; } if (vpnInfo.m_mru != m_mruEdit->text() || vpnInfo.m_mtu != m_mtuEdit->text()) { isChanged = true; } return isChanged; } bool VpnAdvancedPage::checkPptpIsChanged(const KyVpnConfig &vpnInfo) { bool isChanged = false; if (vpnInfo.m_mppeEnable != m_mppeECheckbox->isChecked() || m_mppeECombox->currentData().toInt() != vpnInfo.m_mppeEncryptMethod || vpnInfo.m_isAllowStatefulEncryption != m_useStatefulECheckbox->isChecked() || vpnInfo.m_sendPppPackage != m_sendPppEchoPkgCheckbox->isChecked()) { isChanged = true; } if (vpnInfo.m_authMethods.testFlag(KYAUTH2_PAP) != m_papAuthCheckbox->isChecked() || vpnInfo.m_authMethods.testFlag(KYAUTH2_CHAP) != m_chapAuthCheckbox->isChecked() || vpnInfo.m_authMethods.testFlag(KYAUTH2_MSCHAP) != m_mschapAuthCheckbox->isChecked() || vpnInfo.m_authMethods.testFlag(KYAUTH2_MSCHAPV2) != m_mschap2AuthCheckbox->isChecked() || vpnInfo.m_authMethods.testFlag(KYAUTH2_EAP) != m_eapAuthCheckbox->isChecked()) { isChanged = true; } if (vpnInfo.m_compressMethods.testFlag(KYCOMP_BSD) != m_bsdCompModeCheckbox->isChecked() || vpnInfo.m_compressMethods.testFlag(KYCOMP_DEFLATE) != m_defaultCompModeCheckbox->isChecked() || vpnInfo.m_compressMethods.testFlag(KYCOMP_TCP) != m_tcpCompModeCheckbox->isChecked()) { isChanged = true; } return isChanged; } bool VpnAdvancedPage::checkOpenVpnIsChanged(const KyVpnConfig &vpnInfo) { bool isChanged = false; //General if (vpnInfo.m_useAssignPort != m_customGatewayPortCheckbox->isChecked() || vpnInfo.m_assignPort != m_gatewayPortEdit->text()) { isChanged = true; } if (vpnInfo.m_useRenegSeconds != m_customRenegotiaInrCheckbox->isChecked() || vpnInfo.m_renegSeconds != m_renogotiaInrEdit->text()) { isChanged = true; } if (vpnInfo.m_useCompress != m_compressionCheckbox->isChecked() || vpnInfo.m_openvpnCompress != m_compressionCombox->currentData().toInt()) { isChanged = true; } if (vpnInfo.m_useTcpLink != m_tcpConnCheckbox->isChecked()) { isChanged = true; } if (vpnInfo.m_setDevType != m_setVDevTypeCheckbox->isChecked() || vpnInfo.m_devType != m_setVDevTypeCombox->currentData().toInt()) { isChanged = true; } if (vpnInfo.m_setDevName != m_setVDevNameCheckbox->isChecked() || vpnInfo.m_devName != m_setVDevNameEdit->text()) { isChanged = true; } if (vpnInfo.m_useTunnelMtu != m_customMtuCheckbox->isChecked() || vpnInfo.m_tunnelMtu != m_customMtuEdit->text()) { isChanged = true; } if (vpnInfo.m_useFragmentSize != m_customUdpFragSizeCheckbox->isChecked() || vpnInfo.m_fragmentSize != m_customUdpFragSizeEdit->text()) { isChanged = true; } if (vpnInfo.m_mssfix != m_tcpMssCheckbox->isChecked()) { isChanged = true; } if (vpnInfo.m_remoteRandom != m_randomRemoteHostCheckbox->isChecked()) { isChanged = true; } if (vpnInfo.m_ipv6TunLink != m_ipv6TunLinkCheckbox->isChecked()) { isChanged = true; } if (vpnInfo.m_setPingCycle != m_specPingInrCheckbox->isChecked() || vpnInfo.m_pingCycle != m_specPingInrEdit->text()) { isChanged = true; } if (vpnInfo.m_usePingMethod != m_specExitPingCheckbox->isChecked() || vpnInfo.m_pingMethod != m_specExitRestarCombox->currentData().toInt() || vpnInfo.m_pingMethodTime != m_specExRePingEdit->text()) { isChanged = true; } if (vpnInfo.m_float != m_acceptAuthedPaksCheckbox->isChecked()) { isChanged = true; } if (vpnInfo.m_setMaxRoute != m_specMaxRouteCheckbox->isChecked() || vpnInfo.m_maxRoute != m_specMaxRouteEdit->text()) { isChanged = true; } //TLS settings if (vpnInfo.m_checkServerCa != m_serverCertCheckCombox->currentData().toInt()) { isChanged = true; } if (vpnInfo.m_verifyName != m_subjectMatchEdit->text()) { isChanged = true; } if (vpnInfo.m_useRemoteCertTls != m_usePreviousCertCheckbox->isChecked() || vpnInfo.m_remoteCertType != m_usePreviousCertCombox->currentData().toInt()) { isChanged = true; } if (vpnInfo.m_useNsCertTls != m_verifyPeerCertCheckbox->isChecked() || vpnInfo.m_nsCertType != m_verifyPeerCertCombox->currentData().toInt()) { isChanged = true; } if (vpnInfo.m_vpnTlsMode != m_tlsModeCombox->currentData().toInt() || vpnInfo.m_vpnKeyFile != m_keyPathEdit->text() || vpnInfo.m_vpnTlsTaDir != m_keyDirectionCombox->currentData().toString()) { isChanged = true; } //Proxies int currentProxyType = m_proxyTypeCombox->currentData().toInt(); if (vpnInfo.m_vpnProxyType != currentProxyType) { isChanged = true; } if (currentProxyType == HTTP || currentProxyType == SOCKS) { if (vpnInfo.m_vpnProxyServer != m_proxyServerAddEdit->text() || vpnInfo.m_vpnProxyPort != m_proxyPortEdit->text() || vpnInfo.m_vpnProxyRetry != m_infiniteRetryCheckbox->isChecked()) { isChanged = true; } if (currentProxyType == HTTP) { if (vpnInfo.m_vpnProxyName != m_proxyUsernameEdit->text() || vpnInfo.m_vpnProxyPasswd != m_proxyPwdEdit->text()) { isChanged = true; } } } //Security if (vpnInfo.m_useKeysize != m_customKeySizeCheckbox->isChecked() || vpnInfo.m_keySize != m_customKeySizeEdit->text() || vpnInfo.m_hmacAuthMethod != m_hmacAuthCombox->currentData().toInt()) { isChanged = true; } return isChanged; } bool VpnAdvancedPage::checkStrongSwanIsChanged(const KyVpnConfig &vpnInfo) { bool isChanged = false; if (vpnInfo.m_virtual != m_requestInIPCheckbox->isChecked() || vpnInfo.m_encap != m_udpEncapCheckbox->isChecked() || vpnInfo.m_ipcomp != m_ipCompCheckbox->isChecked() || vpnInfo.m_proposal != m_enablCustomCheckbox->isChecked()) { isChanged = true; } if (m_enablCustomCheckbox->isChecked()) { if (vpnInfo.m_ike != m_ikeEdit->text() || vpnInfo.m_esp != m_espEdit->text()) { isChanged = true; } } return isChanged; } void VpnAdvancedPage::updateL2tpOrPptpAdiaInfo(KyVpnConfig &vpnInfo) { vpnInfo.m_mppeEnable = m_mppeECheckbox->isChecked(); vpnInfo.m_mppeEncryptMethod = (KyMPPEMethod)m_mppeECombox->currentData().toInt(); vpnInfo.m_isAllowStatefulEncryption = m_useStatefulECheckbox->isChecked(); vpnInfo.m_sendPppPackage = m_sendPppEchoPkgCheckbox->isChecked(); vpnInfo.m_authMethods.setFlag(KYAUTH2_PAP, m_papAuthCheckbox->isChecked()); vpnInfo.m_authMethods.setFlag(KYAUTH2_CHAP, m_chapAuthCheckbox->isChecked()); vpnInfo.m_authMethods.setFlag(KYAUTH2_MSCHAP, m_mschapAuthCheckbox->isChecked()); vpnInfo.m_authMethods.setFlag(KYAUTH2_MSCHAPV2, m_mschap2AuthCheckbox->isChecked()); vpnInfo.m_authMethods.setFlag(KYAUTH2_EAP, m_eapAuthCheckbox->isChecked()); vpnInfo.m_compressMethods.setFlag(KYCOMP_BSD, m_bsdCompModeCheckbox->isChecked()); vpnInfo.m_compressMethods.setFlag(KYCOMP_DEFLATE, m_defaultCompModeCheckbox->isChecked()); vpnInfo.m_compressMethods.setFlag(KYCOMP_TCP, m_tcpCompModeCheckbox->isChecked()); if (!m_compModeListWidget->item(COMP_MODE_PROTOCOL)->isHidden() && !m_compModeListWidget->item(COMP_MODE_ADDRESS)->isHidden()) { vpnInfo.m_compressMethods.setFlag(KYCOMP_PROTO, m_protocolCompModeCheckbox->isChecked()); vpnInfo.m_compressMethods.setFlag(KYCOMP_ADDR, m_addressCompModeCheckbox->isChecked()); vpnInfo.m_mru = m_mruEdit->text(); vpnInfo.m_mtu = m_mtuEdit->text(); qDebug() << LOG_FLAG << "Update L2TP advanced info finished"; } else { qDebug() << LOG_FLAG << "Update PPTP advanced info finished"; } } void VpnAdvancedPage::updateOpenVpnAdiaInfo(KyVpnConfig &vpnInfo) { //General vpnInfo.m_useAssignPort = m_customGatewayPortCheckbox->isChecked(); vpnInfo.m_assignPort = m_gatewayPortEdit->text(); vpnInfo.m_useRenegSeconds = m_customRenegotiaInrCheckbox->isChecked(); vpnInfo.m_renegSeconds = m_renogotiaInrEdit->text(); vpnInfo.m_useCompress = m_compressionCheckbox->isChecked(); vpnInfo.m_openvpnCompress = (KyCompressMethod2)m_compressionCombox->currentData().toInt(); vpnInfo.m_useTcpLink = m_tcpConnCheckbox->isChecked(); vpnInfo.m_setDevType = m_setVDevTypeCheckbox->isChecked(); vpnInfo.m_devType = (KyVirtualDeviceType)m_setVDevTypeCombox->currentData().toInt(); vpnInfo.m_setDevName = m_setVDevNameCheckbox->isChecked(); vpnInfo.m_devName = m_setVDevNameEdit->text(); vpnInfo.m_useTunnelMtu = m_customMtuCheckbox->isChecked(); vpnInfo.m_tunnelMtu = m_customMtuEdit->text(); vpnInfo.m_useFragmentSize = m_customUdpFragSizeCheckbox->isChecked(); vpnInfo.m_fragmentSize = m_customUdpFragSizeEdit->text(); vpnInfo.m_mssfix = m_tcpMssCheckbox->isChecked(); vpnInfo.m_remoteRandom = m_randomRemoteHostCheckbox->isChecked(); vpnInfo.m_ipv6TunLink = m_ipv6TunLinkCheckbox->isChecked(); vpnInfo.m_setPingCycle = m_specPingInrCheckbox->isChecked(); vpnInfo.m_pingCycle = m_specPingInrEdit->text(); vpnInfo.m_usePingMethod = m_specExitPingCheckbox->isChecked(); vpnInfo.m_pingMethod = (KyVpnPingMethod)m_specExitRestarCombox->currentData().toInt(); vpnInfo.m_pingMethodTime = m_specExRePingEdit->text(); vpnInfo.m_float = m_acceptAuthedPaksCheckbox->isChecked(); vpnInfo.m_setMaxRoute = m_specMaxRouteCheckbox->isChecked(); vpnInfo.m_maxRoute = m_specMaxRouteEdit->text(); //TLS settings vpnInfo.m_checkServerCa = (KyVpnCheckServerMethod)m_serverCertCheckCombox->currentData().toInt(); vpnInfo.m_verifyName = m_subjectMatchEdit->text(); vpnInfo.m_useRemoteCertTls = m_usePreviousCertCheckbox->isChecked(); vpnInfo.m_remoteCertType = (KyVpnCertType)m_usePreviousCertCombox->currentData().toInt(); vpnInfo.m_useNsCertTls = m_verifyPeerCertCheckbox->isChecked(); vpnInfo.m_nsCertType = (KyVpnCertType)m_verifyPeerCertCombox->currentData().toInt(); vpnInfo.m_vpnTlsMode = (KyVpnTlsMode)m_tlsModeCombox->currentData().toInt(); vpnInfo.m_vpnKeyFile = m_keyPathEdit->text(); vpnInfo.m_vpnTlsTaDir = m_keyDirectionCombox->currentData().toString(); //Proxies vpnInfo.m_vpnProxyType = (KyVpnProxyType)m_proxyTypeCombox->currentData().toInt(); vpnInfo.m_vpnProxyServer = m_proxyServerAddEdit->text(); vpnInfo.m_vpnProxyPort = m_proxyPortEdit->text(); vpnInfo.m_vpnProxyRetry = m_infiniteRetryCheckbox->isChecked(); vpnInfo.m_vpnProxyName = m_proxyUsernameEdit->text(); vpnInfo.m_vpnProxyPasswd = m_proxyPwdEdit->text(); //Security vpnInfo.m_useKeysize = m_customKeySizeCheckbox->isChecked(); vpnInfo.m_keySize = m_customKeySizeEdit->text(); vpnInfo.m_hmacAuthMethod = (KyHMACAuthMethod)m_hmacAuthCombox->currentData().toInt(); qDebug() << LOG_FLAG << "Update open VPN advanced info finished"; } void VpnAdvancedPage::updateStrongSwanAdiaInfo(KyVpnConfig &vpnInfo) { vpnInfo.m_virtual = m_requestInIPCheckbox->isChecked(); vpnInfo.m_encap = m_udpEncapCheckbox->isChecked(); vpnInfo.m_ipcomp = m_ipCompCheckbox->isChecked(); vpnInfo.m_proposal = m_enablCustomCheckbox->isChecked(); vpnInfo.m_ike = m_ikeEdit->text(); vpnInfo.m_esp = m_espEdit->text(); qDebug() << LOG_FLAG << "update strong-swan advanced info finished"; } void VpnAdvancedPage::setVpnAdvancedPage(const VpnType &type) { switch (type) { case L2TP: showL2tpAdiaPage(); break; case OPEN_VPN: showOpenVpnAdiaPage(); break; case PPTP: showPptpAdiaPage(); break; case STRONG_SWAN: showSSwanAdiaPage(); break; default: break; } } void VpnAdvancedPage::paintEvent(QPaintEvent *event) { if (m_authModeListWidget) { QPalette mpal(m_authModeListWidget->palette()); mpal.setColor(QPalette::Base, qApp->palette().base().color()); mpal.setColor(QPalette::AlternateBase, qApp->palette().alternateBase().color()); m_authModeListWidget->setBackgroundRole(QPalette::Base); m_authModeListWidget->setAlternatingRowColors(true); m_authModeListWidget->setPalette(mpal); } if (m_compModeListWidget) { QPalette mpal(m_compModeListWidget->palette()); mpal.setColor(QPalette::Base, qApp->palette().base().color()); mpal.setColor(QPalette::AlternateBase, qApp->palette().alternateBase().color()); m_compModeListWidget->setBackgroundRole(QPalette::Base); m_compModeListWidget->setAlternatingRowColors(true); m_compModeListWidget->setPalette(mpal); } if (m_optionsListWidget) { QPalette mpal(m_optionsListWidget->palette()); mpal.setColor(QPalette::Base, qApp->palette().base().color()); mpal.setColor(QPalette::AlternateBase, qApp->palette().alternateBase().color()); m_optionsListWidget->setBackgroundRole(QPalette::Base); m_optionsListWidget->setAlternatingRowColors(true); m_optionsListWidget->setPalette(mpal); } } void VpnAdvancedPage::initUi() { m_defaultAdiaFrame = new QFrame(this); m_openVpnAdiaFrame = new QFrame(this); m_sSwanAdiaFrame = new QFrame(this); initDefaultAdiaFrame(); initOpenVpnAdiaFrame(); initSSwanAdiaFrame(); QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(NO_LAYOUT_MARGINS); mainLayout->setSpacing(NO_SPACE); mainLayout->addWidget(m_defaultAdiaFrame); mainLayout->addWidget(m_openVpnAdiaFrame); mainLayout->addWidget(m_sSwanAdiaFrame); mainLayout->addSpacing(3); mainLayout->addStretch(); } void VpnAdvancedPage::initConnect() { connect(m_mppeECheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_mppeECombox->setEnabled(state); m_useStatefulECheckbox->setEnabled(state); m_papAuthCheckbox->setEnabled(!state); m_chapAuthCheckbox->setEnabled(!state); m_eapAuthCheckbox->setEnabled(!state); }); //strong-Swan connect(m_enablCustomCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_ikeEspFrame->setEnabled(state); }); //open VPN General connect(m_customGatewayPortCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_gatewayPortEdit->setEnabled(state); }); connect(m_customRenegotiaInrCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_renogotiaInrEdit->setEnabled(state); }); connect(m_compressionCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_compressionCombox->setEnabled(state); }); connect(m_compressionCheckbox, &QCheckBox::stateChanged, this, [=](int state) { if (state == Qt::CheckState::Unchecked) { m_compressionCombox->setCurrentIndex(KYCOMP2_LZODISABLE); } }); connect(m_setVDevTypeCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_setVDevTypeCombox->setEnabled(state); }); connect(m_setVDevNameCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_setVDevNameEdit->setEnabled(state); }); connect(m_customMtuCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_customMtuEdit->setEnabled(state); }); connect(m_customUdpFragSizeCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_customUdpFragSizeEdit->setEnabled(state); }); connect(m_specPingInrCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_specPingInrEdit->setEnabled(state); }); connect(m_specExitPingCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_specExitRestarCombox->setEnabled(state); }); connect(m_specExitPingCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_specExRePingEdit->setEnabled(state); }); connect(m_specMaxRouteCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_specMaxRouteEdit->setEnabled(state); }); //open VPN TLS settings connect(m_serverCertCheckCombox, QOverload::of(&QComboBox::currentIndexChanged), this, [=](int index) { if (index == (int)KYCHECKSERVER_NONE) { m_subjectMatchEdit->setEnabled(false); } else { m_subjectMatchEdit->setEnabled(true); } }); connect(m_tlsModeCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &VpnAdvancedPage::onTlsModeComboxIndexChanged); connect(m_usePreviousCertCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_usePreviousCertCombox->setEnabled(state); }); connect(m_verifyPeerCertCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_verifyPeerCertCombox->setEnabled(state); }); //open VPN proxies connect(m_proxyTypeCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &VpnAdvancedPage::onProxyTypeComboxIndexChanged); //open VPN security connect(m_customKeySizeCheckbox, &QCheckBox::stateChanged, this, [=](int state) { m_customKeySizeEdit->setEnabled(state); }); connect(m_mruEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_mtuEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_gatewayPortEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_renogotiaInrEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_setVDevNameEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_customMtuEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_customUdpFragSizeEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_specPingInrEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_specExRePingEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_subjectMatchEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_specMaxRouteEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_keyPathEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_proxyServerAddEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_proxyPortEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_proxyUsernameEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_proxyPwdEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_customKeySizeEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_ikeEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_espEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_customGatewayPortCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_customRenegotiaInrCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_setVDevNameCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_customMtuCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_customUdpFragSizeCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_specPingInrCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_specExitPingCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_specMaxRouteCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_customKeySizeCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_enablCustomCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); connect(m_serverCertCheckCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfConfirmBtn())); connect(m_tlsModeCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfConfirmBtn())); connect(m_proxyTypeCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfConfirmBtn())); connect(m_keyPathChooseBtn, &QPushButton::clicked, this, &VpnAdvancedPage::onKeyPathButtonClicked); } void VpnAdvancedPage::initDefaultAdiaFrame() { /**********控件**********/ m_mppeECheckbox = new QCheckBox(this); m_useStatefulECheckbox = new QCheckBox(this); m_sendPppEchoPkgCheckbox = new QCheckBox(this); m_authModeLabel = new QLabel(this); m_compModeLabel = new QLabel(this); m_mruLabel = new QLabel(this); m_mtuLabel = new QLabel(this); m_mppeECombox = new QComboBox(this); m_authModeListWidget = new QListWidget(this); m_papAuthCheckbox = new QCheckBox(this); m_chapAuthCheckbox = new QCheckBox(this); m_mschapAuthCheckbox = new QCheckBox(this); m_mschap2AuthCheckbox = new QCheckBox(this); m_eapAuthCheckbox = new QCheckBox(this); m_compModeListWidget = new QListWidget(this); m_bsdCompModeCheckbox = new QCheckBox(this); m_defaultCompModeCheckbox = new QCheckBox(this); m_tcpCompModeCheckbox = new QCheckBox(this); m_protocolCompModeCheckbox = new QCheckBox(this); m_addressCompModeCheckbox = new QCheckBox(this); m_mruFrame = new QFrame(this); m_mruEdit = new QLineEdit(this); m_mtuEdit = new QLineEdit(this); m_authModeListWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus); m_authModeListWidget->setFrameShape(QFrame::Shape::StyledPanel); addListItem(m_authModeListWidget, m_papAuthCheckbox); addListItem(m_authModeListWidget, m_chapAuthCheckbox); addListItem(m_authModeListWidget, m_mschapAuthCheckbox); addListItem(m_authModeListWidget, m_mschap2AuthCheckbox); addListItem(m_authModeListWidget, m_eapAuthCheckbox); m_compModeListWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus); m_compModeListWidget->setFrameShape(QFrame::Shape::StyledPanel); addListItem(m_compModeListWidget, m_bsdCompModeCheckbox); addListItem(m_compModeListWidget, m_defaultCompModeCheckbox); addListItem(m_compModeListWidget, m_tcpCompModeCheckbox); addListItem(m_compModeListWidget, m_protocolCompModeCheckbox); addListItem(m_compModeListWidget, m_addressCompModeCheckbox); /**********布局**********/ QVBoxLayout *defaultAdiaVLayout = new QVBoxLayout(m_defaultAdiaFrame); defaultAdiaVLayout->setContentsMargins(NO_LAYOUT_MARGINS); defaultAdiaVLayout->setSpacing(LAYOUT_SPACING_SMALL); QFrame *secuFrame= new QFrame(m_defaultAdiaFrame); QFormLayout *secuLayout = new QFormLayout(secuFrame); secuLayout->setContentsMargins(NO_LAYOUT_MARGINS); secuLayout->setVerticalSpacing(LAYOUT_SPACING_SMALL); secuLayout->setHorizontalSpacing(HOR_LAYOUT_SPACING); secuLayout->addRow(m_mppeECheckbox, m_mppeECombox); secuLayout->addRow(m_useStatefulECheckbox); secuLayout->addRow(m_sendPppEchoPkgCheckbox); m_mppeECheckbox->setMinimumWidth(MIN_LABEL_WIDTH); QHBoxLayout *mruHLayout = new QHBoxLayout(m_mruFrame); mruHLayout->setContentsMargins(0, 16, 0, 0); mruHLayout->setSpacing(HOR_LAYOUT_SPACING); mruHLayout->addWidget(m_mruLabel); mruHLayout->addWidget(m_mruEdit); mruHLayout->addStretch(); mruHLayout->addWidget(m_mtuLabel); mruHLayout->addWidget(m_mtuEdit); m_mruEdit->setFixedWidth(MIN_EDIT_WIDTH); m_mtuEdit->setFixedWidth(MIN_EDIT_WIDTH); defaultAdiaVLayout->addWidget(secuFrame); defaultAdiaVLayout->addSpacing(4); defaultAdiaVLayout->addWidget(m_authModeLabel); defaultAdiaVLayout->addWidget(m_authModeListWidget); defaultAdiaVLayout->addSpacing(LAYOUT_ADD_SPACING); defaultAdiaVLayout->addWidget(m_compModeLabel); defaultAdiaVLayout->addWidget(m_compModeListWidget); defaultAdiaVLayout->addWidget(m_mruFrame); m_authModeListWidget->setFixedHeight(LISTWIDGET_HEIGHT); m_compModeListWidget->setFixedHeight(LISTWIDGET_HEIGHT); /**********控件显示**********/ m_mppeECheckbox->setText(tr("MPPE encryption algorithm:")); //MPPE加密算法: m_useStatefulECheckbox->setText(tr("Use Stateful encryption")); //使用有状态加密 m_sendPppEchoPkgCheckbox->setText(tr("Send PPP echo packets")); //发送PPP回显包 m_authModeLabel->setText(tr("Authentication Mode:")); //认证方式: m_papAuthCheckbox->setText(tr("PAP authentication")); //PAP认证 m_chapAuthCheckbox->setText(tr("CHAP authentication")); //CHAP认证 m_mschapAuthCheckbox->setText(tr("MSCHAP authentication")); //MSCHAP认证 m_mschap2AuthCheckbox->setText(tr("MSCHAP2 authentication")); //MSCHAP2认证 m_eapAuthCheckbox->setText(tr("EAP authentication")); //EAP认证 m_compModeLabel->setText(tr("Compression Mode:")); //压缩方式: m_bsdCompModeCheckbox->setText(tr("Allow BSD data compression")); //允许BSD压缩 m_defaultCompModeCheckbox->setText(tr("Allow Default data compression")); //允许Default压缩 m_tcpCompModeCheckbox->setText(tr("Allow TCP header compression")); //允许TCP头压缩 m_protocolCompModeCheckbox->setText(tr("Use protocol field compression negotiation")); //使用协议域压缩协商 m_addressCompModeCheckbox->setText(tr("Use Address/Control compression")); //使用地址/控制压缩 m_mruLabel->setText("MRU"); m_mtuLabel->setText("MTU"); m_mruEdit->setText("0"); m_mtuEdit->setText("0"); m_mppeECombox->addItem(tr("All Available"), KYMPPE_DEFAULT); //任意 m_mppeECombox->addItem(tr("128-bit"), KYMPPE_REQUIRE128); //128位 m_mppeECombox->addItem(tr("40-bit"), KYMPPE_REQUIRE40); //40位 //控件输入格式限制 QRegularExpression rxNumber("^[0-9]+$"); m_mruEdit->setValidator(new QRegularExpressionValidator(rxNumber, this)); m_mtuEdit->setValidator(new QRegularExpressionValidator(rxNumber, this)); m_mruEdit->setMaxLength(MAX_MRU_LENGTH); m_mtuEdit->setMaxLength(MAX_MRU_LENGTH); } void VpnAdvancedPage::initOpenVpnAdiaFrame() { /**********控件**********/ //General QLabel *generalLabel = new QLabel(m_openVpnAdiaFrame); m_customGatewayPortCheckbox = new QCheckBox(this); m_customRenegotiaInrCheckbox = new QCheckBox(this); m_compressionCheckbox = new QCheckBox(this); m_tcpConnCheckbox = new QCheckBox(this); m_setVDevTypeCheckbox = new QCheckBox(this); m_setVDevNameCheckbox = new QCheckBox(this); m_customMtuCheckbox = new QCheckBox(this); m_customUdpFragSizeCheckbox = new QCheckBox(this); m_tcpMssCheckbox = new QCheckBox(this); m_randomRemoteHostCheckbox = new QCheckBox(this); m_ipv6TunLinkCheckbox = new QCheckBox(this); m_specPingInrCheckbox = new QCheckBox(this); m_specExitPingCheckbox = new QCheckBox(this); m_acceptAuthedPaksCheckbox = new QCheckBox(this); m_specMaxRouteCheckbox = new QCheckBox(this); m_gatewayPortEdit = new QLineEdit(this); m_renogotiaInrEdit = new QLineEdit(this); m_setVDevNameEdit = new QLineEdit(this); m_customMtuEdit = new QLineEdit(this); m_customUdpFragSizeEdit = new QLineEdit(this); m_specPingInrEdit = new QLineEdit(this); m_specExRePingEdit = new QLineEdit(this); m_specMaxRouteEdit = new QLineEdit(this); m_compressionCombox = new QComboBox(this); m_setVDevTypeCombox = new QComboBox(this); m_specExitRestarCombox = new QComboBox(this); m_customRenoInrLabel = new FixLabel(this); m_customMtuLabel = new FixLabel(this); m_acceptAuthedPaksLabel = new FixLabel(this); m_customUdpLabel = new FixLabel(this); //TLS settings QLabel *tlsSettingLabel = new QLabel(m_openVpnAdiaFrame); QLabel *serverCertCheckLabel = new QLabel(m_openVpnAdiaFrame); QLabel *tlsModeLabel = new QLabel(m_openVpnAdiaFrame); FixLabel *usePreviousCertLabel = new FixLabel(m_openVpnAdiaFrame); FixLabel *verifyPeerCertLabel = new FixLabel(m_openVpnAdiaFrame); m_subjectMatchLabel = new QLabel(this); m_keyPathLabel = new QLabel(this); m_keyDirectionLabel = new QLabel(this); m_subjectMatchEdit = new QLineEdit(this); m_keyPathEdit = new QLineEdit(this); m_keyPathChooseBtn = new QPushButton(this); m_usePreviousCertCheckbox = new QCheckBox(this); m_verifyPeerCertCheckbox = new QCheckBox(this); m_serverCertCheckCombox = new QComboBox(this); m_usePreviousCertCombox = new QComboBox(this); m_verifyPeerCertCombox = new QComboBox(this); m_tlsModeCombox = new QComboBox(this); m_keyDirectionCombox = new QComboBox(this); //Proxies QLabel *proxiesLabel = new QLabel(m_openVpnAdiaFrame); QLabel *proxyTypeLabel = new QLabel(m_openVpnAdiaFrame); m_proxyServerAddLabel = new QLabel(this); m_proxyPortLabel = new QLabel(this); m_proxyUsernameLabel = new QLabel(this); m_proxyPwdLabel = new QLabel(this); m_proxyTypeCombox = new QComboBox(this); m_infiniteRetryCheckbox = new QCheckBox(this); m_proxyServerAddEdit = new QLineEdit(this); m_proxyPortEdit = new QLineEdit(this); m_proxyUsernameEdit = new QLineEdit(this); m_proxyPwdEdit = new KPasswordEdit(this); m_proxyPwdEdit->setClearButtonEnabled(false); //Security QLabel *securityLabel = new QLabel(m_openVpnAdiaFrame); QLabel *hmacLabel = new QLabel(m_openVpnAdiaFrame); m_customKeySizeCheckbox = new QCheckBox(this); m_customKeySizeEdit = new QLineEdit(this); m_hmacAuthCombox = new QComboBox(this); /**********布局**********/ QVBoxLayout *openVpnAdiaVLayout = new QVBoxLayout(m_openVpnAdiaFrame); openVpnAdiaVLayout->setContentsMargins(NO_LAYOUT_MARGINS); //General QFrame *generalFrame = new QFrame(m_openVpnAdiaFrame); QFormLayout *generalLayout = new QFormLayout(generalFrame); QWidget *customRenoInrWidget = new QWidget(this); initCheckWidget(m_customRenegotiaInrCheckbox, m_customRenoInrLabel, customRenoInrWidget); QWidget *customMtuWidget = new QWidget(this); initCheckWidget(m_customMtuCheckbox, m_customMtuLabel, customMtuWidget); QWidget *customUdpWidget = new QWidget(this); initCheckWidget(m_customUdpFragSizeCheckbox, m_customUdpLabel, customUdpWidget); QWidget *acceptAuthWidget = new QWidget(this); initCheckWidget(m_acceptAuthedPaksCheckbox, m_acceptAuthedPaksLabel, acceptAuthWidget); QWidget *exitRestarWidget = new QWidget(this); QHBoxLayout *exitRestarLayout = new QHBoxLayout(exitRestarWidget); exitRestarLayout->setContentsMargins(NO_LAYOUT_MARGINS); exitRestarLayout->addWidget(m_specExitRestarCombox); exitRestarLayout->addWidget(m_specExRePingEdit); generalLayout->setContentsMargins(NO_LAYOUT_MARGINS); generalLayout->addRow(m_customGatewayPortCheckbox, m_gatewayPortEdit); generalLayout->addRow(customRenoInrWidget, m_renogotiaInrEdit); generalLayout->addRow(m_compressionCheckbox, m_compressionCombox); generalLayout->addRow(m_tcpConnCheckbox); generalLayout->addRow(m_setVDevTypeCheckbox, m_setVDevTypeCombox); generalLayout->addRow(m_setVDevNameCheckbox, m_setVDevNameEdit); generalLayout->addRow(customMtuWidget, m_customMtuEdit); generalLayout->addRow(customUdpWidget, m_customUdpFragSizeEdit); generalLayout->addRow(m_tcpMssCheckbox); generalLayout->addRow(m_randomRemoteHostCheckbox); generalLayout->addRow(m_ipv6TunLinkCheckbox); generalLayout->addRow(m_specPingInrCheckbox, m_specPingInrEdit); generalLayout->addRow(m_specExitPingCheckbox, exitRestarWidget); generalLayout->addRow(acceptAuthWidget); generalLayout->addRow(m_specMaxRouteCheckbox, m_specMaxRouteEdit); //TLS settings QFrame *tlsSettingsFrame = new QFrame(m_openVpnAdiaFrame); QFormLayout *tlsLayout = new QFormLayout(tlsSettingsFrame); QWidget *usePreviousCertWidget = new QWidget(this); initCheckWidget(m_usePreviousCertCheckbox, usePreviousCertLabel, usePreviousCertWidget); QWidget *verifyPeerCertWidget = new QWidget(this); initCheckWidget(m_verifyPeerCertCheckbox, verifyPeerCertLabel, verifyPeerCertWidget); QWidget *keyfileWidget = new QWidget(this); QGridLayout *keyfileLayout = new QGridLayout(keyfileWidget); keyfileLayout->setContentsMargins(NO_LAYOUT_MARGINS); keyfileLayout->addWidget(m_keyPathLabel, 0, 0); keyfileLayout->addWidget(m_keyPathEdit, 0, 1); keyfileLayout->addWidget(m_keyPathChooseBtn, 0, 2); keyfileLayout->addWidget(m_keyDirectionLabel, 1, 0); keyfileLayout->addWidget(m_keyDirectionCombox, 1, 1, 1, 2); m_keyDirectionLabel->setMinimumWidth(MIN_LABEL_WIDTH); tlsLayout->setContentsMargins(NO_LAYOUT_MARGINS); tlsLayout->addRow(serverCertCheckLabel, m_serverCertCheckCombox); tlsLayout->addRow(m_subjectMatchLabel, m_subjectMatchEdit); tlsLayout->addRow(usePreviousCertWidget, m_usePreviousCertCombox); tlsLayout->addRow(verifyPeerCertWidget, m_verifyPeerCertCombox); tlsLayout->addRow(tlsModeLabel, m_tlsModeCombox); tlsLayout->addRow(keyfileWidget); //Proxies QFrame *proxiesFrame = new QFrame(m_openVpnAdiaFrame); QFormLayout *proxiesLayout = new QFormLayout(proxiesFrame); proxiesLayout->setContentsMargins(NO_LAYOUT_MARGINS); proxiesLayout->addRow(proxyTypeLabel, m_proxyTypeCombox); proxiesLayout->addRow(m_proxyServerAddLabel, m_proxyServerAddEdit); proxiesLayout->addRow(m_proxyPortLabel, m_proxyPortEdit); proxiesLayout->addRow(nullptr, m_infiniteRetryCheckbox); proxiesLayout->addRow(m_proxyUsernameLabel, m_proxyUsernameEdit); proxiesLayout->addRow(m_proxyPwdLabel, m_proxyPwdEdit); m_proxyUsernameLabel->setMinimumWidth(MIN_LABEL_WIDTH); //Security QFrame *securityFrame = new QFrame(m_openVpnAdiaFrame); QFormLayout *securityLayout = new QFormLayout(securityFrame); securityLayout->setContentsMargins(NO_LAYOUT_MARGINS); securityLayout->addRow(m_customKeySizeCheckbox, m_customKeySizeEdit); securityLayout->addRow(hmacLabel, m_hmacAuthCombox); //all openVpnAdiaVLayout->setSpacing(LAYOUT_SPACING_SMALL); openVpnAdiaVLayout->addWidget(generalLabel); openVpnAdiaVLayout->addWidget(generalFrame); openVpnAdiaVLayout->addSpacing(VLAYOUT_ADD_SPACING); openVpnAdiaVLayout->addWidget(tlsSettingLabel); openVpnAdiaVLayout->addWidget(tlsSettingsFrame); openVpnAdiaVLayout->addSpacing(VLAYOUT_ADD_SPACING); openVpnAdiaVLayout->addWidget(proxiesLabel); openVpnAdiaVLayout->addWidget(proxiesFrame); openVpnAdiaVLayout->addSpacing(VLAYOUT_ADD_SPACING); openVpnAdiaVLayout->addWidget(securityLabel); openVpnAdiaVLayout->addWidget(securityFrame); /**********控件显示**********/ m_customGatewayPortCheckbox->setText(tr("Use custom gateway port")); //使用自定义网关端口 m_compressionCheckbox->setText(tr("Use compression")); //使用压缩 m_tcpConnCheckbox->setText(tr("Use a TCP connection")); //使用TCP连接 m_setVDevTypeCheckbox->setText(tr("Set virtual device type")); //设置虚拟设备类型 m_setVDevNameCheckbox->setText(tr("Set virtual device name")); //设置虚拟设备名称 m_tcpMssCheckbox->setText(tr("Limit TCP Maximum Segment Size(MSS)")); //限制TCP最大段尺寸(MSS) m_randomRemoteHostCheckbox->setText(tr("Randomize remote hosts")); //随机化远程主机 m_ipv6TunLinkCheckbox->setText(tr("IPv6 tun link")); //IPv6 tun连接 m_specPingInrCheckbox->setText(tr("Specify ping interval")); //指定ping周期 m_specExitPingCheckbox->setText(tr("Specify exit or restart ping")); //指定退出或重启的Ping m_specMaxRouteCheckbox->setText(tr("Specify max routes")); //指定路由上限 m_infiniteRetryCheckbox->setText(tr("Infinite retry on error")); //出错时无限重试 m_customKeySizeCheckbox->setText(tr("Use custom key size")); //使用自定义密钥大小 m_keyPathChooseBtn->setText(tr("Choose")); //选择 m_customRenoInrLabel->setFixedWidth(MAX_LABEL_WIDTH); m_customRenoInrLabel->setLabelText(tr("Use custom renegotiation interval")); //使用自定义重协商间隔 m_customMtuLabel->setFixedWidth(MAX_LABEL_WIDTH); m_customMtuLabel->setLabelText(tr("Use custom tunnel Maximum Transmission Umit(MTU)")); //使用自定义隧道最大单元传输(MTU) m_customUdpLabel->setFixedWidth(MAX_LABEL_WIDTH); m_customUdpLabel->setLabelText(tr("Use custom UDP fragment size")); //使用自定义UDP分片大小 m_acceptAuthedPaksLabel->setFixedWidth(440);//文本显示宽度 m_acceptAuthedPaksLabel->setLabelText(tr("Accept authenticated packets from any address (Float)")); //接受来自任何地址(Float)已通过身份验证的数据包 m_subjectMatchLabel->setText(tr("Subject Match")); //主题匹配 m_keyPathLabel->setText(tr("Key File")); //密钥文件 m_keyDirectionLabel->setText(tr("Key Direction")); //密钥方向 m_proxyServerAddLabel->setText(tr("Server Address")); //服务器地址 m_proxyPortLabel->setText(tr("Port")); //端口 m_proxyUsernameLabel->setText(tr("Proxy USername")); //代理用户名 m_proxyPwdLabel->setText(tr("Proxy Password")); //代理密码 generalLabel->setText(tr("General")); //常规 tlsSettingLabel->setText(tr("TLS settings")); serverCertCheckLabel->setText(tr("Server Certificate Check")); //服务器证书检验 usePreviousCertLabel->setFixedWidth(MAX_LABEL_WIDTH); usePreviousCertLabel->setLabelText(tr("Use the previous authentication end (server) certificate")); //使用前面验证端(服务器)证书 verifyPeerCertLabel->setFixedWidth(MAX_LABEL_WIDTH); verifyPeerCertLabel->setLabelText(tr("Verify peer (server) certificate nsCertType specification")); //验证对等点(服务器)证书nsCertType指定 tlsModeLabel->setText(tr("Mode")); proxiesLabel->setText(tr("Proxies")); proxyTypeLabel->setText(tr("Proxy Type")); securityLabel->setText(tr("Security")); hmacLabel->setText(tr("HMAC Authentication")); //HMAC认证 hmacLabel->setFixedWidth(268); //调整控件对齐=MAX_LABEL_WIDTH+28 QFont font = generalLabel->font(); font.setWeight(QFont::Weight::Medium); generalLabel->setFont(font); tlsSettingLabel->setFont(font); proxiesLabel->setFont(font); securityLabel->setFont(font); m_setVDevNameEdit->setPlaceholderText(tr("Input content")); //输入内容 m_compressionCombox->addItem(tr("No"), KYCOMP2_LZODISABLE); //否 m_compressionCombox->addItem("LZO", KYCOMP2_LZO); m_compressionCombox->addItem("LZ4", KYCOMP2_LZ4); m_compressionCombox->addItem("LZ4 v2", KYCOMP2_LZ4V2); m_compressionCombox->addItem(tr("Self-adaption"), KYCOMP2_LZOADAPTIVE); //自适应 m_compressionCombox->addItem(tr("Automatic"), KYCOMP2_AUTO); //自动 m_setVDevTypeCombox->addItem("TUN", KYVIRDEVTYPE_TUN); m_setVDevTypeCombox->addItem("TAP", KYVIRDEVTYPE_TAP); m_specExitRestarCombox->addItem(tr("Exit"), KYVPNPING_EXIT); //退出 m_specExitRestarCombox->addItem(tr("Restart"), KYVPNPING_RESTART); //重启 m_serverCertCheckCombox->addItem(tr("Don't verify certificate identification"), KYCHECKSERVER_NONE); //不验证证书标识 m_serverCertCheckCombox->addItem(tr("Verify the entire subject exactly"), KYCHECKSERVER_ENTIRETHEME); //确切地验证整个主题 m_serverCertCheckCombox->addItem(tr("Verify name exactly"), KYCHECKSERVER_ENTIRENAME); //精确验证名称 m_serverCertCheckCombox->addItem(tr("Verify name by prefix"), KYCHECKSERVER_PRENAME); //按前缀验证名称 m_usePreviousCertCombox->addItem(tr("Server"), KYVPNCERT_SERVER); m_usePreviousCertCombox->addItem(tr("Client"), KYVPNCERT_CLIENT); m_verifyPeerCertCombox->addItem(tr("Server"), KYVPNCERT_SERVER); m_verifyPeerCertCombox->addItem(tr("Client"), KYVPNCERT_CLIENT); m_tlsModeCombox->addItem(tr("None"), TlsMode::NONE); //无 m_tlsModeCombox->addItem(tr("TLS-Certification"), TLS_CERT); //TLS-认证 m_tlsModeCombox->addItem(tr("TLS-Encryption"), TLS_ENCRYPTION); //TLS-加密 m_keyDirectionCombox->addItem(tr("None"), KEY_DIRECTION_NONE); //无 m_keyDirectionCombox->addItem("0", KEY_DIRECTION_ZERO); m_keyDirectionCombox->addItem("1", KEY_DIRECTION_ONE); m_proxyTypeCombox->addItem(tr("Not Required"), NO); //不需要 m_proxyTypeCombox->addItem("HTTP", HTTP); m_proxyTypeCombox->addItem("SOCKS", SOCKS); m_hmacAuthCombox->addItem(tr("Default"), KYHMACAUTH_DEFAULT); //默认 m_hmacAuthCombox->addItem(tr("None"), KYHMACAUTH_NONE); //无 m_hmacAuthCombox->addItem("MD-4", KYHMACAUTH_MD4); m_hmacAuthCombox->addItem("MD-5", KYHMACAUTH_MD5); m_hmacAuthCombox->addItem("SHA-1", KYHMACAUTH_SHA1); m_hmacAuthCombox->addItem("SHA-224", KYHMACAUTH_SHA224); m_hmacAuthCombox->addItem("SHA-256", KYHMACAUTH_SHA256); m_hmacAuthCombox->addItem("SHA-384", KYHMACAUTH_SHA384); m_hmacAuthCombox->addItem("SHA-512", KYHMACAUTH_SHA512); m_hmacAuthCombox->addItem("RIPEMD-160", KYHMACAUTH_RIPEMD160); //控件输入格式限制 QRegularExpression rxNumber("^[0-9]+$"); m_gatewayPortEdit->setValidator(new QRegularExpressionValidator(rxNumber, this)); m_renogotiaInrEdit->setValidator(new QRegularExpressionValidator(rxNumber, this)); m_customMtuEdit->setValidator(new QRegularExpressionValidator(rxNumber, this)); m_customUdpFragSizeEdit->setValidator(new QRegularExpressionValidator(rxNumber, this)); m_specPingInrEdit->setValidator(new QRegularExpressionValidator(rxNumber, this)); m_specExRePingEdit->setValidator(new QRegularExpressionValidator(rxNumber, this)); m_specMaxRouteEdit->setValidator(new QRegularExpressionValidator(rxNumber, this)); // IP的正则格式限制 QRegularExpression rxIp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); m_proxyServerAddEdit->setValidator(new QRegularExpressionValidator(rxIp, this)); //default m_gatewayPortEdit->setText("1194"); m_renogotiaInrEdit->setText("0"); m_customMtuEdit->setText("1500"); m_customUdpFragSizeEdit->setText("1500"); m_specPingInrEdit->setText("30"); m_specExRePingEdit->setText("30"); m_specMaxRouteEdit->setText("30"); if (m_serverCertCheckCombox->currentData().toInt() == (int)KYCHECKSERVER_NONE) { m_subjectMatchEdit->setEnabled(false); } else { m_subjectMatchEdit->setEnabled(true); } onTlsModeComboxIndexChanged(); onProxyTypeComboxIndexChanged(); } void VpnAdvancedPage::initSSwanAdiaFrame() { /**********控件**********/ QLabel *optionsLabel = new QLabel(this); QLabel *ikeLabel = new QLabel(this); QLabel *espLabel = new QLabel(this); m_optionsListWidget = new QListWidget(this); m_requestInIPCheckbox = new QCheckBox(this); m_udpEncapCheckbox = new QCheckBox(this); m_ipCompCheckbox = new QCheckBox(this); m_enablCustomCheckbox = new QCheckBox(this); m_ikeEdit = new QLineEdit(this); m_espEdit = new QLineEdit(this); m_ikeEspFrame = new QFrame(m_sSwanAdiaFrame); /**********布局**********/ QVBoxLayout *sSwanAdiaVLayout = new QVBoxLayout(m_sSwanAdiaFrame); sSwanAdiaVLayout->setContentsMargins(NO_LAYOUT_MARGINS); sSwanAdiaVLayout->setSpacing(LAYOUT_SPACING_SMALL); QFormLayout *ikeEspFrameLayout = new QFormLayout(m_ikeEspFrame); ikeEspFrameLayout->setContentsMargins(NO_LAYOUT_MARGINS); ikeEspFrameLayout->setHorizontalSpacing(HOR_LAYOUT_SPACING); ikeEspFrameLayout->setVerticalSpacing(LAYOUT_ADD_SPACING); ikeEspFrameLayout->addRow(ikeLabel, m_ikeEdit); ikeEspFrameLayout->addRow(espLabel, m_espEdit); sSwanAdiaVLayout->addWidget(optionsLabel); sSwanAdiaVLayout->addWidget(m_optionsListWidget); sSwanAdiaVLayout->addSpacing(LAYOUT_ADD_SPACING); sSwanAdiaVLayout->addWidget(m_enablCustomCheckbox); sSwanAdiaVLayout->addWidget(m_ikeEspFrame); sSwanAdiaVLayout->addStretch(); m_optionsListWidget->setFixedHeight(LISTWIDGET_HEIGHT_SMALL); /**********控件显示**********/ optionsLabel->setText(tr("Options:")); //选项: ikeLabel->setText("IKE"); espLabel->setText("ESP"); m_requestInIPCheckbox->setText(tr("Request an inner IP address")); //请求内部IP地址 m_udpEncapCheckbox->setText(tr("Enforce UDP encapsulation")); //强制UDP封装 m_ipCompCheckbox->setText(tr("Use IP compression")); //使用IP压缩 m_enablCustomCheckbox->setText(tr("Enable custom password suggestions")); //启用自定义密码建议 m_optionsListWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus); m_optionsListWidget->setFrameShape(QFrame::Shape::StyledPanel); addListItem(m_optionsListWidget, m_requestInIPCheckbox); addListItem(m_optionsListWidget, m_udpEncapCheckbox); addListItem(m_optionsListWidget, m_ipCompCheckbox); //strong-Swan default m_enablCustomCheckbox->setChecked(false); m_ikeEspFrame->setEnabled(false); } void VpnAdvancedPage::initDefalutCheckState() { m_mppeECheckbox->setChecked(false); m_mppeECombox->setEnabled(m_mppeECheckbox->isChecked()); //openVPN m_customGatewayPortCheckbox->setChecked(true); m_customRenegotiaInrCheckbox->setChecked(true); m_compressionCheckbox->setChecked(true); m_tcpConnCheckbox->setChecked(true); m_setVDevTypeCheckbox->setChecked(true); m_setVDevNameCheckbox->setChecked(true); m_customMtuCheckbox->setChecked(true); m_customUdpFragSizeCheckbox->setChecked(true); m_tcpMssCheckbox->setChecked(true); m_randomRemoteHostCheckbox->setChecked(true); m_ipv6TunLinkCheckbox->setChecked(true); m_specPingInrCheckbox->setChecked(true); m_specExitPingCheckbox->setChecked(true); m_acceptAuthedPaksCheckbox->setChecked(true); m_specMaxRouteCheckbox->setChecked(true); m_gatewayPortEdit->setEnabled(m_customGatewayPortCheckbox->isChecked()); m_renogotiaInrEdit->setEnabled(m_customRenegotiaInrCheckbox->isChecked()); m_setVDevNameEdit->setEnabled(m_setVDevNameCheckbox->isChecked()); m_customMtuEdit->setEnabled(m_customMtuCheckbox->isChecked()); m_customUdpFragSizeEdit->setEnabled(m_customUdpFragSizeCheckbox->isChecked()); m_specPingInrEdit->setEnabled(m_specPingInrCheckbox->isChecked()); m_specExRePingEdit->setEnabled(m_specExitPingCheckbox->isChecked()); m_specMaxRouteEdit->setEnabled(m_specMaxRouteCheckbox->isChecked()); m_compressionCombox->setEnabled(m_compressionCheckbox->isChecked()); m_setVDevTypeCombox->setEnabled(m_setVDevTypeCheckbox->isChecked()); m_specExitRestarCombox->setEnabled(m_specExitPingCheckbox->isChecked()); m_usePreviousCertCombox->setEnabled(m_usePreviousCertCheckbox->isChecked()); m_verifyPeerCertCombox->setEnabled(m_verifyPeerCertCheckbox->isChecked()); m_customKeySizeEdit->setEnabled(m_customKeySizeCheckbox->isChecked()); } void VpnAdvancedPage::addListItem(QListWidget *listWidget, QWidget *widget) { QListWidgetItem *listWidgetItem = new QListWidgetItem(listWidget); QWidget *itemWidget = new QWidget(listWidget); QHBoxLayout *hLayout = new QHBoxLayout(itemWidget); hLayout->setContentsMargins(16, 0, 0, 0); hLayout->addWidget(widget); listWidgetItem->setSizeHint(QSize(listWidget->width(), ITEM_HEIGHT)); listWidgetItem->setFlags(Qt::NoItemFlags); listWidget->addItem(listWidgetItem); listWidget->setItemWidget(listWidgetItem, itemWidget); } void VpnAdvancedPage::initCheckWidget(QCheckBox *checkBox, FixLabel *label, QWidget *widget) { QHBoxLayout *hLayout = new QHBoxLayout(widget); hLayout->setContentsMargins(NO_LAYOUT_MARGINS); hLayout->setSpacing(4); hLayout->addWidget(checkBox); hLayout->addWidget(label); hLayout->addStretch(); } void VpnAdvancedPage::onProxyTypeComboxIndexChanged() { switch (m_proxyTypeCombox->currentData().toInt()) { case NO: m_proxyServerAddEdit->clear(); m_proxyPortEdit->clear(); m_proxyUsernameEdit->clear(); m_proxyPwdEdit->clear(); m_infiniteRetryCheckbox->setChecked(false); m_proxyServerAddLabel->setEnabled(false); m_proxyPortLabel->setEnabled(false); m_proxyUsernameLabel->setEnabled(false); m_proxyPwdLabel->setEnabled(false); m_infiniteRetryCheckbox->setEnabled(false); m_proxyServerAddEdit->setEnabled(false); m_proxyPortEdit->setEnabled(false); m_proxyUsernameEdit->setEnabled(false); m_proxyPwdEdit->setEnabled(false); break; case HTTP: m_proxyServerAddLabel->setEnabled(true); m_proxyPortLabel->setEnabled(true); m_proxyUsernameLabel->setEnabled(true); m_proxyPwdLabel->setEnabled(true); m_infiniteRetryCheckbox->setEnabled(true); m_proxyServerAddEdit->setEnabled(true); m_proxyPortEdit->setEnabled(true); m_proxyUsernameEdit->setEnabled(true); m_proxyPwdEdit->setEnabled(true); break; case SOCKS: m_proxyServerAddLabel->setEnabled(true); m_proxyPortLabel->setEnabled(true); m_infiniteRetryCheckbox->setEnabled(true); m_proxyServerAddEdit->setEnabled(true); m_proxyPortEdit->setEnabled(true); m_proxyUsernameLabel->setEnabled(false); m_proxyPwdLabel->setEnabled(false); m_proxyUsernameEdit->setEnabled(false); m_proxyPwdEdit->setEnabled(false); break; default: break; } } void VpnAdvancedPage::onTlsModeComboxIndexChanged() { switch (m_tlsModeCombox->currentData().toInt()) { case TlsMode::NONE: m_keyPathLabel->setEnabled(false); m_keyPathEdit->setEnabled(false); m_keyPathChooseBtn->setEnabled(false); m_keyDirectionLabel->setEnabled(false); m_keyDirectionCombox->setEnabled(false); break; case TLS_CERT: m_keyPathLabel->setEnabled(true); m_keyPathEdit->setEnabled(true); m_keyPathChooseBtn->setEnabled(true); m_keyDirectionLabel->setEnabled(true); m_keyDirectionCombox->setEnabled(true); break; case TLS_ENCRYPTION: m_keyPathLabel->setEnabled(true); m_keyPathEdit->setEnabled(true); m_keyPathChooseBtn->setEnabled(true); m_keyDirectionLabel->setEnabled(false); m_keyDirectionCombox->setEnabled(false); break; default: break; } } void VpnAdvancedPage::setEnableOfConfirmBtn() { Q_EMIT setAdvancedPageState(checkConfirmBtnIsEnabled()); } void VpnAdvancedPage::onKeyPathButtonClicked() { QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a private key"), "recent:///", tr("Key Files (*.key *.pem *.der *.p12 *.pfx)")); if (!fileName.isNull()) { m_keyPathEdit->blockSignals(true); m_keyPathEdit->setText(fileName); m_keyPathEdit->blockSignals(false); } } void VpnAdvancedPage::showL2tpAdiaPage() { m_defaultAdiaFrame->setHidden(false); m_mruFrame->setHidden(false); m_compModeListWidget->item(COMP_MODE_PROTOCOL)->setHidden(false); m_compModeListWidget->item(COMP_MODE_ADDRESS)->setHidden(false); m_compModeListWidget->setFixedHeight(LISTWIDGET_HEIGHT); m_openVpnAdiaFrame->setHidden(true); m_sSwanAdiaFrame->setHidden(true); } void VpnAdvancedPage::showPptpAdiaPage() { m_defaultAdiaFrame->setHidden(false); m_compModeListWidget->item(COMP_MODE_PROTOCOL)->setHidden(true); m_compModeListWidget->item(COMP_MODE_ADDRESS)->setHidden(true); m_compModeListWidget->setFixedHeight(LISTWIDGET_HEIGHT_SMALL); m_mruFrame->setHidden(true); m_openVpnAdiaFrame->setHidden(true); m_sSwanAdiaFrame->setHidden(true); } void VpnAdvancedPage::showOpenVpnAdiaPage() { m_openVpnAdiaFrame->setHidden(false); m_defaultAdiaFrame->setHidden(true); m_mruFrame->setHidden(true); m_sSwanAdiaFrame->setHidden(true); } void VpnAdvancedPage::showSSwanAdiaPage() { m_sSwanAdiaFrame->setHidden(false); m_defaultAdiaFrame->setHidden(true); m_mruFrame->setHidden(true); m_openVpnAdiaFrame->setHidden(true); } bool VpnAdvancedPage::checkConfirmBtnIsEnabled() { //L2TP if (!m_mruFrame->isHidden()) { if (m_mruEdit->text().isEmpty() || m_mtuEdit->text().isEmpty()) { qDebug() << LOG_FLAG << "MRU or MTU is empty"; return false; } } //PPTP 无必填项 //OPEN VPN if (!m_openVpnAdiaFrame->isHidden()) { if (m_customGatewayPortCheckbox->isChecked() && m_gatewayPortEdit->text().isEmpty()) { return false; } if (m_customRenegotiaInrCheckbox->isChecked() && m_renogotiaInrEdit->text().isEmpty()) { return false; } if (m_setVDevNameCheckbox->isChecked() && m_setVDevNameEdit->text().isEmpty()) { return false; } if (m_customMtuCheckbox->isChecked() && m_customMtuEdit->text().isEmpty()) { return false; } if (m_customUdpFragSizeCheckbox->isChecked() && m_customUdpFragSizeEdit->text().isEmpty()) { return false; } if (m_specPingInrCheckbox->isChecked() && m_specPingInrEdit->text().isEmpty()) { return false; } if (m_specExitPingCheckbox->isChecked() && m_specExRePingEdit->text().isEmpty()) { return false; } if (m_specMaxRouteCheckbox->isChecked() && m_specMaxRouteEdit->text().isEmpty()) { return false; } if (m_serverCertCheckCombox->currentData().toInt() != (int)KYCHECKSERVER_NONE && m_subjectMatchEdit->text().isEmpty()) { return false; } if (m_tlsModeCombox->currentData().toInt() == TLS_CERT || m_tlsModeCombox->currentData().toInt() == TLS_ENCRYPTION) { if (m_keyPathEdit->text().isEmpty()) { return false; } } if (m_proxyTypeCombox->currentData().toInt() == HTTP || m_proxyTypeCombox->currentData().toInt() == SOCKS) { if (m_proxyServerAddEdit->text().isEmpty() || !getTextEditState(m_proxyServerAddEdit->text())) { return false; } if (m_proxyPortEdit->text().isEmpty()) { return false; } } if(m_customKeySizeCheckbox->isChecked() && m_customKeySizeEdit->text().isEmpty()) { return false; } } //strong-swan if (!m_sSwanAdiaFrame->isHidden()) { if (m_enablCustomCheckbox->isChecked()) { if (m_ikeEdit->text().isEmpty() || m_espEdit->text().isEmpty()) { return false; } } } return true; } bool VpnAdvancedPage::getTextEditState(QString text) { if (text.isEmpty()) { return true; } // IP地址正则表达式,包含开始和结束锚点确保完全匹配 QRegularExpression rx("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); // 进行匹配并返回结果 QRegularExpressionMatch match = rx.match(text); return match.hasMatch(); } kylin-nm/src-vpn/frontend/vpndetails/vpnipv6page.h0000664000175000017500000000374215167646234021260 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #ifndef VPNIPV6PAGE_H #define VPNIPV6PAGE_H #include #include #include #include #include #include #include "kyvpnconnectoperation.h" class VpnIpv6Page : public QFrame { Q_OBJECT public: VpnIpv6Page(QWidget *parent = nullptr); ~VpnIpv6Page() = default; void setVpnIpv6Info(const KyVpnConfig &vpnInfo); void setDns(const QString &firstDns); void setSearchDomain(const QString &searchDomain); bool checkIsChanged(const KyVpnConfig &vpnInfo); void updateVpnIpv6Info(KyVpnConfig &vpnInfo); private: QLabel *m_configLabel; QLabel *m_addressLabel; QLabel *m_maskLabel; QLabel *m_gateWayLabel; QLabel *m_dnsServerLabel; QLabel *m_searchDomainLabel; QComboBox *m_ipv6ConfigCombox; QLineEdit *m_ipv6addressEdit; QLineEdit *m_netMaskEdit; QLineEdit *m_gateWayEdit; QLineEdit *m_dnsServerEdit; QLineEdit *m_searchDomainEdit; void initUI(); void initConnect(); void setManualEnabled(bool state); bool getIpv6EditState(QString text); bool checkConfirmBtnIsEnabled(); private Q_SLOTS: void setEnableOfConfirmBtn(); void onConfigChanged(int index); Q_SIGNALS: void setIpv6PageState(bool); }; #endif // VPNIPV6PAGE_H kylin-nm/src-vpn/frontend/vpndetails/vpnaddpage.h0000664000175000017500000000547015167651420021115 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #ifndef VPNADDPAGE_H #define VPNADDPAGE_H #include #include #include #include #include #include #include #include #include #include #include #include #include "kyvpnconnectoperation.h" #define VPNADDPAGE_MAINLAYOUT_MARGINS 0, 12, 0, 12 #define VPNADDPAGE_ITEM_MARGINS 24, 0, 24, 0 #define VPNADDPAGE_NULLMAGINS 0, 0, 0, 0 #define VPNADDPAGE_SIZE 520,312 #define VPNADDPAGE_FRAME_FIXEDSIZE 520, 60 #define VPNADDPAGE_BUTTON_FIXEDSIZE 96, 36 #define VPNADDPAGE_NULLSPACE 0 #define VPNADDPAGE_BUTTON_SPACE 16 #define VPNADDPAGE_NAME_MAX_LENGTH 32 #define VPNADDPAGE_LABLE_FIXEDWIDTH 112 #define VPNADDPAGE_COMBOBOX_FIXEDWIDTH 360 #define VPNADDPAGE_INPUTBOX_FIXEDWIDTH 360 #define VPNDETAILPAGE_ITEM_MARGINS 24, 0, 24, 0 #define VPNDETAILPAGE_NULLMAGINS 0, 0, 0, 0 #define VPNDETAILPAGE_FRAME_FIXEDSIZE 520, 60 #define VPNDETAILPAGE_BUTTON_FIXEDSIZE 96, 36 #define VPNDETAILPAGE_NULLSPACE 0 #define VPNDETAILPAGE_BUTTON_SPACE 16 class vpnAddPage : public QWidget { Q_OBJECT public: explicit vpnAddPage(QWidget *parent = nullptr); void centerToScreen(); ~vpnAddPage(); protected: void paintEvent(QPaintEvent *event); private: void initWindow(); void initUI(); void initVpnTypeFrame(); void initVpnNameFrame(); void initVpnServerFrame(); void initButtonFrame(); void initConnection(); bool checkConfimBtnIsEnabled(); bool createVpnConnect(); QFrame *m_vpnTypeFrame = nullptr; QFrame *m_vpnNameFrame = nullptr; QFrame *m_vpnServerFrame = nullptr; QFrame *m_buttonFrame = nullptr; QComboBox *m_vpnTypeComboBox = nullptr; QLineEdit *m_vpnNameLineEdit = nullptr; QLineEdit *m_vpnServerLineEdit = nullptr; QPushButton *m_confimBtn = nullptr; QPushButton *m_cancelBtn = nullptr; QCheckBox *m_autoConnectBox = nullptr; KyVpnConnectOperation *m_vpnConnOperation = nullptr; private Q_SLOTS: void onConfimBtnClicked(); void onSetConfimBtnEnable(); Q_SIGNALS: void closed(); }; #endif // VPNADDPAGE_H kylin-nm/src-vpn/frontend/vpndetails/vpnconfigpage.h0000664000175000017500000001413315167646234021635 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #ifndef VPNCONFIGPAGE_H #define VPNCONFIGPAGE_H #include #include #include #include #include #include #include #include #include #include "kylable.h" #include "kwidget.h" #include "kpasswordedit.h" #include "kyvpnconnectoperation.h" using namespace kdk; #define KEY_DIRECTION_NONE_INDEX 0 #define KEY_DIRECTION_ZERO_INDEX 1 #define KEY_DIRECTION_ONE_INDEX 2 #define KEY_DIRECTION_NONE "None" #define KEY_DIRECTION_ZERO "0" #define KEY_DIRECTION_ONE "1" enum VpnType { UNKNOW = -1, L2TP = 0, OPEN_VPN, PPTP, STRONG_SWAN }; enum OpenVpnAuthMethodIndex { CERTIFICATE_INDEX = 0, STATICPASSWD_INDEX, PASSWD_INDEX, CERTIFICATEANDPASSWD_INDEX, }; enum StrongSwanAuthMethodIndex { KEY_INDEX = 0, AGENT_INDEX, SMARTCARD_INDEX, EAP_INDEX, }; class VpnConfigPage : public QFrame { Q_OBJECT public: explicit VpnConfigPage(QWidget *parent = nullptr); ~VpnConfigPage() = default; VpnType getVpnType(); void setVpnConfigInfo(const KyVpnConfig &vpnInfo); bool checkIsChanged(const KyVpnConfig &vpnInfo); void updateVpnConfigInfo(KyVpnConfig &vpnInfo); private: QFrame *m_vpnCommunalFrame; QFrame *m_authModeFrame; QFrame *m_caCertFrame; QFrame *m_userCertFrame; QFrame *m_staticKeysFrame; QFrame *m_pinFrame; QFrame *m_PrivateKeysFrame; QFrame *m_usersFrame; QFrame *m_userPwdOpFrame; QFrame *m_ntFrame; //公有 QLabel *m_vpnTypeLabel; QLabel *m_vpnNameLabel; FixLabel *m_serverAddressLabel; QComboBox *m_vpnTypeComboBox = nullptr; QLineEdit *m_vpnNameEdit = nullptr; QLineEdit *m_serverAddressEdit = nullptr; //认证方式 Authentication Mode FixLabel *m_authModeLabel; QComboBox *m_authModeComboBox = nullptr; //证书 私钥 FixLabel *m_caCertLabel; FixLabel *m_userCertLabel; FixLabel *m_privateKeyLabel; FixLabel *m_privateKeyPwdLabel; FixLabel *m_pwdOptionLabel; QLineEdit *m_caCertPathEdit; QLineEdit *m_userCertPathEdit; QLineEdit *m_privateKeyEdit; KPasswordEdit *m_privateKeyPwdEdit; QComboBox *m_pwdOptionCombox; QPushButton *m_caCertButton; QPushButton *m_userCertButton; QPushButton *m_privateKeyButton; //静态密钥 QLabel *m_staticKeyLabel; FixLabel *m_keyDirectionLabel; QLabel *m_noticesLabel; QLabel *m_localIpLabel; QLabel *m_remoteIpLabel; QLineEdit *m_staticKeyPathEdit; QPushButton *m_staticKeyButton; QComboBox *m_keyDirectionCombox; QLineEdit *m_localIpEdit; QLineEdit *m_remoteIpEdit; //智能卡 PIN码 QLabel *m_pinLabel; QLineEdit *m_pinEdit; //密码 FixLabel *m_usernameLabel; QLabel *m_userPwdLabel; FixLabel *m_userPwdOptionLabel; QLineEdit *m_usernameEdit; KPasswordEdit *m_userPwdEdit; QComboBox *m_userPwdOptionCombox; //L2TP PPTP公有 QLabel *m_ntDomainLabel; QLineEdit *m_ntDomainEdit; void initUI(); void initConnect(); void showL2tpPwd(); void showPptpPwd(); void showOpenVpnTls(); void showOpenVpnPwd(); void showOpenVpnPwdTls(); void showOpenVpnStaticKey(); void showSswanCertPrivteKey(); void showSswanCertSsh(); void showSswanSmartCard(); void showSswanEap(); bool getTextEditState(QString text); bool checkConfirmBtnIsEnabled(); //填充VPN认证信息 void setPwdAuthInfo(const QString &username, const QString &userPwd, const KyPasswdPolicy &userPwdPolicy); void setCaCertAuthInfo(const QString &caCertificate); void setKeyAuthInfo(const QString &userCert, const QString &privateKey, const QString &privateKeyPwd, const KyPasswdPolicy &privatePwdPolicy); void setStaticKeyAuthInfo(const QString &staticKey, const QString &vpnKeyDirection, const QString &localIp, const QString &remoteIp); void setAgentAuthInfo(const QString &userCert); void setSmartCardAuthInfo(const QString &pin); void setEapAuthInfo(const QString &username, const QString &userPwd); void setNtDomain(const QString &ntDomain); //set info void setL2tpConfigInfo(const KyVpnConfig &vpnInfo); void setPptpConfigInfo(const KyVpnConfig &vpnInfo); void setOpenVpnConfigInfo(const KyVpnConfig &vpnInfo); void setSSwanVpnConfigInfo(const KyVpnConfig &vpnInfo); //check change bool checkL2tpIsChanged(const KyVpnConfig &vpnInfo); bool checkPptpIsChanged(const KyVpnConfig &vpnInfo); bool checkOpenVpnIsChanged(const KyVpnConfig &vpnInfo); bool checkStrongSwanIsChanged(const KyVpnConfig &vpnInfo); //update void updateL2tpConfigInfo(KyVpnConfig &vpnInfo); void updatePptpConfigInfo(KyVpnConfig &vpnInfo); void updateOpenVpnConfigInfo(KyVpnConfig &vpnInfo); void updateSSwanVpnConfigInfo(KyVpnConfig &vpnInfo); private Q_SLOTS: void onVpnTypeComboxIndexChanged(); void onAuthModeComboxIndexChanged(); void setEnableOfConfirmBtn(); void onCaCertButtonClicked(); void onUserCertButtonClicked(); void onStaticKeyButtonClicked(); void onPrivateKeyButtonClicked(); Q_SIGNALS: void setConfigPageState(bool); void vpnTypeChanged(VpnType type); }; #endif // VPNCONFIGPAGE_H kylin-nm/src-vpn/frontend/vpndetails/vpndetail.h0000664000175000017500000000610615167651420020767 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #ifndef VPNDETAIL_H #define VPNDETAIL_H #include #include #include #include #include #include #include #include #include #include #include #include "kwidget.h" #include "ktabbar.h" #include "../tools/divider.h" #include "vpnconfigpage.h" #include "vpnipv4page.h" #include "vpnipv6page.h" #include "vpnadvancedpage.h" #include "kyvpnconnectoperation.h" using namespace kdk; class VpnTabBar : public KTabBar { Q_OBJECT public: explicit VpnTabBar(QWidget *parent = nullptr); ~VpnTabBar() = default; protected: QSize sizeHint() const; QSize minimumTabSizeHint(int index) const; private Q_SLOTS: void onModeChanged(bool mode); }; class VpnDetail : public QWidget { Q_OBJECT public: explicit VpnDetail(QString vpnUuid, QString vpnName, QWidget *parent = nullptr); void centerToScreen(); protected: void paintEvent(QPaintEvent *event); private: void initUI(); void initWindow(); void initTabBar(); void initConnection(); void setConfirmEnable(); void getVpnConfig(QString connectUuid, KyVpnConfig &vpnInfo); void pagePadding(bool isOpenVpn); bool updateVpnCnofig(); void setVpndetailSomeEnable(bool on); bool m_isOpenVpn = false; QString m_vpnName; QString m_uuid; KyVpnConfig m_vpnInfo; QStackedWidget * m_stackWidget; QWidget *m_topWidget; QWidget *m_centerWidget; Divider *m_divider = nullptr; QWidget *m_bottomWidget; VpnConfigPage *m_configPage = nullptr; VpnIpv4Page *m_ipv4Page = nullptr; VpnIpv6Page *m_ipv6Page = nullptr; VpnAdvancedPage *m_advancedPage = nullptr; QScrollArea *m_configScroArea = nullptr; QScrollArea *m_ipv4ScroArea = nullptr; QScrollArea *m_ipv6ScroArea = nullptr; QScrollArea *m_advancedScroArea = nullptr; VpnTabBar *m_vpnTabBar = nullptr; QCheckBox *m_autoConnectBox = nullptr; QLabel *m_autoConnectLabel; QPushButton *m_cancelBtn; QPushButton *m_confimBtn; bool m_isConfigOk = false; bool m_isIpv4Ok = false; bool m_isIpv6Ok = false; bool m_isAdvancedOk = false; protected Q_SLOTS: void onTabCurrentRowChange(int row); void onConfimBtnClicked(); Q_SIGNALS: void currentChanged(int); }; #endif // VPNDETAIL_H kylin-nm/src-vpn/frontend/vpndetails/vpnadvancedpage.h0000664000175000017500000001571615167646234022145 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #ifndef VPNADVANCEDPAGE_H #define VPNADVANCEDPAGE_H #include #include #include #include #include #include #include #include #include #include #include #include "kylable.h" #include "kwidget.h" #include "kpasswordedit.h" #include "vpnconfigpage.h" #include "kyvpnconnectoperation.h" using namespace kdk; enum TlsMode { NONE = 0, TLS_CERT, TLS_ENCRYPTION }; enum ProxyType { NO = 0, HTTP, SOCKS }; class VpnAdvancedPage : public QFrame { Q_OBJECT public: VpnAdvancedPage(QWidget *parent = nullptr); ~VpnAdvancedPage() = default; //Adia: Advanced void setL2tpOrPptpAdiaInfo(const KyVpnConfig &vpnInfo); void setOpenVpnAdiaInfo(const KyVpnConfig &vpnInfo); void setStrongSwanAdiaInfo(const KyVpnConfig &vpnInfo); bool checkIsChanged(const KyVpnConfig &vpnInfo, VpnType &vpnType); bool checkL2tpIsChanged(const KyVpnConfig &vpnInfo); bool checkPptpIsChanged(const KyVpnConfig &vpnInfo); bool checkOpenVpnIsChanged(const KyVpnConfig &vpnInfo); bool checkStrongSwanIsChanged(const KyVpnConfig &vpnInfo); void updateL2tpOrPptpAdiaInfo(KyVpnConfig &vpnInfo); void updateOpenVpnAdiaInfo(KyVpnConfig &vpnInfo); void updateStrongSwanAdiaInfo(KyVpnConfig &vpnInfo); protected: void paintEvent(QPaintEvent *event); private: bool m_isOpenVpn; QFrame *m_defaultAdiaFrame; QFrame *m_mruFrame; QFrame *m_openVpnAdiaFrame; QFrame *m_sSwanAdiaFrame; //L2TP PPTP Encryption(E) QCheckBox *m_mppeECheckbox = nullptr; QCheckBox *m_useStatefulECheckbox = nullptr; QCheckBox *m_sendPppEchoPkgCheckbox = nullptr; QLabel *m_authModeLabel; QLabel *m_compModeLabel; QLabel *m_mruLabel; QLabel *m_mtuLabel; QLineEdit *m_mruEdit; QLineEdit *m_mtuEdit; QComboBox *m_mppeECombox = nullptr; //认证方式 QListWidget *m_authModeListWidget = nullptr; QCheckBox *m_papAuthCheckbox = nullptr; QCheckBox *m_chapAuthCheckbox = nullptr; QCheckBox *m_mschapAuthCheckbox = nullptr; QCheckBox *m_mschap2AuthCheckbox = nullptr; QCheckBox *m_eapAuthCheckbox = nullptr; //压缩方式 QListWidget *m_compModeListWidget = nullptr; QCheckBox *m_bsdCompModeCheckbox = nullptr; QCheckBox *m_defaultCompModeCheckbox = nullptr; QCheckBox *m_tcpCompModeCheckbox = nullptr; QCheckBox *m_protocolCompModeCheckbox = nullptr; QCheckBox *m_addressCompModeCheckbox = nullptr; //Open VPN //general QCheckBox *m_customGatewayPortCheckbox = nullptr; QCheckBox *m_customRenegotiaInrCheckbox = nullptr; QCheckBox *m_compressionCheckbox = nullptr; QCheckBox *m_tcpConnCheckbox = nullptr; QCheckBox *m_setVDevTypeCheckbox = nullptr; QCheckBox *m_setVDevNameCheckbox = nullptr; QCheckBox *m_customMtuCheckbox = nullptr; QCheckBox *m_customUdpFragSizeCheckbox = nullptr; QCheckBox *m_tcpMssCheckbox = nullptr; QCheckBox *m_randomRemoteHostCheckbox = nullptr; QCheckBox *m_ipv6TunLinkCheckbox = nullptr; QCheckBox *m_specPingInrCheckbox = nullptr; QCheckBox *m_specExitPingCheckbox = nullptr; QCheckBox *m_acceptAuthedPaksCheckbox = nullptr; QCheckBox *m_specMaxRouteCheckbox = nullptr; QLineEdit *m_gatewayPortEdit; QLineEdit *m_renogotiaInrEdit; QLineEdit *m_setVDevNameEdit; QLineEdit *m_customMtuEdit; QLineEdit *m_customUdpFragSizeEdit; QLineEdit *m_specPingInrEdit; QLineEdit *m_specExRePingEdit; QLineEdit *m_specMaxRouteEdit; QComboBox *m_compressionCombox = nullptr; QComboBox *m_setVDevTypeCombox = nullptr; QComboBox *m_specExitRestarCombox = nullptr; FixLabel *m_customRenoInrLabel; FixLabel *m_customMtuLabel; FixLabel *m_customUdpLabel; FixLabel *m_acceptAuthedPaksLabel; //TLS settings QLabel *m_subjectMatchLabel; QLabel *m_keyPathLabel; QLabel *m_keyDirectionLabel; QLineEdit *m_subjectMatchEdit; QLineEdit *m_keyPathEdit; QPushButton *m_keyPathChooseBtn; QCheckBox *m_usePreviousCertCheckbox = nullptr; QCheckBox *m_verifyPeerCertCheckbox = nullptr; QComboBox *m_serverCertCheckCombox = nullptr; QComboBox *m_usePreviousCertCombox = nullptr; QComboBox *m_verifyPeerCertCombox = nullptr; QComboBox *m_tlsModeCombox = nullptr; QComboBox *m_keyDirectionCombox = nullptr; //proxies QLabel *m_proxyServerAddLabel; QLabel *m_proxyPortLabel; QLabel *m_proxyUsernameLabel; QLabel *m_proxyPwdLabel; QComboBox *m_proxyTypeCombox = nullptr; QCheckBox *m_infiniteRetryCheckbox = nullptr; QLineEdit *m_proxyServerAddEdit; QLineEdit *m_proxyPortEdit; QLineEdit *m_proxyUsernameEdit; KPasswordEdit *m_proxyPwdEdit; //security QCheckBox *m_customKeySizeCheckbox = nullptr; QLineEdit *m_customKeySizeEdit; QComboBox *m_hmacAuthCombox = nullptr; //strongswan QListWidget *m_optionsListWidget = nullptr; QCheckBox *m_requestInIPCheckbox = nullptr; QCheckBox *m_udpEncapCheckbox = nullptr; QCheckBox *m_ipCompCheckbox = nullptr; QCheckBox *m_enablCustomCheckbox = nullptr; QFrame *m_ikeEspFrame; QLineEdit *m_ikeEdit; QLineEdit *m_espEdit; void initUi(); void initConnect(); void initDefaultAdiaFrame(); //L2TP PPTP void initOpenVpnAdiaFrame(); //Open VPN void initSSwanAdiaFrame(); //strong-swan void initDefalutCheckState(); void addListItem(QListWidget *listWidget, QWidget *widget); void initCheckWidget(QCheckBox *checkBox, FixLabel *label, QWidget *widget); void showL2tpAdiaPage(); void showPptpAdiaPage(); void showOpenVpnAdiaPage(); void showSSwanAdiaPage(); bool checkConfirmBtnIsEnabled(); bool getTextEditState(QString text); private Q_SLOTS: void onProxyTypeComboxIndexChanged(); void onTlsModeComboxIndexChanged(); void setEnableOfConfirmBtn(); void onKeyPathButtonClicked(); public Q_SLOTS: void setVpnAdvancedPage(const VpnType &type); Q_SIGNALS: void setAdvancedPageState(bool); }; #endif // VPNADVANCEDPAGE_H kylin-nm/src-vpn/frontend/vpndetails/vpnipv4page.h0000664000175000017500000000425315167646234021254 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #ifndef VPNIPV4PAGE_H #define VPNIPV4PAGE_H #include #include #include #include #include #include #include "kyvpnconnectoperation.h" class VpnIpv4Page : public QFrame { Q_OBJECT public: VpnIpv4Page(QWidget *parent = nullptr); ~VpnIpv4Page() = default; void setVpnIpv4Info(const KyVpnConfig &vpnInfo); void setDns(const QString &firstDns); void setSearchDomain(const QString &searchDomain); void setDhcpClientId(const QString &dhcpId); bool checkIsChanged(const KyVpnConfig &vpnInfo); void updateVpnIpv4Info(KyVpnConfig &vpnInfo); private: QLabel *m_configLabel; QLabel *m_addressLabel; QLabel *m_maskLabel; QLabel *m_gateWayLabel; QLabel *m_dnsServerLabel; QLabel *m_searchDomainLabel; QLabel *m_dhcpClientIdLabel; QComboBox *m_ipv4ConfigCombox; QLineEdit *m_ipv4addressEdit; QLineEdit *m_netMaskEdit; QLineEdit *m_gateWayEdit; QLineEdit *m_dnsServerEdit; QLineEdit *m_searchDomainEdit; QLineEdit *m_dhcpClientIdEdit; void initUI(); void initConnect(); void setManualEnabled(bool state); bool getTextEditState(QString text); bool netMaskIsValide(QString text); QString getNetMaskText(QString text); bool checkConfirmBtnIsEnabled(); private Q_SLOTS: void setEnableOfConfirmBtn(); void onConfigChanged(int index); Q_SIGNALS: void setIpv4PageState(bool); }; #endif // VPNIPV4PAGE_H kylin-nm/src-vpn/frontend/vpndetails/vpndetails.pri0000664000175000017500000000056715167646234021531 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/vpnaddpage.h \ $$PWD/vpnadvancedpage.h \ $$PWD/vpnconfigpage.h \ $$PWD/vpndetail.h \ $$PWD/vpnipv4page.h \ $$PWD/vpnipv6page.h SOURCES += \ $$PWD/vpnaddpage.cpp \ $$PWD/vpnadvancedpage.cpp \ $$PWD/vpnconfigpage.cpp \ $$PWD/vpndetail.cpp \ $$PWD/vpnipv4page.cpp \ $$PWD/vpnipv6page.cpp kylin-nm/src-vpn/frontend/vpndetails/vpndetail.cpp0000664000175000017500000003535015167651420021325 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #include "vpndetail.h" #define WINDOW_WIDTH 520 #define WINDOW_HEIGHT 562 #define NO_LAYOUT_MARGINS 0,0,0,0 #define HLAYOUT_MARGINS 24,0,24,0 #define CENTER_LAYOUT_MARGINS 24,0,0,0 #define NO_SPACE 0 #define HLAYOUT_SPACING 16 #define VLAYOUT_SPACING 24 #define BOTTOM_WIDGET_HEIGHT 85 #define TAB_HEIGHT 36 #define TAB_WIDTH 80 #define MAX_TAB_TEXT_LENGTH 44 #define VPNTAB_WIDTH 240 #define PAGE_WIDTH 472 #define SCRO_WIDTH 496 #define CONFIG_PAGE_NUM 0 #define IPV4_PAGE_NUM 1 #define IPV6_PAGE_NUM 2 #define ADVANCED_PAGE_NUM 3 #define NORMAL_PAGE_COUNT 3 #define LOG_FLAG "[VPN Detail]" #define TAB_HEIGHT_TABLET 48 VpnDetail::VpnDetail(QString vpnUuid, QString vpnName, QWidget *parent) : m_vpnName(vpnName), m_uuid(vpnUuid), QWidget(parent) { initWindow(); centerToScreen(); getVpnConfig(m_uuid, m_vpnInfo); initUI(); initConnection(); pagePadding(m_isOpenVpn); m_isConfigOk = true; m_isIpv4Ok = true; m_isIpv6Ok = true; m_isAdvancedOk = true; setConfirmEnable(); } void VpnDetail::paintEvent(QPaintEvent *event) { QPalette pal = qApp->palette(); QPainter painter(this); painter.setBrush(pal.color(QPalette::Base)); painter.drawRect(this->rect()); painter.fillRect(rect(), QBrush(pal.color(QPalette::Base))); return QWidget::paintEvent(event); } void VpnDetail::initWindow() { this->setFixedSize(WINDOW_WIDTH, WINDOW_HEIGHT); this->setWindowTitle(tr("VPN")); this->setAttribute(Qt::WA_DeleteOnClose); } void VpnDetail::initTabBar() { //文本长度超出显示区域设置tooltip int tabCount = m_vpnTabBar->count(); for (int i = 0; i< tabCount; ++i) { QFontMetrics fontMetrics(m_vpnTabBar->font()); int fontSize = fontMetrics.horizontalAdvance(m_vpnTabBar->tabText(i)); if (fontSize > MAX_TAB_TEXT_LENGTH) { m_vpnTabBar->setTabToolTip(i, m_vpnTabBar->tabText(i)); } else { m_vpnTabBar->setTabToolTip(i, ""); } } } void VpnDetail::initUI() { //控件 m_topWidget = new QWidget(this); m_centerWidget = new QWidget(this); m_bottomWidget = new QWidget(this); m_divider = new Divider(false, this); m_vpnTabBar = new VpnTabBar(this); m_autoConnectBox = new QCheckBox(this); m_autoConnectLabel = new QLabel(this); m_cancelBtn = new QPushButton(this); m_confimBtn = new QPushButton(this); m_stackWidget = new QStackedWidget(m_centerWidget); m_configPage = new VpnConfigPage(this); m_ipv4Page = new VpnIpv4Page(this); m_ipv6Page = new VpnIpv6Page(this); m_advancedPage = new VpnAdvancedPage(this); m_configScroArea = new QScrollArea(m_centerWidget); m_configScroArea->setFrameShape(QFrame::NoFrame); m_configScroArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_configScroArea->setWidget(m_configPage); m_configScroArea->setWidgetResizable(true); m_ipv4ScroArea = new QScrollArea(m_centerWidget); m_ipv4ScroArea->setFrameShape(QFrame::NoFrame); m_ipv4ScroArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_ipv4ScroArea->setWidget(m_ipv4Page); m_ipv4ScroArea->setWidgetResizable(true); m_ipv6ScroArea = new QScrollArea(m_centerWidget); m_ipv6ScroArea->setFrameShape(QFrame::NoFrame); m_ipv6ScroArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_ipv6ScroArea->setWidget(m_ipv6Page); m_ipv6ScroArea->setWidgetResizable(true); m_advancedScroArea = new QScrollArea(m_centerWidget); m_advancedScroArea->setFrameShape(QFrame::NoFrame); m_advancedScroArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_advancedScroArea->setWidget(m_advancedPage); m_advancedScroArea->setWidgetResizable(true); QPalette pal = m_configScroArea->palette(); pal.setBrush(QPalette::Window, Qt::transparent); m_configScroArea->setPalette(pal); m_ipv4ScroArea->setPalette(pal); m_ipv6ScroArea->setPalette(pal); m_advancedScroArea->setPalette(pal); m_configPage->setFixedWidth(PAGE_WIDTH); m_ipv4Page->setFixedWidth(PAGE_WIDTH); m_ipv6Page->setFixedWidth(PAGE_WIDTH); m_advancedPage->setFixedWidth(PAGE_WIDTH); m_configScroArea->setFixedWidth(SCRO_WIDTH); m_ipv4ScroArea->setFixedWidth(SCRO_WIDTH); m_ipv6ScroArea->setFixedWidth(SCRO_WIDTH); m_advancedScroArea->setFixedWidth(SCRO_WIDTH); m_stackWidget->addWidget(m_configScroArea); m_stackWidget->addWidget(m_ipv4ScroArea); m_stackWidget->addWidget(m_ipv6ScroArea); m_stackWidget->addWidget(m_advancedScroArea); //控件显示文本 m_vpnTabBar->addTab(tr("VPN")); m_vpnTabBar->addTab(tr("IPv4")); if (m_isOpenVpn) { m_vpnTabBar->addTab(tr("IPv6")); m_vpnTabBar->setFixedWidth(VPNTAB_WIDTH + TAB_WIDTH); } else { m_vpnTabBar->setFixedWidth(VPNTAB_WIDTH); } m_vpnTabBar->addTab(tr("Advanced")); m_vpnTabBar->setFixedHeight(TAB_HEIGHT); initTabBar(); m_autoConnectBox->setChecked(false); m_autoConnectLabel->setText(tr("Auto Connection")); m_cancelBtn->setText(tr("Cancel")); m_confimBtn->setText(tr("Confirm")); //布局 QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(NO_LAYOUT_MARGINS); mainLayout->setSpacing(NO_SPACE); mainLayout->addSpacing(HLAYOUT_SPACING); mainLayout->addWidget(m_topWidget); mainLayout->addSpacing(VLAYOUT_SPACING); mainLayout->addWidget(m_centerWidget); mainLayout->addStretch(); mainLayout->addWidget(m_divider); mainLayout->addWidget(m_bottomWidget); m_bottomWidget->setFixedHeight(BOTTOM_WIDGET_HEIGHT); QHBoxLayout *topLayout = new QHBoxLayout(m_topWidget); topLayout->setContentsMargins(HLAYOUT_MARGINS); topLayout->addWidget(m_vpnTabBar, Qt::AlignCenter); QVBoxLayout *centerlayout = new QVBoxLayout(m_centerWidget); centerlayout->setContentsMargins(CENTER_LAYOUT_MARGINS); // 右边距为0,为安全页滚动区域留出空间 centerlayout->addWidget(m_stackWidget); QHBoxLayout *bottomLayout = new QHBoxLayout(m_bottomWidget); bottomLayout->setContentsMargins(HLAYOUT_MARGINS); bottomLayout->setSpacing(NO_SPACE); bottomLayout->addWidget(m_autoConnectBox); bottomLayout->addSpacing(8); bottomLayout->addWidget(m_autoConnectLabel); bottomLayout->addStretch(); bottomLayout->addWidget(m_cancelBtn); bottomLayout->addSpacing(HLAYOUT_SPACING); bottomLayout->addWidget(m_confimBtn); m_advancedPage->setVpnAdvancedPage(m_configPage->getVpnType()); } void VpnDetail::initConnection() { connect(m_vpnTabBar, &VpnTabBar::currentChanged, this, &VpnDetail::onTabCurrentRowChange); connect(m_cancelBtn, &QPushButton::clicked, [&] () {this->close();}); connect(m_confimBtn, &QPushButton::clicked, this, &VpnDetail::onConfimBtnClicked); connect(m_configPage, &VpnConfigPage::setConfigPageState, this, [=] (bool state) { m_isConfigOk = state; setConfirmEnable(); }); connect(m_ipv4Page, &VpnIpv4Page::setIpv4PageState, this, [=] (bool state) { m_isIpv4Ok = state; setConfirmEnable(); }); connect(m_ipv6Page, &VpnIpv6Page::setIpv6PageState, this, [=] (bool state) { m_isIpv6Ok = state; setConfirmEnable(); }); connect(m_advancedPage, &VpnAdvancedPage::setAdvancedPageState, this, [=] (bool state) { m_isAdvancedOk = state; setConfirmEnable(); }); connect(m_configPage, &VpnConfigPage::vpnTypeChanged, m_advancedPage, &VpnAdvancedPage::setVpnAdvancedPage); connect(m_configPage, &VpnConfigPage::vpnTypeChanged, this, [=](VpnType type) { if (type == OPEN_VPN) { if (m_vpnTabBar->count() == NORMAL_PAGE_COUNT) { m_vpnTabBar->insertTab(IPV6_PAGE_NUM, tr("IPv6")); m_vpnTabBar->setFixedWidth(VPNTAB_WIDTH + TAB_WIDTH); } } else { if (m_vpnTabBar->count() > NORMAL_PAGE_COUNT) { m_vpnTabBar->removeTab(IPV6_PAGE_NUM); m_vpnTabBar->setFixedWidth(VPNTAB_WIDTH); } } }); } void VpnDetail::centerToScreen() { QRect desk_rect; QScreen *currentScreen = QGuiApplication::screenAt(QCursor::pos()); if (currentScreen) { desk_rect = currentScreen->geometry(); } else { desk_rect=QGuiApplication::primaryScreen()->geometry(); } int desk_x = desk_rect.width(); int desk_y = desk_rect.height(); int x = this->width(); int y = this->height(); this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); } void VpnDetail::setConfirmEnable() { bool isConfirmBtnEnable = false; if (m_isConfigOk && m_isIpv4Ok && m_isAdvancedOk) { if (m_isOpenVpn && !m_isIpv6Ok) { isConfirmBtnEnable = false; } else { isConfirmBtnEnable = true; } } m_confimBtn->setEnabled(isConfirmBtnEnable); } void VpnDetail::getVpnConfig(QString connectUuid, KyVpnConfig &vpnInfo) { KyVpnConnectOperation vpnConnect(this); vpnInfo = vpnConnect.getVpnConfig(connectUuid); m_isOpenVpn = m_vpnInfo.m_vpnType == KYVPNTYPE_OPENVPN; } void VpnDetail::pagePadding(bool isOpenVpn) { m_autoConnectBox->setChecked(m_vpnInfo.m_isAutoConnect); //配置页面填充 m_configPage->setVpnConfigInfo(m_vpnInfo); //IPv4页面填充 m_ipv4Page->setVpnIpv4Info(m_vpnInfo); if (!m_vpnInfo.m_ipv4Dns.isEmpty()) { m_ipv4Page->setDns(m_vpnInfo.m_ipv4Dns.at(0).toString()); } if (!m_vpnInfo.m_ipv4DnsSearch.isEmpty()) { m_ipv4Page->setSearchDomain(m_vpnInfo.m_ipv4DnsSearch.at(0)); } m_ipv4Page->setDhcpClientId(m_vpnInfo.m_ipv4DhcpClientId); //IPv6页面填充 if (isOpenVpn) { m_ipv6Page->setVpnIpv6Info(m_vpnInfo); if (!m_vpnInfo.m_ipv6Dns.isEmpty()) { m_ipv6Page->setDns(m_vpnInfo.m_ipv6Dns.at(0).toString()); } if (!m_vpnInfo.m_ipv6DnsSearch.isEmpty()) { m_ipv6Page->setSearchDomain(m_vpnInfo.m_ipv6DnsSearch.at(0)); } } //高级页面填充 if (m_vpnInfo.m_vpnType == KYVPNTYPE_L2TP || m_vpnInfo.m_vpnType == KYVPNTYPE_PPTP) { m_advancedPage->setL2tpOrPptpAdiaInfo(m_vpnInfo); } else if (m_vpnInfo.m_vpnType == KYVPNTYPE_OPENVPN) { m_advancedPage->setOpenVpnAdiaInfo(m_vpnInfo); } else if (m_vpnInfo.m_vpnType == KYVPNTYPE_STRONGSWAN) { m_advancedPage->setStrongSwanAdiaInfo(m_vpnInfo); } } bool VpnDetail::updateVpnCnofig() { KyVpnConnectOperation vpnConnect(this); KyVpnConfig vpnConfig = m_vpnInfo; bool needUpdate = false; VpnType vpnType = m_configPage->getVpnType(); if (m_vpnInfo.m_isAutoConnect != m_autoConnectBox->isChecked()) { vpnConfig.m_isAutoConnect = m_autoConnectBox->isChecked(); needUpdate = true; } if (m_configPage->checkIsChanged(m_vpnInfo)) { m_configPage->updateVpnConfigInfo(vpnConfig); needUpdate = true; } if (m_ipv4Page->checkIsChanged(m_vpnInfo)) { m_ipv4Page->updateVpnIpv4Info(vpnConfig); needUpdate = true; } if (vpnType == OPEN_VPN) { if (m_ipv6Page->checkIsChanged(m_vpnInfo)) { m_ipv6Page->updateVpnIpv6Info(vpnConfig); needUpdate = true; } } if (m_advancedPage->checkIsChanged(m_vpnInfo, vpnType)) { if (vpnType == L2TP || vpnType == PPTP) { m_advancedPage->updateL2tpOrPptpAdiaInfo(vpnConfig); needUpdate = true; } else if (vpnType == OPEN_VPN) { m_advancedPage->updateOpenVpnAdiaInfo(vpnConfig); needUpdate = true; } else if (vpnType == STRONG_SWAN) { m_advancedPage->updateStrongSwanAdiaInfo(vpnConfig); needUpdate = true; } } if (needUpdate) { vpnConnect.setVpnConfig(m_uuid, vpnConfig); } return true; } void VpnDetail::setVpndetailSomeEnable(bool on) { m_configPage->setEnabled(on); m_ipv4Page->setEnabled(on); m_ipv6Page->setEnabled(on); m_advancedPage->setEnabled(on); m_cancelBtn->setEnabled(on); m_confimBtn->setEnabled(on); } void VpnDetail::onTabCurrentRowChange(int row) { if (row < 2) { m_stackWidget->setCurrentIndex(row); } else { if (m_configPage->getVpnType() == OPEN_VPN) { m_stackWidget->setCurrentIndex(row); } else { m_stackWidget->setCurrentIndex(ADVANCED_PAGE_NUM); } } } void VpnDetail::onConfimBtnClicked() { qDebug() << "onConfimBtnClicked"; setVpndetailSomeEnable(false); //更新连接 qDebug() << "Confirm update connect"; if (!updateVpnCnofig()) { setVpndetailSomeEnable(true); return; } close(); } VpnTabBar::VpnTabBar(QWidget *parent) :KTabBar(KTabBarStyle::SegmentDark, parent) { //模式切换 QDBusConnection::sessionBus().connect(QString("com.kylin.statusmanager.interface"), QString("/"), QString("com.kylin.statusmanager.interface"), QString("mode_change_signal"), this, SLOT(onModeChanged(bool))); //模式获取 QDBusInterface interface(QString("com.kylin.statusmanager.interface"), QString("/"), QString("com.kylin.statusmanager.interface"), QDBusConnection::sessionBus()); if(!interface.isValid()) { this->setFixedHeight(TAB_HEIGHT); return; } QDBusReply reply = interface.call("get_current_tabletmode"); if (!reply.isValid()) { this->setFixedHeight(TAB_HEIGHT); return; } onModeChanged(reply.value()); } QSize VpnTabBar::sizeHint() const { QSize size = KTabBar::sizeHint(); size.setWidth(TAB_WIDTH); return size; } QSize VpnTabBar::minimumTabSizeHint(int index) const { Q_UNUSED(index) QSize size = KTabBar::minimumTabSizeHint(index); size.setWidth(TAB_WIDTH); return size; } void VpnTabBar::onModeChanged(bool mode) { if (mode) { this->setFixedHeight(TAB_HEIGHT_TABLET); // 平板模式 } else { this->setFixedHeight(TAB_HEIGHT); // PC模式 } } kylin-nm/src-vpn/frontend/vpndetails/vpnconfigpage.cpp0000664000175000017500000011756215167651420022173 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #include "vpnconfigpage.h" #include #include #define NO_LAYOUT_MARGINS 0, 0, 0, 0 #define NO_SPACE 0 #define HLAYOUT_SPACING 16 #define VLAYOUT_SPACING 24 #define LEFT_LABEL_WIDTH 100 #define PIN_MAX_LENGTH 10 #define PWD_OPTION_THISUSER_INDEX 0 #define PWD_OPTION_ALLUSERS_INDEX 1 #define PWD_OPTION_ASKEVERYTIME_INDEX 2 #define PWD_OPTION_NOTREQUIRED_INDEX 3 #define LOG_FLAG "[VPN ConfigPage]" VpnConfigPage::VpnConfigPage(QWidget *parent) : QFrame(parent) { initUI(); initConnect(); onVpnTypeComboxIndexChanged(); } VpnType VpnConfigPage::getVpnType() { return VpnType(m_vpnTypeComboBox->currentData().toInt()); } void VpnConfigPage::setVpnConfigInfo(const KyVpnConfig &vpnInfo) { m_vpnNameEdit->setText(vpnInfo.m_vpnName); m_serverAddressEdit->setText(vpnInfo.m_gateway); m_vpnTypeComboBox->setCurrentIndex(vpnInfo.m_vpnType); onVpnTypeComboxIndexChanged(); switch (vpnInfo.m_vpnType) { case KYVPNTYPE_L2TP: setL2tpConfigInfo(vpnInfo); break; case KYVPNTYPE_PPTP: setPptpConfigInfo(vpnInfo); break; case KYVPNTYPE_OPENVPN: setOpenVpnConfigInfo(vpnInfo); break; case KYVPNTYPE_STRONGSWAN: setSSwanVpnConfigInfo(vpnInfo); break; default: qDebug() << LOG_FLAG << "Unknow VPN Type" << vpnInfo.m_vpnType; break; } } bool VpnConfigPage::checkIsChanged(const KyVpnConfig &vpnInfo) { bool isChanged = false; int currentVpnType = m_vpnTypeComboBox->currentData().toInt(); if (vpnInfo.m_vpnType != currentVpnType || vpnInfo.m_vpnName != m_vpnNameEdit->text() || vpnInfo.m_gateway != m_serverAddressEdit->text()) { isChanged = true; } switch (currentVpnType) { case L2TP: if (checkL2tpIsChanged(vpnInfo)) { isChanged = true; } break; case PPTP: if (checkPptpIsChanged(vpnInfo)) { isChanged = true; } break; case OPEN_VPN: if (checkOpenVpnIsChanged(vpnInfo)) { isChanged = true; } break; case STRONG_SWAN: if (checkStrongSwanIsChanged(vpnInfo)) { isChanged = true; } default: break; } return isChanged; } void VpnConfigPage::updateVpnConfigInfo(KyVpnConfig &vpnInfo) { vpnInfo.m_vpnType = (KyVpnType)m_vpnTypeComboBox->currentData().toInt(); vpnInfo.m_vpnName = m_vpnNameEdit->text(); vpnInfo.m_gateway = m_serverAddressEdit->text(); switch (m_vpnTypeComboBox->currentData().toInt()) { case L2TP: updateL2tpConfigInfo(vpnInfo); break; case OPEN_VPN: updateOpenVpnConfigInfo(vpnInfo); break; case PPTP: updatePptpConfigInfo(vpnInfo); break; case STRONG_SWAN: updateSSwanVpnConfigInfo(vpnInfo); break; default: break; } } void VpnConfigPage::initUI() { /**********控件**********/ //公有 m_vpnTypeLabel = new QLabel(this); m_vpnNameLabel = new QLabel(this); m_serverAddressLabel = new FixLabel(this); m_vpnTypeComboBox = new QComboBox(this); m_vpnNameEdit = new QLineEdit(this); m_serverAddressEdit = new QLineEdit(this); //认证方式 Authentication Mode m_authModeLabel = new FixLabel(this); m_authModeComboBox = new QComboBox(this); //证书 私钥 m_caCertLabel = new FixLabel(this); m_userCertLabel = new FixLabel(this); m_privateKeyLabel = new FixLabel(this); m_privateKeyPwdLabel = new FixLabel(this); m_pwdOptionLabel = new FixLabel(this); m_caCertPathEdit = new QLineEdit(this); m_userCertPathEdit = new QLineEdit(this); m_privateKeyEdit = new QLineEdit(this); m_privateKeyPwdEdit = new KPasswordEdit(this); m_pwdOptionCombox = new QComboBox(this); m_caCertButton = new QPushButton(this); m_userCertButton = new QPushButton(this); m_privateKeyButton = new QPushButton(this); //静态密钥 m_staticKeyLabel = new QLabel(this); m_keyDirectionLabel = new FixLabel(this); m_noticesLabel = new QLabel(this); m_localIpLabel = new QLabel(this); m_remoteIpLabel = new QLabel(this); m_staticKeyPathEdit = new QLineEdit(this); m_staticKeyButton = new QPushButton(this); m_keyDirectionCombox = new QComboBox(this); m_localIpEdit = new QLineEdit(this); m_remoteIpEdit = new QLineEdit(this); //智能卡 PIN码 m_pinLabel = new QLabel(this); m_pinEdit = new QLineEdit(this); //密码 m_usernameLabel = new FixLabel(this); m_userPwdLabel = new QLabel(this); m_userPwdOptionLabel = new FixLabel(this); m_usernameEdit = new QLineEdit(this); m_userPwdEdit = new KPasswordEdit(this); m_userPwdOptionCombox = new QComboBox(this); //L2TP PPTP公有 m_ntDomainLabel = new QLabel(this); m_ntDomainEdit = new QLineEdit(this); /**********布局**********/ m_vpnCommunalFrame = new QFrame(this); m_authModeFrame = new QFrame(this); m_caCertFrame = new QFrame(this); m_userCertFrame = new QFrame(this); m_staticKeysFrame = new QFrame(this); m_pinFrame = new QFrame(this); m_PrivateKeysFrame = new QFrame(this); m_usersFrame = new QFrame(this); m_userPwdOpFrame = new QFrame(this); m_ntFrame = new QFrame(this); //布局 QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(NO_LAYOUT_MARGINS); mainLayout->setSpacing(VLAYOUT_SPACING); mainLayout->addWidget(m_vpnCommunalFrame); mainLayout->addWidget(m_authModeFrame); mainLayout->addWidget(m_caCertFrame); mainLayout->addWidget(m_userCertFrame); mainLayout->addWidget(m_staticKeysFrame); mainLayout->addWidget(m_pinFrame); mainLayout->addWidget(m_PrivateKeysFrame); mainLayout->addWidget(m_usersFrame); mainLayout->addWidget(m_userPwdOpFrame); mainLayout->addWidget(m_ntFrame); mainLayout->addSpacing(3); mainLayout->addStretch(); QGridLayout *vpnCommLayout = new QGridLayout(m_vpnCommunalFrame); vpnCommLayout->setContentsMargins(NO_LAYOUT_MARGINS); vpnCommLayout->setHorizontalSpacing(HLAYOUT_SPACING); vpnCommLayout->setVerticalSpacing(VLAYOUT_SPACING); vpnCommLayout->addWidget(m_vpnTypeLabel, 0, 0); vpnCommLayout->addWidget(m_vpnNameLabel, 1, 0); vpnCommLayout->addWidget(m_serverAddressLabel, 2, 0); vpnCommLayout->addWidget(m_vpnTypeComboBox, 0, 1); vpnCommLayout->addWidget(m_vpnNameEdit, 1, 1); vpnCommLayout->addWidget(m_serverAddressEdit, 2, 1); m_vpnTypeLabel->setFixedWidth(LEFT_LABEL_WIDTH); m_vpnNameLabel->setFixedWidth(LEFT_LABEL_WIDTH); m_serverAddressLabel->setFixedWidth(LEFT_LABEL_WIDTH); QHBoxLayout *authMdLayout = new QHBoxLayout(m_authModeFrame); authMdLayout->setContentsMargins(NO_LAYOUT_MARGINS); authMdLayout->setSpacing(HLAYOUT_SPACING); authMdLayout->addWidget(m_authModeLabel); authMdLayout->addWidget(m_authModeComboBox); m_authModeLabel->setFixedWidth(LEFT_LABEL_WIDTH); QHBoxLayout *caCertLayout = new QHBoxLayout(m_caCertFrame); caCertLayout->setContentsMargins(NO_LAYOUT_MARGINS); caCertLayout->setSpacing(HLAYOUT_SPACING); caCertLayout->addWidget(m_caCertLabel); caCertLayout->addWidget(m_caCertPathEdit); caCertLayout->addWidget(m_caCertButton); m_caCertLabel->setFixedWidth(LEFT_LABEL_WIDTH); QHBoxLayout *userLayout = new QHBoxLayout(m_userCertFrame); userLayout->setContentsMargins(NO_LAYOUT_MARGINS); userLayout->setSpacing(HLAYOUT_SPACING); userLayout->addWidget(m_userCertLabel); userLayout->addWidget(m_userCertPathEdit); userLayout->addWidget(m_userCertButton); m_userCertLabel->setFixedWidth(LEFT_LABEL_WIDTH); QGridLayout *staticKeyLayout = new QGridLayout(m_staticKeysFrame); staticKeyLayout->setContentsMargins(NO_LAYOUT_MARGINS); staticKeyLayout->setHorizontalSpacing(HLAYOUT_SPACING); staticKeyLayout->setVerticalSpacing(VLAYOUT_SPACING); staticKeyLayout->addWidget(m_staticKeyLabel, 0, 0); staticKeyLayout->addWidget(m_staticKeyPathEdit, 0, 1); staticKeyLayout->addWidget(m_staticKeyButton, 0, 2); staticKeyLayout->addWidget(m_keyDirectionLabel, 1, 0); staticKeyLayout->addWidget(m_keyDirectionCombox, 1, 1, 1, 2); staticKeyLayout->addWidget(m_noticesLabel, 2, 0, 2, 3); staticKeyLayout->addWidget(m_localIpLabel, 4, 0); staticKeyLayout->addWidget(m_localIpEdit, 4, 1, 1, 2); staticKeyLayout->addWidget(m_remoteIpLabel, 5, 0); staticKeyLayout->addWidget(m_remoteIpEdit, 5, 1, 1, 2); m_staticKeyLabel->setFixedWidth(LEFT_LABEL_WIDTH); m_keyDirectionLabel->setFixedWidth(LEFT_LABEL_WIDTH); m_localIpLabel->setFixedWidth(LEFT_LABEL_WIDTH); m_remoteIpLabel->setFixedWidth(LEFT_LABEL_WIDTH); QHBoxLayout *pinLayout = new QHBoxLayout(m_pinFrame); pinLayout->setContentsMargins(NO_LAYOUT_MARGINS); pinLayout->setSpacing(HLAYOUT_SPACING); pinLayout->addWidget(m_pinLabel); pinLayout->addWidget(m_pinEdit); m_pinLabel->setFixedWidth(LEFT_LABEL_WIDTH); QGridLayout *privateKeysLayout = new QGridLayout(m_PrivateKeysFrame); privateKeysLayout->setContentsMargins(NO_LAYOUT_MARGINS); privateKeysLayout->setHorizontalSpacing(HLAYOUT_SPACING); privateKeysLayout->setVerticalSpacing(VLAYOUT_SPACING); privateKeysLayout->addWidget(m_privateKeyLabel, 0, 0); privateKeysLayout->addWidget(m_privateKeyPwdLabel, 1, 0); privateKeysLayout->addWidget(m_pwdOptionLabel, 2, 0); privateKeysLayout->addWidget(m_privateKeyEdit, 0, 1); privateKeysLayout->addWidget(m_privateKeyButton, 0, 2); privateKeysLayout->addWidget(m_privateKeyPwdEdit, 1, 1, 1, 2); privateKeysLayout->addWidget(m_pwdOptionCombox, 2, 1, 1, 2); m_privateKeyLabel->setFixedWidth(LEFT_LABEL_WIDTH); m_privateKeyPwdLabel->setFixedWidth(LEFT_LABEL_WIDTH); m_pwdOptionLabel->setFixedWidth(LEFT_LABEL_WIDTH); QGridLayout *usersLayout = new QGridLayout(m_usersFrame); usersLayout->setContentsMargins(NO_LAYOUT_MARGINS); usersLayout->setHorizontalSpacing(HLAYOUT_SPACING); usersLayout->setVerticalSpacing(VLAYOUT_SPACING); usersLayout->addWidget(m_usernameLabel, 0, 0); usersLayout->addWidget(m_usernameEdit, 0, 1); usersLayout->addWidget(m_userPwdLabel, 1, 0); usersLayout->addWidget(m_userPwdEdit, 1, 1); m_usernameLabel->setFixedWidth(LEFT_LABEL_WIDTH); m_userPwdLabel->setFixedWidth(LEFT_LABEL_WIDTH); QHBoxLayout *userPwdOLayout = new QHBoxLayout(m_userPwdOpFrame); userPwdOLayout->setContentsMargins(NO_LAYOUT_MARGINS); userPwdOLayout->setSpacing(HLAYOUT_SPACING); userPwdOLayout->addWidget(m_userPwdOptionLabel); userPwdOLayout->addWidget(m_userPwdOptionCombox); m_userPwdOptionLabel->setFixedWidth(LEFT_LABEL_WIDTH); QHBoxLayout *ntLayout = new QHBoxLayout(m_ntFrame); ntLayout->setContentsMargins(NO_LAYOUT_MARGINS); ntLayout->setSpacing(HLAYOUT_SPACING); ntLayout->addWidget(m_ntDomainLabel); ntLayout->addWidget(m_ntDomainEdit); m_ntDomainLabel->setFixedWidth(LEFT_LABEL_WIDTH); /**********控件显示**********/ m_vpnTypeLabel->setText(tr("Type")); //类型 m_vpnNameLabel->setText(tr("Name")); //名称 m_staticKeyLabel->setText(tr("Static Key")); //静态密钥 m_localIpLabel->setText(tr("Local IP")); //本地IP地址 m_remoteIpLabel->setText(tr("Remote IP")); //远程IP地址 m_pinLabel->setText(tr("PIN Code")); //PIN码 m_userPwdLabel->setText(tr("Password")); //密码 m_ntDomainLabel->setText(tr("NT Domain")); //NT域 m_serverAddressLabel->setLabelText(tr("Server Address")); //服务器地址 m_authModeLabel->setLabelText(tr("Authentication Mode")); //认证方式 m_caCertLabel->setLabelText(tr("CA Certificate")); //CA证书 m_userCertLabel->setLabelText(tr("User Certificate")); //用户证书 m_keyDirectionLabel->setLabelText(tr("Key Direction")); //密钥方向 m_privateKeyLabel->setLabelText(tr("Private Key")); //私钥 m_privateKeyPwdLabel->setLabelText(tr("Private Key Password")); //私有密钥密码 m_pwdOptionLabel->setLabelText(tr("Password Options")); //密码选项 m_usernameLabel->setLabelText(tr("Username")); //用户名 m_userPwdOptionLabel->setLabelText(tr("Password Options")); //密码选项 m_noticesLabel->setWordWrap(true); m_noticesLabel->setText(tr("Notice:\nIf key direction is used, it must be opposite to the VPN side used. " "If '1' is used, the connection must use '0'. " "If you are not sure which value to use, please contact your system administrator.")); QPalette pal; pal.setColor(QPalette::WindowText, qApp->palette().color(QPalette::Mid)); m_noticesLabel->setPalette(pal); m_caCertButton->setText(tr("Choose")); //选择 m_userCertButton->setText(tr("Choose")); m_staticKeyButton->setText(tr("Choose")); m_privateKeyButton->setText(tr("Choose")); m_vpnTypeComboBox->addItem("L2TP", L2TP); m_vpnTypeComboBox->addItem("open VPN", OPEN_VPN); m_vpnTypeComboBox->addItem("PPTP", PPTP); m_vpnTypeComboBox->addItem("strong-swan", STRONG_SWAN); m_keyDirectionCombox->addItem(tr("None"), KEY_DIRECTION_NONE); m_keyDirectionCombox->addItem("0", KEY_DIRECTION_ZERO); m_keyDirectionCombox->addItem("1", KEY_DIRECTION_ONE); m_pwdOptionCombox->addItem(tr("Save password only for this user"), KYPASSWD_FORTHISUSER); //仅对当前用户保存密码 m_pwdOptionCombox->addItem(tr("Save password for all users"), KYPASSWD_FORALLUSER); //为所有用户保存密码 m_pwdOptionCombox->addItem(tr("Ask password every time"), KYPASSWD_ASKEVERYTIME); //每次都询问 m_pwdOptionCombox->addItem(tr("Don't require a password"), KYPASSWD_ISNOTREQUIRED);//不需要密码 m_pwdOptionCombox->setCurrentIndex(PWD_OPTION_ASKEVERYTIME_INDEX); m_userPwdOptionCombox->addItem(tr("Save password only for this user"), KYPASSWD_FORTHISUSER); m_userPwdOptionCombox->addItem(tr("Save password for all users"), KYPASSWD_FORALLUSER); m_userPwdOptionCombox->addItem(tr("Ask password every time"), KYPASSWD_ASKEVERYTIME); m_userPwdOptionCombox->addItem(tr("Don't require a password"), KYPASSWD_ISNOTREQUIRED); m_userPwdOptionCombox->setCurrentIndex(PWD_OPTION_ASKEVERYTIME_INDEX); m_vpnNameEdit->setPlaceholderText(tr("Required")); //必填 m_serverAddressEdit->setPlaceholderText(tr("Required")); m_privateKeyPwdEdit->setClearButtonEnabled(false); m_userPwdEdit->setClearButtonEnabled(false); //控件输入格式限制 QRegularExpression rxNumber("^[0-9]+$"); m_pinEdit->setValidator(new QRegularExpressionValidator(rxNumber, this)); m_pinEdit->setMaxLength(PIN_MAX_LENGTH); // IP的正则格式限制 QRegularExpression rxIp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); QRegularExpressionValidator *ipExpVal = new QRegularExpressionValidator(rxIp, this); m_serverAddressEdit->setValidator(ipExpVal); m_localIpEdit->setValidator(ipExpVal); m_remoteIpEdit->setValidator(ipExpVal); } void VpnConfigPage::initConnect() { connect(m_vpnTypeComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &VpnConfigPage::onVpnTypeComboxIndexChanged); connect(m_authModeComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &VpnConfigPage::onAuthModeComboxIndexChanged); connect(m_vpnNameEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_serverAddressEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_caCertPathEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_userCertPathEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_privateKeyEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_staticKeyPathEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_localIpEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_remoteIpEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_pinEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_usernameEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_ntDomainEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_vpnTypeComboBox, &QComboBox::currentTextChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_authModeComboBox, &QComboBox::currentTextChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_pwdOptionCombox, &QComboBox::currentTextChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_userPwdOptionCombox, &QComboBox::currentTextChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); connect(m_caCertButton, &QPushButton::clicked, this, &VpnConfigPage::onCaCertButtonClicked); connect(m_userCertButton, &QPushButton::clicked, this, &VpnConfigPage::onUserCertButtonClicked); connect(m_staticKeyButton, &QPushButton::clicked, this, &VpnConfigPage::onStaticKeyButtonClicked); connect(m_privateKeyButton, &QPushButton::clicked, this, &VpnConfigPage::onPrivateKeyButtonClicked); } void VpnConfigPage::showL2tpPwd() { m_vpnCommunalFrame->setHidden(false); m_authModeFrame->setHidden(false); m_usersFrame->setHidden(false); m_userPwdOpFrame->setHidden(false); m_ntFrame->setHidden(false); m_PrivateKeysFrame->setHidden(true); m_caCertFrame->setHidden(true); m_userCertFrame->setHidden(true); m_staticKeysFrame->setHidden(true); m_pinFrame->setHidden(true); } void VpnConfigPage::showPptpPwd() { m_vpnCommunalFrame->setHidden(false); m_usersFrame->setHidden(false); m_userPwdOpFrame->setHidden(false); m_ntFrame->setHidden(false); m_authModeFrame->setHidden(true); m_PrivateKeysFrame->setHidden(true); m_caCertFrame->setHidden(true); m_userCertFrame->setHidden(true); m_staticKeysFrame->setHidden(true); m_pinFrame->setHidden(true); } void VpnConfigPage::showOpenVpnTls() { m_vpnCommunalFrame->setHidden(false); m_authModeFrame->setHidden(false); m_PrivateKeysFrame->setHidden(false); m_caCertFrame->setHidden(false); m_userCertFrame->setHidden(false); m_staticKeysFrame->setHidden(true); m_pinFrame->setHidden(true); m_usersFrame->setHidden(true); m_userPwdOpFrame->setHidden(true); m_ntFrame->setHidden(true); } void VpnConfigPage::showOpenVpnPwd() { m_vpnCommunalFrame->setHidden(false); m_authModeFrame->setHidden(false); m_caCertFrame->setHidden(false); m_usersFrame->setHidden(false); m_userPwdOpFrame->setHidden(false); m_userCertFrame->setHidden(true); m_PrivateKeysFrame->setHidden(true); m_staticKeysFrame->setHidden(true); m_pinFrame->setHidden(true); m_ntFrame->setHidden(true); } void VpnConfigPage::showOpenVpnPwdTls() { m_vpnCommunalFrame->setHidden(false); m_authModeFrame->setHidden(false); m_caCertFrame->setHidden(false); m_userCertFrame->setHidden(false); m_PrivateKeysFrame->setHidden(false); m_usersFrame->setHidden(false); m_userPwdOpFrame->setHidden(false); m_staticKeysFrame->setHidden(true); m_pinFrame->setHidden(true); m_ntFrame->setHidden(true); } void VpnConfigPage::showOpenVpnStaticKey() { m_vpnCommunalFrame->setHidden(false); m_authModeFrame->setHidden(false); m_staticKeysFrame->setHidden(false); m_caCertFrame->setHidden(true); m_userCertFrame->setHidden(true); m_PrivateKeysFrame->setHidden(true); m_usersFrame->setHidden(true); m_userPwdOpFrame->setHidden(true); m_pinFrame->setHidden(true); m_ntFrame->setHidden(true); } void VpnConfigPage::showSswanCertPrivteKey() { m_vpnCommunalFrame->setHidden(false); m_authModeFrame->setHidden(false); m_userCertFrame->setHidden(false); m_PrivateKeysFrame->setHidden(false); m_caCertFrame->setHidden(true); m_usersFrame->setHidden(true); m_userPwdOpFrame->setHidden(true); m_staticKeysFrame->setHidden(true); m_pinFrame->setHidden(true); m_ntFrame->setHidden(true); } void VpnConfigPage::showSswanCertSsh() { m_vpnCommunalFrame->setHidden(false); m_authModeFrame->setHidden(false); m_userCertFrame->setHidden(false); m_caCertFrame->setHidden(true); m_PrivateKeysFrame->setHidden(true); m_usersFrame->setHidden(true); m_userPwdOpFrame->setHidden(true); m_staticKeysFrame->setHidden(true); m_pinFrame->setHidden(true); m_ntFrame->setHidden(true); } void VpnConfigPage::showSswanSmartCard() { m_vpnCommunalFrame->setHidden(false); m_authModeFrame->setHidden(false); m_pinFrame->setHidden(false); m_caCertFrame->setHidden(true); m_userCertFrame->setHidden(true); m_PrivateKeysFrame->setHidden(true); m_usersFrame->setHidden(true); m_userPwdOpFrame->setHidden(true); m_staticKeysFrame->setHidden(true); m_ntFrame->setHidden(true); } void VpnConfigPage::showSswanEap() { m_vpnCommunalFrame->setHidden(false); m_authModeFrame->setHidden(false); m_usersFrame->setHidden(false); m_caCertFrame->setHidden(true); m_userCertFrame->setHidden(true); m_PrivateKeysFrame->setHidden(true); m_userPwdOpFrame->setHidden(true); m_staticKeysFrame->setHidden(true); m_pinFrame->setHidden(true); m_ntFrame->setHidden(true); } bool VpnConfigPage::getTextEditState(QString text) { if (text.isEmpty()) { return true; } // IP地址正则表达式,包含开始和结束锚点确保完全匹配 QRegularExpression rx("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); // 进行匹配并返回结果 QRegularExpressionMatch match = rx.match(text); return match.hasMatch(); } bool VpnConfigPage::checkConfirmBtnIsEnabled() { if (m_vpnNameEdit->text().isEmpty()) { qDebug() << LOG_FLAG << "VPN name empty or invalid"; return false; } if (m_serverAddressEdit->text().isEmpty() || !getTextEditState(m_serverAddressEdit->text())) { qDebug() << LOG_FLAG << "VPN server address empty or invalid"; return false; } int currentAuthMethod = m_authModeComboBox->currentData().toInt(); switch (currentAuthMethod) { case KYAUTH_PASSWD: case KYAUTH_EAP: if (m_usernameEdit->text().isEmpty() && !m_userPwdEdit->text().isEmpty()) { return false; } if (m_vpnTypeComboBox->currentData().toInt() == OPEN_VPN && m_caCertPathEdit->text().isEmpty()) { return false; } break; case KYAUTH_CERTIFICATE: if (m_caCertPathEdit->text().isEmpty() || m_userCertPathEdit->text().isEmpty() || m_privateKeyEdit->text().isEmpty()) { return false; } break; case KYAUTH_CERTIFICATEANDPASSWD: if (m_caCertPathEdit->text().isEmpty() || m_userCertPathEdit->text().isEmpty() || m_privateKeyEdit->text().isEmpty()) { return false; } if (m_usernameEdit->text().isEmpty() && !m_userPwdEdit->text().isEmpty()) { return false; } break; case KYAUTH_STATICPASSWD: if (m_staticKeyPathEdit->text().isEmpty()) { return false; } break; default: break; } return true; } void VpnConfigPage::setPwdAuthInfo(const QString &username, const QString &userPwd, const KyPasswdPolicy &userPwdPolicy) { m_usernameEdit->setText(username); m_userPwdEdit->setText(userPwd); if (userPwdPolicy == KYPASSWD_ISNOTREQUIRED) { m_userPwdOptionCombox->setCurrentIndex(PWD_OPTION_NOTREQUIRED_INDEX); } else { m_userPwdOptionCombox->setCurrentIndex(userPwdPolicy); } } void VpnConfigPage::setCaCertAuthInfo(const QString &caCertificate) { m_caCertPathEdit->setText(caCertificate); } void VpnConfigPage::setKeyAuthInfo(const QString &userCert, const QString &privateKey, const QString &privateKeyPwd, const KyPasswdPolicy &privatePwdPolicy) { m_userCertPathEdit->setText(userCert); m_privateKeyEdit->setText(privateKey); m_privateKeyPwdEdit->setText(privateKeyPwd); if (privatePwdPolicy == KYPASSWD_ISNOTREQUIRED) { m_userPwdOptionCombox->setCurrentIndex(PWD_OPTION_NOTREQUIRED_INDEX); } else { m_userPwdOptionCombox->setCurrentIndex(privatePwdPolicy); } } void VpnConfigPage::setStaticKeyAuthInfo(const QString &staticKey, const QString &vpnKeyDirection, const QString &localIp, const QString &remoteIp) { m_staticKeyPathEdit->setText(staticKey); m_localIpEdit->setText(localIp); m_remoteIpEdit->setText(remoteIp); if (vpnKeyDirection == KEY_DIRECTION_ZERO) { m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_ZERO_INDEX); } else if (vpnKeyDirection == KEY_DIRECTION_ONE) { m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_ONE_INDEX); } else { m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_NONE_INDEX); } } void VpnConfigPage::setAgentAuthInfo(const QString &userCert) { m_userCertPathEdit->setText(userCert); } void VpnConfigPage::setSmartCardAuthInfo(const QString &pin) { m_pinEdit->setText(pin); } void VpnConfigPage::setEapAuthInfo(const QString &username, const QString &userPwd) { m_usernameEdit->setText(username); m_userPwdEdit->setText(userPwd); } void VpnConfigPage::setNtDomain(const QString &ntDomain) { m_ntDomainEdit->setText(ntDomain); } void VpnConfigPage::setL2tpConfigInfo(const KyVpnConfig &vpnInfo) { if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_PASSWD) { m_authModeComboBox->setCurrentIndex(KYAUTH_PASSWD); setPwdAuthInfo(vpnInfo.m_userName, vpnInfo.m_userPasswd, vpnInfo.m_passwdPolicy); setNtDomain(vpnInfo.m_ntDomain); } } void VpnConfigPage::setPptpConfigInfo(const KyVpnConfig &vpnInfo) { m_authModeComboBox->clear(); setPwdAuthInfo(vpnInfo.m_userName, vpnInfo.m_userPasswd, vpnInfo.m_passwdPolicy); setNtDomain(vpnInfo.m_ntDomain); } void VpnConfigPage::setOpenVpnConfigInfo(const KyVpnConfig &vpnInfo) { if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_PASSWD) { m_authModeComboBox->setCurrentIndex(PASSWD_INDEX); setCaCertAuthInfo(vpnInfo.m_caCertificate); setPwdAuthInfo(vpnInfo.m_userName, vpnInfo.m_userPasswd, vpnInfo.m_passwdPolicy); } else if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_CERTIFICATE) { m_authModeComboBox->setCurrentIndex(CERTIFICATE_INDEX); setCaCertAuthInfo(vpnInfo.m_caCertificate); setKeyAuthInfo(vpnInfo.m_userCertificate, vpnInfo.m_userKey, vpnInfo.m_privatePasswd, vpnInfo.m_privatePasswdPolicy); } else if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_STATICPASSWD) { m_authModeComboBox->setCurrentIndex(STATICPASSWD_INDEX); setStaticKeyAuthInfo(vpnInfo.m_staticKey, vpnInfo.m_vpnKeyDir, vpnInfo.m_localAddress, vpnInfo.m_remoteAddress); } else if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_CERTIFICATEANDPASSWD) { m_authModeComboBox->setCurrentIndex(CERTIFICATEANDPASSWD_INDEX); setCaCertAuthInfo(vpnInfo.m_caCertificate); setKeyAuthInfo(vpnInfo.m_userCertificate, vpnInfo.m_userKey, vpnInfo.m_privatePasswd, vpnInfo.m_privatePasswdPolicy); setPwdAuthInfo(vpnInfo.m_userName, vpnInfo.m_userPasswd, vpnInfo.m_passwdPolicy); } } void VpnConfigPage::setSSwanVpnConfigInfo(const KyVpnConfig &vpnInfo) { if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_KEY) { m_authModeComboBox->setCurrentIndex(KEY_INDEX); setCaCertAuthInfo(vpnInfo.m_caCertificate); setKeyAuthInfo(vpnInfo.m_userCertificate, vpnInfo.m_userKey, vpnInfo.m_privatePasswd, vpnInfo.m_privatePasswdPolicy); } else if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_AGENT) { m_authModeComboBox->setCurrentIndex(AGENT_INDEX); setAgentAuthInfo(vpnInfo.m_userCertificate); } else if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_SMARTCARD) { m_authModeComboBox->setCurrentIndex(SMARTCARD_INDEX); setSmartCardAuthInfo(vpnInfo.m_pinId); } else if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_EAP) { m_authModeComboBox->setCurrentIndex(EAP_INDEX); setEapAuthInfo(vpnInfo.m_userName, vpnInfo.m_userPasswd); } } void VpnConfigPage::updateL2tpConfigInfo(KyVpnConfig &vpnInfo) { vpnInfo.m_authMethod = (KyAuthMethod)m_authModeComboBox->currentData().toInt(); vpnInfo.m_ntDomain = m_ntDomainEdit->text(); vpnInfo.m_userName = m_usernameEdit->text(); vpnInfo.m_userPasswd = m_userPwdEdit->text(); vpnInfo.m_passwdPolicy = (KyPasswdPolicy)m_userPwdOptionCombox->currentData().toInt(); } void VpnConfigPage::updatePptpConfigInfo(KyVpnConfig &vpnInfo) { vpnInfo.m_ntDomain = m_ntDomainEdit->text(); vpnInfo.m_userName = m_usernameEdit->text(); vpnInfo.m_userPasswd = m_userPwdEdit->text(); vpnInfo.m_passwdPolicy = (KyPasswdPolicy)m_userPwdOptionCombox->currentData().toInt(); } void VpnConfigPage::updateOpenVpnConfigInfo(KyVpnConfig &vpnInfo) { vpnInfo.m_authMethod = (KyAuthMethod)m_authModeComboBox->currentData().toInt(); if (vpnInfo.m_authMethod == KYAUTH_CERTIFICATE || vpnInfo.m_authMethod == KYAUTH_CERTIFICATEANDPASSWD) { vpnInfo.m_caCertificate = m_caCertPathEdit->text(); vpnInfo.m_userCertificate = m_userCertPathEdit->text(); vpnInfo.m_userKey = m_privateKeyEdit->text(); vpnInfo.m_privatePasswd = m_privateKeyPwdEdit->text(); vpnInfo.m_privatePasswdPolicy = (KyPasswdPolicy)m_pwdOptionCombox->currentData().toInt(); } if (vpnInfo.m_authMethod == KYAUTH_CERTIFICATEANDPASSWD || vpnInfo.m_authMethod == KYAUTH_PASSWD) { vpnInfo.m_userName = m_usernameEdit->text(); vpnInfo.m_userPasswd = m_userPwdEdit->text(); vpnInfo.m_passwdPolicy = (KyPasswdPolicy)m_userPwdOptionCombox->currentData().toInt(); vpnInfo.m_caCertificate = m_caCertPathEdit->text(); } if (vpnInfo.m_authMethod == KYAUTH_STATICPASSWD) { vpnInfo.m_staticKey = m_staticKeyPathEdit->text(); vpnInfo.m_vpnKeyDir = m_keyDirectionCombox->currentData().toString(); vpnInfo.m_localAddress = m_localIpEdit->text(); vpnInfo.m_remoteAddress = m_remoteIpEdit->text(); } } void VpnConfigPage::updateSSwanVpnConfigInfo(KyVpnConfig &vpnInfo) { vpnInfo.m_authMethod = (KyAuthMethod)m_authModeComboBox->currentData().toInt(); if (vpnInfo.m_authMethod == KYAUTH_KEY) { vpnInfo.m_caCertificate = m_caCertPathEdit->text(); vpnInfo.m_userCertificate = m_userCertPathEdit->text(); vpnInfo.m_userKey = m_privateKeyEdit->text(); vpnInfo.m_privatePasswd = m_privateKeyPwdEdit->text(); vpnInfo.m_privatePasswdPolicy = (KyPasswdPolicy)m_pwdOptionCombox->currentData().toInt(); } else if (vpnInfo.m_authMethod == KYAUTH_AGENT) { vpnInfo.m_userCertificate = m_userCertPathEdit->text(); } else if (vpnInfo.m_authMethod == KYAUTH_SMARTCARD) { vpnInfo.m_pinId = m_pinEdit->text(); } else if (vpnInfo.m_authMethod == KYAUTH_EAP) { vpnInfo.m_userName = m_usernameEdit->text(); vpnInfo.m_userPasswd = m_userPwdEdit->text(); } } void VpnConfigPage::onVpnTypeComboxIndexChanged() { switch (m_vpnTypeComboBox->currentData().toInt()) { case L2TP: m_authModeComboBox->clear(); m_authModeComboBox->addItem(tr("Password"), KYAUTH_PASSWD); onAuthModeComboxIndexChanged(); break; case OPEN_VPN: m_authModeComboBox->clear(); m_authModeComboBox->addItem(tr("Certificate(TLS)"), KYAUTH_CERTIFICATE); m_authModeComboBox->addItem(tr("Static key"), KYAUTH_STATICPASSWD); m_authModeComboBox->addItem(tr("Password"), KYAUTH_PASSWD); m_authModeComboBox->addItem(tr("Password and certificate(TLS)"), KYAUTH_CERTIFICATEANDPASSWD); onAuthModeComboxIndexChanged(); break; case PPTP: m_authModeComboBox->clear(); showPptpPwd(); break; case STRONG_SWAN: m_authModeComboBox->clear(); m_authModeComboBox->addItem(tr("Certificate/Private key"), KYAUTH_KEY); m_authModeComboBox->addItem(tr("Certificate/ssh-agent"), KYAUTH_AGENT); m_authModeComboBox->addItem(tr("Smart card"), KYAUTH_SMARTCARD); m_authModeComboBox->addItem("EAP", KYAUTH_EAP); onAuthModeComboxIndexChanged(); break; default: break; } Q_EMIT vpnTypeChanged(VpnType(m_vpnTypeComboBox->currentData().toInt())); } void VpnConfigPage::onAuthModeComboxIndexChanged() { switch (m_authModeComboBox->currentData().toInt()) { case KYAUTH_PASSWD: if (m_vpnTypeComboBox->currentData().toInt() == L2TP) { showL2tpPwd(); } else if (m_vpnTypeComboBox->currentData().toInt() == OPEN_VPN) { showOpenVpnPwd(); } break; case KYAUTH_KEY: showSswanCertPrivteKey(); break; case KYAUTH_AGENT: showSswanCertSsh(); break; case KYAUTH_SMARTCARD: showSswanSmartCard(); break; case KYAUTH_EAP: showSswanEap(); break; case KYAUTH_CERTIFICATE: showOpenVpnTls(); break; case KYAUTH_CERTIFICATEANDPASSWD: showOpenVpnPwdTls(); break; case KYAUTH_STATICPASSWD: showOpenVpnStaticKey(); break; default: qDebug() << LOG_FLAG << "Unknow VPN auth mothod"; break; } } void VpnConfigPage::setEnableOfConfirmBtn() { Q_EMIT setConfigPageState(checkConfirmBtnIsEnabled()); } void VpnConfigPage::onPrivateKeyButtonClicked() { QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a private key"), "recent:///", tr("Key Files (*.key *.pem *.der *.p12 *.pfx)")); if (!fileName.isNull()) { m_privateKeyEdit->blockSignals(true); m_privateKeyEdit->setText(fileName); m_privateKeyEdit->blockSignals(false); } } void VpnConfigPage::onCaCertButtonClicked() { QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a CA certificate"), "recent:///", tr("CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx)")); if (!fileName.isNull()) { m_caCertPathEdit->blockSignals(true); m_caCertPathEdit->setText(fileName); m_caCertPathEdit->blockSignals(false); } } void VpnConfigPage::onUserCertButtonClicked() { QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a User certificate"), "recent:///", tr("CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx)")); if (!fileName.isNull()) { m_userCertPathEdit->blockSignals(true); m_userCertPathEdit->setText(fileName); m_userCertPathEdit->blockSignals(false); } } void VpnConfigPage::onStaticKeyButtonClicked() { QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a Static key"), "recent:///", tr("Key Files (*.key *.pem *.der *.p12 *.pfx)")); if (!fileName.isNull()) { m_staticKeyPathEdit->blockSignals(true); m_staticKeyPathEdit->setText(fileName); m_staticKeyPathEdit->blockSignals(false); } } bool VpnConfigPage::checkL2tpIsChanged(const KyVpnConfig &vpnInfo) { bool isChanged = false; if (vpnInfo.m_ntDomain != m_ntDomainEdit->text() || vpnInfo.m_userName != m_usernameEdit->text() || vpnInfo.m_userPasswd != m_userPwdEdit->text() || vpnInfo.m_passwdPolicy != m_userPwdOptionCombox->currentData().toInt()) { isChanged = true; } return isChanged; } bool VpnConfigPage::checkPptpIsChanged(const KyVpnConfig &vpnInfo) { bool isChanged = false; if (vpnInfo.m_ntDomain != m_ntDomainEdit->text() || vpnInfo.m_userName != m_usernameEdit->text() || vpnInfo.m_userPasswd != m_userPwdEdit->text() || vpnInfo.m_passwdPolicy != m_userPwdOptionCombox->currentData().toInt()) { isChanged = true; } return isChanged; } bool VpnConfigPage::checkOpenVpnIsChanged(const KyVpnConfig &vpnInfo) { bool isChanged = false; int currentAuthMethod = m_authModeComboBox->currentData().toInt(); if (vpnInfo.m_authMethod != currentAuthMethod) { isChanged = true; } if (currentAuthMethod == KYAUTH_PASSWD || currentAuthMethod == KYAUTH_CERTIFICATEANDPASSWD) { if (vpnInfo.m_userName != m_usernameEdit->text() || vpnInfo.m_userPasswd != m_userPwdEdit->text() || vpnInfo.m_passwdPolicy != m_userPwdOptionCombox->currentData().toInt() || vpnInfo.m_caCertificate != m_caCertPathEdit->text()) { isChanged = true; } } if (currentAuthMethod == KYAUTH_CERTIFICATEANDPASSWD || currentAuthMethod == KYAUTH_CERTIFICATE) { if (vpnInfo.m_caCertificate != m_caCertPathEdit->text() || vpnInfo.m_userCertificate != m_userCertPathEdit->text() || vpnInfo.m_userKey != m_privateKeyEdit->text() || vpnInfo.m_privatePasswd != m_privateKeyPwdEdit->text() || vpnInfo.m_privatePasswdPolicy != m_pwdOptionCombox->currentData().toInt()) { isChanged = true; } } if (currentAuthMethod == KYAUTH_STATICPASSWD) { if (vpnInfo.m_staticKey != m_staticKeyPathEdit->text() || vpnInfo.m_vpnKeyDir != m_keyDirectionCombox->currentData().toString() || vpnInfo.m_localAddress != m_localIpEdit->text() || vpnInfo.m_remoteAddress != m_localIpEdit->text()) { isChanged = true; } } return isChanged; } bool VpnConfigPage::checkStrongSwanIsChanged(const KyVpnConfig &vpnInfo) { bool isChanged = false; int currentAuthMethod = m_authModeComboBox->currentData().toInt(); if (vpnInfo.m_authMethod != currentAuthMethod) { isChanged = true; } if (currentAuthMethod == KYAUTH_KEY) { if (vpnInfo.m_caCertificate != m_caCertPathEdit->text() || vpnInfo.m_userCertificate != m_userCertPathEdit->text() || vpnInfo.m_userKey != m_privateKeyEdit->text() || vpnInfo.m_privatePasswd != m_privateKeyPwdEdit->text() || vpnInfo.m_privatePasswdPolicy != m_pwdOptionCombox->currentData().toInt()) { isChanged = true; } }else if (currentAuthMethod == KYAUTH_AGENT) { if (vpnInfo.m_userCertificate != m_userCertPathEdit->text()) { isChanged = true; } } else if (currentAuthMethod == KYAUTH_SMARTCARD) { if (vpnInfo.m_pinId != m_pinEdit->text()) { isChanged = true; } } else if (currentAuthMethod == KYAUTH_EAP) { if (vpnInfo.m_userName != m_usernameEdit->text() || vpnInfo.m_userPasswd != m_userPwdEdit->text()) { isChanged = true; } } return isChanged; } kylin-nm/src-vpn/frontend/vpndetails/vpnaddpage.cpp0000664000175000017500000002013415167651420021442 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #include "vpnaddpage.h" #include #include "vpnconfigpage.h" #define VPNADDPAGE_SIZE 520,272 #define MAINLAYOUT_MARGINS 24, 16, 24, 24 #define MAINLAYOUT_SPACE 24 #define NULL_MARGINS 0,0,0,0 #define NULL_SPACE 0 #define VPNADDPAGE_NAME_MAX_LENGTH 32 #define VPNADDPAGE_LABLE_FIXEDWIDTH 112 #define VPNADDPAGE_COMBOBOX_FIXEDWIDTH 360 #define VPNADDPAGE_INPUTBOX_FIXEDWIDTH 360 vpnAddPage::vpnAddPage(QWidget *parent) : QWidget(parent) { m_vpnConnOperation = new KyVpnConnectOperation(this); initWindow(); initUI(); initConnection(); centerToScreen(); } void vpnAddPage::centerToScreen() { QRect desk_rect; QScreen *currentScreen = QGuiApplication::screenAt(QCursor::pos()); if (currentScreen) { desk_rect = currentScreen->geometry(); } else { desk_rect=QGuiApplication::primaryScreen()->geometry(); } int desk_x = desk_rect.width(); int desk_y = desk_rect.height(); int x = this->width(); int y = this->height(); this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); } void vpnAddPage::initWindow() { this->setFixedSize(VPNADDPAGE_SIZE); this->setWindowTitle(tr("create VPN")); this->setWindowFlag(Qt::WindowMinMaxButtonsHint,false); this->setAttribute(Qt::WA_DeleteOnClose); } void vpnAddPage::initUI() { QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(MAINLAYOUT_MARGINS); mainLayout->setSpacing(MAINLAYOUT_SPACE); initVpnTypeFrame(); initVpnNameFrame(); initVpnServerFrame(); initButtonFrame(); onSetConfimBtnEnable(); mainLayout->addWidget(m_vpnTypeFrame); mainLayout->addWidget(m_vpnNameFrame); mainLayout->addWidget(m_vpnServerFrame); mainLayout->addStretch(); mainLayout->addWidget(m_buttonFrame); this->setLayout(mainLayout); } void vpnAddPage::initVpnTypeFrame() { m_vpnTypeFrame = new QFrame(this); m_vpnTypeFrame->setFrameShape(QFrame::Shape::NoFrame); QHBoxLayout *typeLayout = new QHBoxLayout(m_vpnTypeFrame); typeLayout->setContentsMargins(NULL_MARGINS); typeLayout->setSpacing(NULL_SPACE); QLabel *vpnTypeLabel = new QLabel(tr("VPN Type"), this); vpnTypeLabel->setFixedWidth(VPNADDPAGE_LABLE_FIXEDWIDTH); m_vpnTypeComboBox = new QComboBox(this); m_vpnTypeComboBox->setInsertPolicy(QComboBox::NoInsert); m_vpnTypeComboBox->setFixedWidth(VPNADDPAGE_COMBOBOX_FIXEDWIDTH); m_vpnTypeComboBox->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); m_vpnTypeComboBox->addItem("L2TP", L2TP); m_vpnTypeComboBox->addItem("open VPN", OPEN_VPN); m_vpnTypeComboBox->addItem("PPTP", PPTP); m_vpnTypeComboBox->addItem("strong-swan", STRONG_SWAN); typeLayout->addWidget(vpnTypeLabel); typeLayout->addWidget(m_vpnTypeComboBox); m_vpnTypeFrame->setLayout(typeLayout); } void vpnAddPage::initVpnNameFrame() { m_vpnNameFrame = new QFrame(this); m_vpnNameFrame->setFrameShape(QFrame::Shape::NoFrame); QHBoxLayout *nameLayout = new QHBoxLayout(m_vpnNameFrame); nameLayout->setContentsMargins(NULL_MARGINS); nameLayout->setSpacing(NULL_SPACE); QLabel *vpnNameLabel = new QLabel(tr("VPN Name"), this); vpnNameLabel->setFixedWidth(VPNADDPAGE_LABLE_FIXEDWIDTH); m_vpnNameLineEdit = new QLineEdit(this); m_vpnNameLineEdit->setFixedWidth(VPNADDPAGE_INPUTBOX_FIXEDWIDTH); m_vpnNameLineEdit->setMaxLength(VPNADDPAGE_NAME_MAX_LENGTH); m_vpnNameLineEdit->setPlaceholderText(tr("Required")); //必填 nameLayout->addWidget(vpnNameLabel); nameLayout->addWidget(m_vpnNameLineEdit); m_vpnNameFrame->setLayout(nameLayout); } void vpnAddPage::initVpnServerFrame() { m_vpnServerFrame = new QFrame(this); m_vpnServerFrame->setFrameShape(QFrame::Shape::NoFrame); QHBoxLayout *serverLayout = new QHBoxLayout(m_vpnServerFrame); serverLayout->setContentsMargins(NULL_MARGINS); serverLayout->setSpacing(NULL_SPACE); QLabel *vpnServerLabel = new QLabel(tr("VPN Server"), this); vpnServerLabel->setFixedWidth(VPNADDPAGE_LABLE_FIXEDWIDTH); m_vpnServerLineEdit = new QLineEdit(this); m_vpnServerLineEdit->setFixedWidth(VPNADDPAGE_INPUTBOX_FIXEDWIDTH); m_vpnServerLineEdit->setPlaceholderText(tr("Required")); //必填 serverLayout->addWidget(vpnServerLabel); serverLayout->addWidget(m_vpnServerLineEdit); m_vpnServerFrame->setLayout(serverLayout); // IP的正则格式限制 QRegularExpression rxIp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); QRegularExpressionValidator *ipExpVal = new QRegularExpressionValidator(rxIp, this); m_vpnServerLineEdit->setValidator(ipExpVal); } void vpnAddPage::initButtonFrame() { m_buttonFrame = new QFrame(this); QHBoxLayout *buttonLayout = new QHBoxLayout(m_buttonFrame); buttonLayout->setContentsMargins(NULL_MARGINS); buttonLayout->setSpacing(NULL_SPACE); m_autoConnectBox = new QCheckBox(this); m_autoConnectBox->setText(tr("Auto Connection")); m_confimBtn = new QPushButton(this); m_confimBtn->setText(tr("Confirm")); m_cancelBtn = new QPushButton(this); m_cancelBtn->setText(tr("Cancel")); buttonLayout->addWidget(m_autoConnectBox); buttonLayout->addStretch(); buttonLayout->addWidget(m_cancelBtn); buttonLayout->addSpacing(16); buttonLayout->addWidget(m_confimBtn); m_buttonFrame->setLayout(buttonLayout); } void vpnAddPage::initConnection() { if (m_vpnNameLineEdit != nullptr) { connect(m_vpnNameLineEdit, &QLineEdit::textChanged, this, &vpnAddPage::onSetConfimBtnEnable); } if (m_vpnServerLineEdit != nullptr) { connect(m_vpnServerLineEdit, &QLineEdit::textChanged, this, &vpnAddPage::onSetConfimBtnEnable); } if (m_cancelBtn != nullptr) { connect(m_cancelBtn, &QPushButton::clicked, [&] () {this->close();}); } if (m_confimBtn != nullptr) { connect(m_confimBtn, &QPushButton::clicked, this, &vpnAddPage::onConfimBtnClicked); } } bool vpnAddPage::checkConfimBtnIsEnabled() { if (m_vpnNameLineEdit->text().isEmpty()) { qDebug() << "ipv4address empty or invalid"; return false; } if (m_vpnServerLineEdit->text().isEmpty()) { qDebug() << "ipv4 netMask empty or invalid"; return false; } return true; } void vpnAddPage::onSetConfimBtnEnable() { m_confimBtn->setEnabled(checkConfimBtnIsEnabled()); } void vpnAddPage::onConfimBtnClicked() { //新建有线连接 qDebug() << "Confirm create vpn connect"; if (!createVpnConnect()) { // setNetdetailSomeEnable(true); // return; } close(); } bool vpnAddPage::createVpnConnect() { KyVpnConfig vpnSetting; QString connectName = m_vpnNameLineEdit->text(); vpnSetting.m_gateway = m_vpnServerLineEdit->text(); vpnSetting.setConnectName(connectName); vpnSetting.m_vpnName = connectName; vpnSetting.m_isAutoConnect = m_autoConnectBox->isChecked(); vpnSetting.m_vpnType = (KyVpnType)m_vpnTypeComboBox->currentData().toInt(); m_vpnConnOperation->createVpnConnect(vpnSetting); return true; } vpnAddPage::~vpnAddPage() { Q_EMIT this->closed(); } void vpnAddPage::paintEvent(QPaintEvent *event) { QPalette pal = qApp->palette(); QPainter painter(this); painter.setBrush(pal.color(QPalette::Base)); painter.drawRect(this->rect()); painter.fillRect(rect(), QBrush(pal.color(QPalette::Base))); return QWidget::paintEvent(event); } kylin-nm/src-vpn/frontend/vpndetails/vpnipv4page.cpp0000664000175000017500000002411615167651420021600 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #include "vpnipv4page.h" #include "math.h" #include #define NO_LAYOUT_MARGINS 0, 0, 0, 0 #define NO_SPACE 0 #define HLAYOUT_SPACING 16 #define VLAYOUT_SPACING 24 #define AUTO_CONFIG 0 #define MANUAL_CONFIG 1 #define LOG_FLAG "[VPN IPv4Page]" VpnIpv4Page::VpnIpv4Page(QWidget *parent) : QFrame(parent) { initUI(); initConnect(); } void VpnIpv4Page::setVpnIpv4Info(const KyVpnConfig &vpnInfo) { if (vpnInfo.m_ipv4ConfigIpType == CONFIG_IP_DHCP) { m_ipv4ConfigCombox->setCurrentIndex(AUTO_CONFIG); } else { m_ipv4ConfigCombox->setCurrentIndex(MANUAL_CONFIG); if (!vpnInfo.m_ipv4Address.isEmpty()) { m_ipv4addressEdit->setText(vpnInfo.m_ipv4Address.at(0).ip().toString()); m_netMaskEdit->setText(vpnInfo.m_ipv4Address.at(0).netmask().toString()); m_gateWayEdit->setText(vpnInfo.m_ipv4Address.at(0).gateway().toString()); } } } void VpnIpv4Page::setDns(const QString &firstDns) { m_dnsServerEdit->setText(firstDns); } void VpnIpv4Page::setSearchDomain(const QString &searchDomain) { m_searchDomainEdit->setText(searchDomain); } void VpnIpv4Page::setDhcpClientId(const QString &dhcpId) { m_dhcpClientIdEdit->setText(dhcpId); } bool VpnIpv4Page::checkIsChanged(const KyVpnConfig &vpnInfo) { bool isChanged = false; if (m_ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { if (vpnInfo.m_ipv4ConfigIpType != CONFIG_IP_DHCP) { qDebug() << LOG_FLAG << "ipv4ConfigType change to Auto"; isChanged = true; } } else { if (vpnInfo.m_ipv4ConfigIpType != CONFIG_IP_MANUAL) { qDebug() << LOG_FLAG << "ipv4ConfigType change to Manual"; isChanged = true; } if (!vpnInfo.m_ipv4Address.isEmpty()) { if(vpnInfo.m_ipv4Address.at(0).ip().toString() != m_ipv4addressEdit->text() || vpnInfo.m_ipv4Address.at(0).netmask().toString() != getNetMaskText(m_netMaskEdit->text()) || vpnInfo.m_ipv4Address.at(0).gateway().toString() != m_gateWayEdit->text()) { isChanged = true; } } } if (!vpnInfo.m_ipv4Dns.isEmpty() && vpnInfo.m_ipv4Dns.at(0).toString() != m_dnsServerEdit->text()) { isChanged = true; } if (!vpnInfo.m_ipv4DnsSearch.isEmpty() && vpnInfo.m_ipv4DnsSearch.at(0) != m_searchDomainEdit->text()) { isChanged = true; } if (vpnInfo.m_ipv4DhcpClientId != m_dhcpClientIdEdit->text()){ isChanged = true; } return isChanged; } void VpnIpv4Page::updateVpnIpv4Info(KyVpnConfig &vpnInfo) { if (m_ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { QString ipv4address(""); QString netMask(""); QString gateWay(""); vpnInfo.setIpConfigType(IPADDRESS_V4, CONFIG_IP_DHCP); qDebug() << LOG_FLAG << "IPv4 method" << vpnInfo.m_ipv4ConfigIpType; qDebug() << LOG_FLAG << "Update IPv4 info finished"; } else { QString ipv4address =m_ipv4addressEdit->text(); QString netMask = getNetMaskText(m_netMaskEdit->text()); QString gateWay = m_gateWayEdit->text(); qDebug() << ipv4address << netMask << gateWay; vpnInfo.setIpConfigType(IPADDRESS_V4, CONFIG_IP_MANUAL); vpnInfo.dumpInfo(); qDebug() << LOG_FLAG << "Update IPv4 info finished"; } QList ipv4DnsList; ipv4DnsList.clear(); if (!m_dnsServerEdit->text().isEmpty()) { ipv4DnsList.append(QHostAddress(m_dnsServerEdit->text())); } vpnInfo.m_ipv4DnsSearch.clear(); vpnInfo.m_ipv4DnsSearch.append(m_searchDomainEdit->text()); vpnInfo.m_ipv4DhcpClientId = m_dhcpClientIdEdit->text(); } void VpnIpv4Page::initUI() { /**********控件**********/ m_configLabel = new QLabel(this); m_addressLabel = new QLabel(this); m_maskLabel = new QLabel(this); m_gateWayLabel = new QLabel(this); m_dnsServerLabel = new QLabel(this); m_searchDomainLabel = new QLabel(this); m_dhcpClientIdLabel = new QLabel(this); m_ipv4ConfigCombox =new QComboBox(this); m_ipv4addressEdit = new QLineEdit(this); m_netMaskEdit = new QLineEdit(this); m_gateWayEdit = new QLineEdit(this); m_dnsServerEdit = new QLineEdit(this); m_searchDomainEdit = new QLineEdit(this); m_dhcpClientIdEdit = new QLineEdit(this); /**********布局**********/ QFormLayout *mainLayout = new QFormLayout(this); mainLayout->setContentsMargins(NO_LAYOUT_MARGINS); mainLayout->setHorizontalSpacing(HLAYOUT_SPACING); mainLayout->setVerticalSpacing(VLAYOUT_SPACING); mainLayout->addRow(m_configLabel, m_ipv4ConfigCombox); mainLayout->addRow(m_addressLabel, m_ipv4addressEdit); mainLayout->addRow(m_maskLabel, m_netMaskEdit); mainLayout->addRow(m_gateWayLabel, m_gateWayEdit); mainLayout->addRow(m_dnsServerLabel, m_dnsServerEdit); mainLayout->addRow(m_searchDomainLabel, m_searchDomainEdit); mainLayout->addRow(m_dhcpClientIdLabel, m_dhcpClientIdEdit); /**********控件显示**********/ m_configLabel->setText(tr("IPv4 Config")); m_addressLabel->setText(tr("Address")); m_maskLabel->setText(tr("Netmask")); m_gateWayLabel->setText(tr("Default Gateway")); m_dnsServerLabel->setText(tr("DNS Server")); m_searchDomainLabel->setText(tr("Search Domain")); //搜索域 m_dhcpClientIdLabel->setText(tr("DHCP Client ID")); //DHCP客户端ID m_ipv4ConfigCombox->addItem(tr("Auto(DHCP)"), AUTO_CONFIG); //"自动(DHCP)" m_ipv4ConfigCombox->addItem(tr("Manual"), MANUAL_CONFIG); //"手动" // IP的正则格式限制 QRegularExpression rxIp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); QRegularExpressionValidator *ipExpVal = new QRegularExpressionValidator(rxIp, this); m_ipv4addressEdit->setValidator(ipExpVal); m_netMaskEdit->setValidator(ipExpVal); m_gateWayEdit->setValidator(ipExpVal); m_dnsServerEdit->setValidator(ipExpVal); } void VpnIpv4Page::initConnect() { if (m_ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { setManualEnabled(false); } else if (m_ipv4ConfigCombox->currentIndex() == MANUAL_CONFIG) { setManualEnabled(true); } connect(m_ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(onConfigChanged(int))); connect(m_ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfConfirmBtn())); connect(m_ipv4addressEdit, &QLineEdit::textChanged, this, &VpnIpv4Page::setEnableOfConfirmBtn); connect(m_netMaskEdit, &QLineEdit::textChanged, this, &VpnIpv4Page::setEnableOfConfirmBtn); connect(m_gateWayEdit, &QLineEdit::textChanged, this, &VpnIpv4Page::setEnableOfConfirmBtn); connect(m_dnsServerEdit, &QLineEdit::textChanged, this, &VpnIpv4Page::setEnableOfConfirmBtn); connect(m_searchDomainEdit, &QLineEdit::textChanged, this, &VpnIpv4Page::setEnableOfConfirmBtn); connect(m_dhcpClientIdEdit, &QLineEdit::textChanged, this, &VpnIpv4Page::setEnableOfConfirmBtn); } void VpnIpv4Page::setManualEnabled(bool state) { m_addressLabel->setEnabled(state); m_maskLabel->setEnabled(state); m_gateWayLabel->setEnabled(state); m_ipv4addressEdit->setEnabled(state); m_netMaskEdit->setEnabled(state); m_gateWayEdit->setEnabled(state); } bool VpnIpv4Page::getTextEditState(QString text) { if (text.isEmpty()) { return true; } // IP地址正则表达式,包含开始和结束锚点确保完全匹配 QRegularExpression rx("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); // 进行匹配并返回结果 QRegularExpressionMatch match = rx.match(text); return match.hasMatch(); } bool VpnIpv4Page::netMaskIsValide(QString text) { if (getTextEditState(text)) { return true; } else { if (text.length() > 0 && text.length() < 3) { int num = text.toInt(); if (num > 0 && num < 33) { return true; } } } return false; } QString VpnIpv4Page::getNetMaskText(QString text) { if (text.length() > 2) { return text; } int num = text.toInt(); QStringList list; list << "0" << "0" << "0" << "0"; int count = 0; while (num - 8 >= 0) { list[count] = "255"; num = num - 8; count ++; } if (num > 0) { int size = pow(2, 8) - pow(2,(8-num)); list[count] = QString::number(size); } return QString("%1.%2.%3.%4").arg(list[0],list[1],list[2],list[3]); } bool VpnIpv4Page::checkConfirmBtnIsEnabled() { if (m_ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { return true; } else { if (m_ipv4addressEdit->text().isEmpty() || !getTextEditState(m_ipv4addressEdit->text())) { qDebug() << LOG_FLAG << "IPv4 address empty or invalid"; return false; } if (m_netMaskEdit->text().isEmpty() || !netMaskIsValide(m_netMaskEdit->text())) { qDebug() << LOG_FLAG << "IPv4 netMask empty or invalid"; return false; } } return true; } void VpnIpv4Page::setEnableOfConfirmBtn() { Q_EMIT setIpv4PageState(checkConfirmBtnIsEnabled()); } void VpnIpv4Page::onConfigChanged(int index) { if (index == AUTO_CONFIG) { m_ipv4addressEdit->clear(); m_netMaskEdit->clear(); m_gateWayEdit->clear(); setManualEnabled(false); } else if (index == MANUAL_CONFIG) { setManualEnabled(true); } } kylin-nm/src-vpn/frontend/vpnobject.h0000664000175000017500000000526015167651420016622 0ustar fengfeng/* * * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * */ #ifndef VPNOBJECT_H #define VPNOBJECT_H #include #include #include #include #include #include "vpnpage.h" #include "vpnaddpage.h" class VpnPage; #define VISIBLE "visible" #define GSETTINGS_VPNICON_VISIBLE "org.ukui.kylin-nm.vpnicon" //const QByteArray GSETTINGS_VPNICON_VISIBLE = "org.ukui.kylin-nm.vpnicon"; #include "ukuiwindowhelper/ukuiwindowhelper.h" class vpnObject : public QMainWindow { Q_OBJECT public: explicit vpnObject(QMainWindow *parent = nullptr); ~vpnObject(); void getVirtualList(QVector &vector); //Vpn连接删除 void deleteVpn(const QString &connUuid); //有线连接断开 void activateVpn(const QString& connUuid); void deactivateVpn(const QString& connUuid); void showDetailPage(const QString& connUuid); void showVpnAddWidget(); private: void initUI(); void initTrayIcon(); void initVpnIconVisible(); void initDbusConnnect(); bool launchApp(QString desktopFile); void runExternalApp(); private: VpnPage *m_vpnPage = nullptr; QSystemTrayIcon * m_vpnTrayIcon = nullptr; QGSettings * m_vpnGsettings; //VPN配置文件 double tran =1; QGSettings *StyleSettings = nullptr; QWidget * vpnWidget = nullptr; QDBusInterface * m_positionInterface = nullptr; bool m_isShowInCenter = false; vpnAddPage *m_vpnAddPage = nullptr; UkuiWindowHelper *m_uwin = nullptr; public Q_SLOTS: void onShowMainWindow(); private Q_SLOTS: void onTrayIconActivated(QSystemTrayIcon::ActivationReason reason); void onTabletModeChanged(bool mode); Q_SIGNALS: void vpnAdd(QStringList info); void vpnRemove(QString dbusPath); void vpnUpdate(QStringList info); void vpnActiveConnectionStateChanged(QString uuid, int status); void activateFailed(QString errorMessage); void deactivateFailed(QString errorMessage); void mainWindowVisibleChanged(const bool &visible); }; #endif // VPNOBJECT_H kylin-nm/src-vpn/frontend/single-pages/0000775000175000017500000000000015167651420017032 5ustar fengfengkylin-nm/src-vpn/frontend/single-pages/vpnpage.h0000664000175000017500000001063415167651420020647 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef VPNPAGE_H #define VPNPAGE_H #include "divider.h" #include #include #include #include #include #include #include #include #include "list-items/listitem.h" #include "list-items/vpnlistitem.h" #include "single-pages/singlepage.h" #include "ukuiwindowhelper/ukuiwindowhelper.h" #define VPNPAGE_LAYOUT_MARGINS 0,0,0,0 #define VPN_LIST_SPACING 0 #define ITEM_HEIGHT 50 #define ITEM_SPACE 8 #define PAGE_SPACE 22 #define LOG_FLAG "[VpnPage]" class VpnListItem; class VpnPage : public SinglePage { Q_OBJECT public: explicit VpnPage(QWidget *parent = nullptr); ~VpnPage(); //for dbus void getVirtualList(QVector &vector); void deleteVpn(const QString &connUuid); void activateVpn(const QString& connUuid); void deactivateVpn(const QString& connUuid); void showDetailPage(QString uuid); protected: bool eventFilter(QObject *watched, QEvent *event); private: void initPanelGSettings(); void initUI(); void initVpnArea(); void resetPageHeight(); inline void initDeviceCombox() { return; } QListWidgetItem *insertNewItem(KyConnectItem *itemData, QListWidget *listWidget); QListWidgetItem *addNewItem(KyConnectItem *itemData, QListWidget *listWidget); bool removeConnectionItem(QMap &connectMap, QListWidget *vpnListWidget, QString path); void constructItemArea(); void updateConnectionArea(KyConnectItem *p_newItem); void updateActivatedConnectionArea(KyConnectItem *p_newItem); void updateConnectionState(QMap &connectMap, QListWidget *vpnListWidget, QString uuid, ConnectState state); void updateActiveConnectionProperty(KyConnectItem *p_connectItem); void updateConnectionProperty(KyConnectItem *p_connectItem); void sendVpnUpdateSignal(KyConnectItem *p_connectItem); void sendVpnAddSignal(KyConnectItem *p_connectItem); void sendVpnStateChangeSignal(QString uuid, ConnectState state); void clearConnectionMap(QMap &connectMap, QListWidget *vpnListWidget); void deleteConnectionMapItem(QMap &connectMap, QListWidget *vpnListWidget, QString uuid); void resetWindowPosition(); void resetListWidgetWidth(); Q_SIGNALS: void vpnAdd(QStringList info); void vpnRemove(QString dbusPath); void vpnUpdate(QStringList info); void vpnActiveConnectionStateChanged(QString uuid, int status); void vpnConnectChanged(int state); private Q_SLOTS: void onConnectionStateChange(QString uuid, NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason); void onAddConnection(QString uuid); void onRemoveConnection(QString path); void onUpdateConnection(QString uuid); void onShowControlCenter(); private: KyVpnConnectOperation *m_vpnConnectOperation = nullptr; KyActiveConnectResourse *m_activeResourse = nullptr; //激活的连接 KyConnectResourse *m_connectResourse = nullptr; //未激活的连接 QMap m_vpnItemMap; QMap m_activeItemMap; //获取任务栏位置和大小 QGSettings *m_panelGSettings = nullptr; int m_panelPosition; int m_panelSize; public Q_SLOTS: void showUI(); }; #endif // LANPAGE_H kylin-nm/src-vpn/frontend/single-pages/singlepage.h0000664000175000017500000000626415167651420021331 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef SINGLEPAGE_H #define SINGLEPAGE_H #include "divider.h" #include "kylable.h" #include #include #include #include #include #include #include #include #include #include #include #include "kylinnetworkdeviceresource.h" #include "kwidget.h" #include "kswitchbutton.h" #include "ukuiwindowhelper/ukuiwindowhelper.h" using namespace kdk; #define MAIN_LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_SPACING 0 #define TITLE_FRAME_HEIGHT 50 #define SETTING_FRAME_HEIGHT 56 #define TITLE_LAYOUT_MARGINS 24,0,24,0 #define NET_LAYOUT_MARGINS 8,4,0,4 #define TEXT_HEIGHT 20 #define SETTINGS_LAYOUT_MARGINS 23,0,24,0 #define MAX_ITEMS 4 #define MAX_WIDTH 400 #define MIN_WIDTH 400 #define SCROLL_STEP 4 #define TRANSPARENCY "transparency" #define TRANSPARENCY_GSETTINGS "org.ukui.control-center.personalise" class SinglePage : public QWidget { Q_OBJECT public: explicit SinglePage(QWidget *parent = nullptr); ~SinglePage(); static void showDesktopNotify(const QString &message, QString soundName); Q_SIGNALS: void activateFailed(QString errorMessage); void deactivateFailed(QString errorMessage); private Q_SLOTS: void onTransChanged(); void onThemeChanged(const QString &key); void setThemePalette(); protected: void paintEvent(QPaintEvent *event); void keyPressEvent(QKeyEvent *event); protected: void initUI(); void initTransparency(); void paintWithTrans(); private: void initWindowProperties(); void initWindowTheme(); protected: QVBoxLayout * m_mainLayout = nullptr; QLabel * m_titleLabel = nullptr; QFrame * m_titleFrame = nullptr; QHBoxLayout * m_titleLayout = nullptr; QFrame * m_listFrame = nullptr; QListWidget * m_listWidget = nullptr; QVBoxLayout * m_listLayout = nullptr; QFrame * m_settingsFrame = nullptr; QHBoxLayout * m_settingsLayout = nullptr; KyLable * m_settingsLabel = nullptr; Divider * m_netDivider = nullptr; Divider * m_setDivider = nullptr; QGSettings * m_transGsettings = nullptr; double m_transparency = 1.0; //透明度 //监听主题的Gsettings QGSettings * m_styleGsettings = nullptr; QLabel *m_emptyLabel = nullptr; UkuiWindowHelper *m_uwin; }; #endif // TABPAGE_H kylin-nm/src-vpn/frontend/single-pages/vpnpage.cpp0000664000175000017500000006335715167651420021214 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include "vpnpage.h" #include #include #include #include "windowmanager/windowmanager.h" #define PANEL_SETTINGS "org.ukui.panel.settings" #define PANEL_SIZE_KEY "panelsize" #define PANEL_POSITION_KEY "panelposition" #define MARGIN 8 #define PANEL_TOP 1 #define PANEL_LEFT 2 #define PANEL_RIGHT 3 #define VPN_PAGE_HEIGHT 370 VpnPage::VpnPage(QWidget *parent) : SinglePage(parent) { m_activeResourse = new KyActiveConnectResourse(this); m_connectResourse = new KyConnectResourse(this); m_vpnConnectOperation = new KyVpnConnectOperation(this); initPanelGSettings(); initUI(); initVpnArea(); installEventFilter(this); connect(m_activeResourse, &KyActiveConnectResourse::stateChangeReason, this, &VpnPage::onConnectionStateChange); connect(m_activeResourse, &KyActiveConnectResourse::activeConnectRemove, this, [=] (QString activeConnectUuid) { sendVpnStateChangeSignal(activeConnectUuid,Deactivated); } ); connect(m_connectResourse, &KyConnectResourse::connectionAdd, this, &VpnPage::onAddConnection); connect(m_connectResourse, &KyConnectResourse::connectionRemove, this, &VpnPage::onRemoveConnection); connect(m_connectResourse, &KyConnectResourse::connectionUpdate, this, &VpnPage::onUpdateConnection); connect(m_vpnConnectOperation, &KyVpnConnectOperation::activateConnectionError, this, &VpnPage::activateFailed); connect(m_vpnConnectOperation, &KyVpnConnectOperation::deactivateConnectionError, this, &VpnPage::deactivateFailed); connect(KX11Extras::self(), &KX11Extras::activeWindowChanged, this, [&](WId activeWindowId){ if (activeWindowId != this->winId() && activeWindowId != 0) { hide(); } }); } VpnPage::~VpnPage() { } void VpnPage::deleteConnectionMapItem(QMap &connectMap, QListWidget *vpnListWidget, QString uuid) { QListWidgetItem *p_listWidgetItem = connectMap.value(uuid); if (p_listWidgetItem) { connectMap.remove(uuid); VpnListItem *p_vpnItem = (VpnListItem *)vpnListWidget->itemWidget(p_listWidgetItem); vpnListWidget->removeItemWidget(p_listWidgetItem); delete p_vpnItem; p_vpnItem = nullptr; delete p_listWidgetItem; p_listWidgetItem = nullptr; } return; } void VpnPage::clearConnectionMap(QMap &connectMap, QListWidget *vpnListWidget) { QMap::iterator iter; iter = connectMap.begin(); while (iter != connectMap.end()) { qDebug()<<"[VpnPage] clear connection map item"<< iter.key(); QListWidgetItem *p_widgetItem = iter.value(); VpnListItem *p_vpnItem = (VpnListItem *)vpnListWidget->itemWidget(p_widgetItem); vpnListWidget->removeItemWidget(p_widgetItem); delete p_vpnItem; p_vpnItem = nullptr; delete p_widgetItem; p_widgetItem = nullptr; iter = connectMap.erase(iter); } return; } void VpnPage::constructItemArea() { QList activedList; QList netList; activedList.clear(); netList.clear(); clearConnectionMap(m_activeItemMap, m_listWidget); clearConnectionMap(m_vpnItemMap, m_listWidget); m_connectResourse->getVpnAndVirtualConnections(netList); KyConnectItem *p_newItem = nullptr; if (!netList.isEmpty()) { for (int index = 0; index < netList.size(); index++) { KyConnectItem *p_netConnectionItem = netList.at(index); p_newItem = m_activeResourse->getActiveConnectionByUuid(p_netConnectionItem->m_connectUuid); if (p_newItem == nullptr) { if (m_vpnItemMap.contains(p_netConnectionItem->m_connectUuid)) { qDebug()<m_connectUuid; } QListWidgetItem *p_listWidgetItem = addNewItem(p_netConnectionItem, m_listWidget); m_vpnItemMap.insert(p_netConnectionItem->m_connectUuid, p_listWidgetItem); } else { if (m_activeItemMap.contains(p_netConnectionItem->m_connectUuid)) { qDebug()<m_connectUuid; } QListWidgetItem *p_listWidgetItem = addNewItem(p_newItem, m_listWidget); m_activeItemMap.insert(p_netConnectionItem->m_connectUuid, p_listWidgetItem); } delete p_netConnectionItem; p_netConnectionItem = nullptr; } } resetListWidgetWidth(); if (m_listWidget->count() == 0) { if (m_emptyLabel) { m_listWidget->hide(); m_emptyLabel->show(); } } else { if (m_emptyLabel) { m_emptyLabel->hide(); m_listWidget->show(); } } } void VpnPage::initVpnArea() { constructItemArea(); } void VpnPage::resetPageHeight() { int height = 0; int count = m_listWidget->count(); m_listFrame->setFixedHeight(VPN_PAGE_HEIGHT); if (m_listWidget->count() == 0) { if (m_emptyLabel) { m_listWidget->hide(); m_emptyLabel->show(); } else { m_listWidget->show(); } } else { if (m_emptyLabel){ m_emptyLabel->hide(); } m_listWidget->show(); } m_listFrame->show(); m_netDivider->show(); } bool VpnPage::removeConnectionItem(QMap &connectMap, QListWidget *vpnListWidget, QString path) { QMap::iterator iter; for (iter = connectMap.begin(); iter != connectMap.end(); ++iter) { QListWidgetItem *p_listWidgetItem = iter.value(); VpnListItem *p_vpnItem = (VpnListItem*)vpnListWidget->itemWidget(p_listWidgetItem); if (p_vpnItem->getConnectionPath() == path) { qDebug()<<"[VpnPage] Remove a connection from list"; vpnListWidget->removeItemWidget(p_listWidgetItem); delete p_vpnItem; p_vpnItem = nullptr; delete p_listWidgetItem; p_listWidgetItem = nullptr; iter = connectMap.erase(iter); resetListWidgetWidth(); return true; } } return false; } void VpnPage::onRemoveConnection(QString path) //删除时后端会自动断开激活,将其从未激活列表中删除 { //for dbus qDebug() << "[VpnPage] emit lanRemove because onRemoveConnection " << path; Q_EMIT vpnRemove(path); removeConnectionItem(m_vpnItemMap, m_listWidget, path); removeConnectionItem(m_activeItemMap, m_listWidget, path); resetPageHeight(); resetWindowPosition(); this->update(); } void VpnPage::onAddConnection(QString uuid) //新增一个有线连接,将其加入到激活列表 { if (!m_connectResourse->isVirtualConncection(uuid)) { return; } KyConnectItem *p_newItem = nullptr; p_newItem = m_connectResourse->getConnectionItemByUuid(uuid); if (nullptr == p_newItem) { return; } sendVpnAddSignal(p_newItem); qDebug()<<"[VpnPage] Add a new connection, name:"<m_connectName; QListWidgetItem *p_listWidgetItem = insertNewItem(p_newItem, m_listWidget); if (m_vpnItemMap.contains(p_newItem->m_connectUuid)) { qDebug()<m_connectUuid; } m_vpnItemMap.insert(p_newItem->m_connectUuid, p_listWidgetItem); delete p_newItem; p_newItem = nullptr; resetListWidgetWidth(); resetPageHeight(); resetWindowPosition(); this->update(); return; } void VpnPage::onShowControlCenter() { QProcess process; process.startDetached("ukui-control-center", QStringList() << "-m" << "vpn"); } void VpnPage::initUI() { m_titleLabel->setText(tr("VPN")); m_listWidget->setFrameShape(QFrame::Shape::NoFrame); m_listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_listWidget->setVerticalScrollMode(QAbstractItemView::ScrollMode::ScrollPerPixel); m_listWidget->verticalScrollBar()->setProperty("drawScrollBarGroove",false); //去除滚动条的外侧黑框 m_listWidget->verticalScrollBar()->setSingleStep(SCROLL_STEP); m_listWidget->verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu); m_settingsLabel->setText(tr("VPN Settings")); m_settingsLabel->setAttribute(Qt::WA_Hover, true); m_settingsLabel->setMouseTracking(true); m_settingsLabel->installEventFilter(this); m_emptyLabel = new QLabel(m_listFrame); m_emptyLabel->setText(tr("No VPN configuration available")); m_emptyLabel->setAlignment(Qt::AlignCenter); m_emptyLabel->setWordWrap(true); m_emptyLabel->setEnabled(false); m_emptyLabel->hide(); if (m_listLayout) { m_listLayout->addWidget(m_emptyLabel); } } QListWidgetItem *VpnPage::insertNewItem(KyConnectItem *itemData, QListWidget *listWidget) { int index = 0; for(index = 0; index < m_listWidget->count(); index++) { QListWidgetItem *p_listWidgetItem = m_listWidget->item(index); VpnListItem *p_vpnItem = (VpnListItem *)m_listWidget->itemWidget(p_listWidgetItem); QString name1 = p_vpnItem->getConnectionName(); QString name2 = itemData->m_connectName; if (QString::compare(name1, name2, Qt::CaseInsensitive) > 0 && index >= m_activeItemMap.count()) { break; } } QListWidgetItem *p_sortListWidgetItem = new QListWidgetItem(); p_sortListWidgetItem->setFlags(p_sortListWidgetItem->flags() & (~Qt::ItemIsSelectable)); //设置不可被选中 p_sortListWidgetItem->setSizeHint(QSize(listWidget->width(),ITEM_HEIGHT)); listWidget->insertItem(index, p_sortListWidgetItem); VpnListItem *p_sortLanItem = nullptr; p_sortLanItem = new VpnListItem(itemData); listWidget->setItemWidget(p_sortListWidgetItem, p_sortLanItem); return p_sortListWidgetItem; } QListWidgetItem *VpnPage::addNewItem(KyConnectItem *itemData, QListWidget *listWidget) { QListWidgetItem *p_listWidgetItem = new QListWidgetItem(); p_listWidgetItem->setFlags(p_listWidgetItem->flags() & (~Qt::ItemIsSelectable)); p_listWidgetItem->setSizeHint(QSize(listWidget->width() - 16, ITEM_HEIGHT)); if (itemData != nullptr && itemData->m_connectState == NetworkManager::ActiveConnection::State::Activated) { listWidget->insertItem(0, p_listWidgetItem); } else { listWidget->addItem(p_listWidgetItem); } VpnListItem *p_vpnItem = nullptr; if (itemData != nullptr) { p_vpnItem = new VpnListItem(itemData); qDebug() << "[VpnPage] addNewItem, connection: " << itemData->m_connectName; } else { p_vpnItem = new VpnListItem(); qDebug() << "[VpnPage] Add nullItem!"; } listWidget->setItemWidget(p_listWidgetItem, p_vpnItem); return p_listWidgetItem; } void VpnPage::updateActivatedConnectionArea(KyConnectItem *p_newItem) { if (m_activeItemMap.contains(p_newItem->m_connectUuid)) { return; } deleteConnectionMapItem(m_vpnItemMap, m_listWidget, p_newItem->m_connectUuid); qDebug()<<"[VpnPage]update active connection item"<m_connectName; deleteConnectionMapItem(m_activeItemMap, m_listWidget, p_newItem->m_connectUuid); QListWidgetItem *p_listWidgetItem = addNewItem(p_newItem, m_listWidget); m_activeItemMap.insert(p_newItem->m_connectUuid, p_listWidgetItem); resetListWidgetWidth(); if (m_activeItemMap.count() >= 4) { return; } resetPageHeight(); resetWindowPosition(); this->update(); } void VpnPage::updateConnectionArea(KyConnectItem *p_newItem) { if (m_vpnItemMap.contains(p_newItem->m_connectUuid)) { return; } deleteConnectionMapItem(m_activeItemMap, m_listWidget, p_newItem->m_connectUuid); qDebug()<<"[VpnPage] update connection item"<m_connectName; QListWidgetItem *p_listWidgetItem = insertNewItem(p_newItem, m_listWidget); m_vpnItemMap.insert(p_newItem->m_connectUuid, p_listWidgetItem); resetListWidgetWidth(); if (m_vpnItemMap.count() >= 4) { return; } resetPageHeight(); resetWindowPosition(); this->update(); } void VpnPage::updateConnectionState(QMap &connectMap, QListWidget *vpnListWidget, QString uuid, ConnectState state) { qDebug() << LOG_FLAG << "update connection state"; QListWidgetItem *p_listWidgetItem = connectMap.value(uuid); if (p_listWidgetItem) { VpnListItem *p_vpnItem = (VpnListItem *)vpnListWidget->itemWidget(p_listWidgetItem); if (p_vpnItem != nullptr) { p_vpnItem->updateConnectionState(state); } } } void VpnPage::onConnectionStateChange(QString uuid, NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason) { //VpnPage函数内持续监听连接状态的变化并记录供其他函数调用获取状态 if (!m_connectResourse->isVirtualConncection(uuid)) { qDebug() << "[VpnPage] connection state change signal but not vpn"; return; } sendVpnStateChangeSignal(uuid, (ConnectState)state); if (m_activeItemMap.keys().contains(uuid) && state == NetworkManager::ActiveConnection::State::Activated) { return; } qDebug()<<"[VpnPage] connection uuid"<< uuid << "state change slot:"<< state; KyConnectItem *p_newItem = nullptr; QString deviceName = ""; QString ssid = ""; if (state == NetworkManager::ActiveConnection::State::Activated) { p_newItem = m_activeResourse->getActiveConnectionByUuid(uuid); if (nullptr == p_newItem) { qWarning()<<"[VpnPage] get active connection failed, connection uuid" << uuid; return; } ssid = p_newItem->m_connectName; updateActivatedConnectionArea(p_newItem); updateConnectionState(m_activeItemMap, m_listWidget, uuid, (ConnectState)state); } else if (state == NetworkManager::ActiveConnection::State::Deactivated) { p_newItem = m_connectResourse->getConnectionItemByUuid(uuid); qDebug() << "[VpnPage] deactivated reason" << reason; if (nullptr == p_newItem) { qWarning()<<"[VpnPage] get active connection failed, connection uuid" << uuid; return; } ssid = p_newItem->m_connectName; updateConnectionArea(p_newItem); updateConnectionState(m_vpnItemMap, m_listWidget, uuid, (ConnectState)state); } else if (state == NetworkManager::ActiveConnection::State::Activating) { updateConnectionState(m_vpnItemMap, m_listWidget, uuid, (ConnectState)state); } else if (state == NetworkManager::ActiveConnection::State::Deactivating) { updateConnectionState(m_activeItemMap, m_listWidget, uuid, (ConnectState)state); } Q_EMIT vpnActiveConnectionStateChanged(uuid, state); if (p_newItem) { delete p_newItem; p_newItem = nullptr; } return; } void VpnPage::getVirtualList(QVector &vector) { QList netConnectList; vector.clear(); m_connectResourse->getVpnAndVirtualConnections(netConnectList); //未激活列表的显示 if (!netConnectList.isEmpty()) { for (int i = 0; i < netConnectList.size(); i++) { KyConnectItem *p_newItem = nullptr; KyConnectItem *p_netConnectionItem = netConnectList.at(i); p_newItem = m_activeResourse->getActiveConnectionByUuid(p_netConnectionItem->m_connectUuid); NetworkManager::ActiveConnection::State state = p_netConnectionItem->m_connectState; if (p_newItem != nullptr) { state = NetworkManager::ActiveConnection::Activated; } vector.append(QStringList() << netConnectList.at(i)->m_connectName << netConnectList.at(i)->m_connectUuid << netConnectList.at(i)->m_connectPath << QString::number(state)); } } return; } void VpnPage::sendVpnUpdateSignal(KyConnectItem *p_connectItem) { QStringList info; info << p_connectItem->m_connectName << p_connectItem->m_connectUuid << p_connectItem->m_connectPath; Q_EMIT vpnUpdate(info); return; } void VpnPage::sendVpnAddSignal(KyConnectItem *p_connectItem) { QStringList info; KyConnectItem *p_newItem = nullptr; p_newItem = m_activeResourse->getActiveConnectionByUuid(p_connectItem->m_connectUuid); NetworkManager::ActiveConnection::State state = p_connectItem->m_connectState; if (p_newItem != nullptr) { state = NetworkManager::ActiveConnection::Activated; } info << p_connectItem->m_connectName << p_connectItem->m_connectUuid << p_connectItem->m_connectPath << QString::number(state); qDebug() << "[VpnPage] emit vpnAdd because addConnection "; Q_EMIT vpnAdd(info); return; } void VpnPage::sendVpnStateChangeSignal(QString uuid, ConnectState state) { if (state == Activating || state == Deactivating) { if (m_activeResourse->connectionIsVirtual(uuid)) { return; } } Q_EMIT this->vpnConnectChanged(state); return; } void VpnPage::updateConnectionProperty(KyConnectItem *p_connectItem) { QString newUuid = p_connectItem->m_connectUuid; if (m_vpnItemMap.contains(newUuid)) { QListWidgetItem *p_listWidgetItem = m_vpnItemMap.value(newUuid); VpnListItem *p_vpnItem = (VpnListItem*)m_listWidget->itemWidget(p_listWidgetItem); if (p_connectItem->m_connectName != p_vpnItem->getConnectionName()){ //只要名字改变就要删除,重新插入,主要是为了排序 deleteConnectionMapItem(m_vpnItemMap, m_listWidget, newUuid); QListWidgetItem *p_sortListWidgetItem = insertNewItem(p_connectItem, m_listWidget); if (m_vpnItemMap.contains(newUuid)) { qDebug()<m_connectPath != p_vpnItem->getConnectionPath()) { p_vpnItem->updateConnectionPath(p_connectItem->m_connectPath); } } else if (!m_activeItemMap.contains(newUuid)){ if (p_connectItem->m_ifaceName.isEmpty()) { QListWidgetItem *p_listWidgetItem = insertNewItem(p_connectItem, m_listWidget); if (m_vpnItemMap.contains(newUuid)) { qDebug()<m_connectUuid; if (m_activeItemMap.contains(newUuid)) { QListWidgetItem *p_listWidgetItem = m_activeItemMap.value(newUuid); VpnListItem *p_vpnItem = (VpnListItem *)m_listWidget->itemWidget(p_listWidgetItem); if (p_vpnItem->getConnectionName() != p_connectItem->m_connectName) { p_vpnItem->updateConnectionName(p_connectItem->m_connectName); } if (p_vpnItem->getConnectionName() != p_connectItem->m_connectPath) { p_vpnItem->updateConnectionPath(p_connectItem->m_connectPath); } } return; } void VpnPage::onUpdateConnection(QString uuid) { if (!m_connectResourse->isVirtualConncection(uuid)) { return; } qDebug() << "[VpnPage]:Connection property Changed." << Q_FUNC_INFO << __LINE__; KyConnectItem *p_newItem = nullptr; if (m_connectResourse->isActivatedConnection(uuid)) { p_newItem = m_activeResourse->getActiveConnectionByUuid(uuid); if (nullptr == p_newItem) { qWarning()<<"[VpnPage] get item failed, when update activate connection." <<"connection uuid" << uuid; return; } updateActiveConnectionProperty(p_newItem); } else { p_newItem = m_connectResourse->getConnectionItemByUuid(uuid); if (nullptr == p_newItem) { qWarning()<<"[VpnPage] get item failed, when update connection." <<"connection uuid"<type() == QEvent::MouseButtonRelease) { onShowControlCenter(); } } if (watched == this) { //失焦退出 if (event->type() == QEvent::ActivationChange) { if (QApplication::activeWindow() != this) { hide(); return true; } } } return QWidget::eventFilter(watched, event); } void VpnPage::initPanelGSettings() { const QByteArray id(PANEL_SETTINGS); if (QGSettings::isSchemaInstalled(id)) { if (m_panelGSettings == nullptr) { m_panelGSettings = new QGSettings(id, QByteArray(), this); } if (m_panelGSettings->keys().contains(PANEL_POSITION_KEY)) { m_panelPosition = m_panelGSettings->get(PANEL_POSITION_KEY).toInt(); } if (m_panelGSettings->keys().contains(PANEL_SIZE_KEY)) { m_panelSize = m_panelGSettings->get(PANEL_SIZE_KEY).toInt(); } connect(m_panelGSettings, &QGSettings::changed, this, [&] (const QString &key) { if (key == PANEL_POSITION_KEY) { m_panelPosition = m_panelGSettings->get(PANEL_POSITION_KEY).toInt(); } if (key == PANEL_SIZE_KEY) { m_panelSize = m_panelGSettings->get(PANEL_SIZE_KEY).toInt(); } if (this->isVisible()) { resetWindowPosition(); } }); } } void VpnPage::deleteVpn(const QString &connUuid) { qDebug() << "[VpnPage] deleteVpn" << connUuid; if (connUuid == nullptr) { return; } m_vpnConnectOperation->deleteVpnConnect(connUuid); } void VpnPage::activateVpn(const QString& connUuid) { if (m_vpnItemMap.contains(connUuid)) { qDebug() << "[VpnPage] activateVpn" << connUuid; m_vpnConnectOperation->activateVpnConnection(connUuid); } } void VpnPage::deactivateVpn(const QString& connUuid) { qDebug() << "[VpnPage] deactivateVpn" << connUuid; QString name(""); m_vpnConnectOperation->deactivateVpnConnection(name, connUuid); } void VpnPage::showDetailPage(QString uuid) { QListWidgetItem * vpnlistItem = m_vpnItemMap.value(uuid); VpnListItem *vpnItem = (VpnListItem *)m_listWidget->itemWidget(vpnlistItem); vpnItem->onInfoButtonClicked(); } void VpnPage::showUI() { //2209中窗管在hide界面时会刷新属性,需要重新设置无图标属性 const KWindowInfo info(this->winId(), NET::WMState); if (!info.hasState(NET::SkipTaskbar) || !info.hasState(NET::SkipPager)) { KX11Extras::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager);//mqtest qt6移除该接口 } kdk::WindowManager::setSkipTaskBar(this->windowHandle(), true); resetPageHeight(); showNormal(); raise(); activateWindow(); resetWindowPosition(); return; } void VpnPage::resetWindowPosition() { QRect availableGeo = QGuiApplication::screenAt(QCursor::pos())->geometry(); int x, y; switch(m_panelPosition){ case PANEL_TOP: //任务栏位于上方 x = availableGeo.x() + availableGeo.width() - this->width() - MARGIN; y = availableGeo.y() + m_panelSize + MARGIN; break; //任务栏位于左边 case PANEL_LEFT: x = availableGeo.x() + m_panelSize + MARGIN; y = availableGeo.y() + availableGeo.height() - this->height() - MARGIN; break; //任务栏位于右边 case PANEL_RIGHT: x = availableGeo.x() + availableGeo.width() - m_panelSize - this->width() - MARGIN; y = availableGeo.y() + availableGeo.height() - this->height() - MARGIN; break; //任务栏位于下方 default: x = availableGeo.x() + availableGeo.width() - this->width() - MARGIN; y = availableGeo.y() + availableGeo.height() - m_panelSize - this->height() - MARGIN; break; } kdk::WindowManager::setGeometry(this->windowHandle(), QRect(x, y, this->width(), this->height())); qDebug() << " Position of ukui-panel is " << m_panelPosition << "; Position of mainwindow is " << this->geometry() << "." << Q_FUNC_INFO << __LINE__; } void VpnPage::resetListWidgetWidth() { if (m_listWidget->count() <= MAX_ITEMS) { m_listFrame->setFixedWidth(MIN_WIDTH); } else { m_listFrame->setFixedWidth(MAX_WIDTH); } } kylin-nm/src-vpn/frontend/single-pages/singlepage.cpp0000664000175000017500000001733115167651420021661 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "singlepage.h" #include #include #include #include #include #include #include #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" SinglePage::SinglePage(QWidget *parent) : QWidget(parent) { setThemePalette(); initUI(); initWindowProperties(); initTransparency(); initWindowTheme(); m_uwin = new UkuiWindowHelper(this); m_uwin->setWindowRole(UkuiWindowHelper::WindowRole::SystemWindow); m_uwin->setSlideEffect(UkuiWindowHelper::Position::Bottom); } SinglePage::~SinglePage() { } void SinglePage::initUI() { m_mainLayout = new QVBoxLayout(this); m_mainLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); m_mainLayout->setSpacing(MAIN_LAYOUT_SPACING); this->setLayout(m_mainLayout); m_titleFrame = new QFrame(this); m_titleFrame->setFixedHeight(TITLE_FRAME_HEIGHT); m_titleLayout = new QHBoxLayout(m_titleFrame); m_titleLayout->setContentsMargins(TITLE_LAYOUT_MARGINS); m_titleFrame->setLayout(m_titleLayout); m_titleLabel = new QLabel(m_titleFrame); m_titleLayout->addWidget(m_titleLabel); m_titleLayout->addStretch(); m_netDivider = new Divider(true, this); m_listFrame = new QFrame(this); m_listLayout = new QVBoxLayout(m_listFrame); m_listLayout->setContentsMargins(NET_LAYOUT_MARGINS); m_listFrame->setLayout(m_listLayout); m_listWidget = new QListWidget(m_listFrame); m_listLayout->addWidget(m_listWidget); m_listWidget->setProperty("needTranslucent", true); m_setDivider = new Divider(true, this); m_settingsFrame = new QFrame(this); m_settingsFrame->setFixedHeight(SETTING_FRAME_HEIGHT); m_settingsLayout = new QHBoxLayout(m_settingsFrame); m_settingsLayout->setContentsMargins(SETTINGS_LAYOUT_MARGINS); m_settingsLabel = new KyLable(m_settingsFrame); m_settingsLabel->setText(tr("Settings")); m_settingsLabel->setScaledContents(true); m_settingsLayout->addWidget(m_settingsLabel); m_settingsLayout->addStretch(); m_settingsFrame->setLayout(m_settingsLayout); m_mainLayout->addWidget(m_titleFrame); m_mainLayout->addWidget(m_netDivider); m_mainLayout->addWidget(m_listFrame); m_mainLayout->addWidget(m_setDivider); m_mainLayout->addWidget(m_settingsFrame); } void SinglePage::initWindowProperties() { QPalette pal = m_listFrame->palette(); pal.setBrush(QPalette::Base, QColor(0,0,0,0)); //背景透明 m_listFrame->setPalette(pal); this->setFixedWidth(MAX_WIDTH); this->setAttribute(Qt::WA_TranslucentBackground); this->setProperty("useStyleWindowManager", false); //禁用拖动 //绘制毛玻璃特效 QString platform = QGuiApplication::platformName(); if(!platform.startsWith(QLatin1String("wayland"),Qt::CaseInsensitive)) { QPainterPath path; auto rect = this->rect(); path.addRect(rect); // m_uwin->setBlurEffect(QRegion(path.toFillPolygon().toPolygon()),0 , true);//qt6kf6环境中此处会崩溃先注释 } } /** * @brief SinglePage::initWindowTheme 初始化窗口主题并创建信号槽 */ void SinglePage::initWindowTheme() { const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { m_styleGsettings = new QGSettings(style_id, QByteArray(), this); connect(m_styleGsettings, &QGSettings::changed, this, &SinglePage::onThemeChanged); } else { qWarning() << "Gsettings interface \"org.ukui.style\" is not exist!" << Q_FUNC_INFO << __LINE__; } } void SinglePage::showDesktopNotify(const QString &message, QString soundName) { QDBusInterface iface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus()); QStringList actions; //跳转动作 actions.append("default"); actions.append("kylin-vpn"); //默认动作:点击消息体时打开麒麟录音 QMap hints; if (!soundName.isEmpty()) { hints.insert("sound-name",soundName); //添加声音 } QList args; args<<(tr("Kylin VPN")) <<((unsigned int) 0) <palette().window().color(); QPainterPath rectPath; col.setAlphaF(m_transparency); rectPath.addRect(this->rect()); painter.setBrush(col); painter.drawPath(rectPath); m_uwin->setBlurEffect(QRegion(rectPath.toFillPolygon().toPolygon()),0 , true); } void SinglePage::initTransparency() { if(QGSettings::isSchemaInstalled(QByteArray(TRANSPARENCY_GSETTINGS))) { m_transGsettings = new QGSettings(QByteArray(TRANSPARENCY_GSETTINGS)); if(m_transGsettings->keys().contains(TRANSPARENCY)) { m_transparency = m_transGsettings->get(TRANSPARENCY).toDouble() + 0.15; m_transparency = (m_transparency > 1) ? 1 : m_transparency; connect(m_transGsettings, &QGSettings::changed, this, &SinglePage::onTransChanged); } } } void SinglePage::onTransChanged() { m_transparency = m_transGsettings->get("transparency").toDouble() + 0.15; m_transparency = (m_transparency > 1) ? 1 : m_transparency; paintWithTrans(); } void SinglePage::onThemeChanged(const QString &key) { if (key == COLOR_THEME) { setThemePalette(); paintWithTrans(); Q_EMIT qApp->paletteChanged(qApp->palette()); } else if ("themeColor" == key) { setThemePalette(); } } void SinglePage::setThemePalette() { QPalette pal = qApp->palette(); QGSettings * styleGsettings = nullptr; const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { styleGsettings = new QGSettings(style_id, QByteArray(), this); QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = themePalette(true, this); } } pal.setColor(QPalette::Window, pal.base().color()); this->setPalette(pal); } void SinglePage::paintWithTrans() { QPalette pal = this->palette(); QColor color = this->palette().base().color(); color.setAlphaF(m_transparency); pal.setColor(QPalette::Window, color); this->setPalette(pal); } void SinglePage::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Escape) { this->hide(); } return QWidget::keyPressEvent(event); } kylin-nm/src-vpn/frontend/single-pages/single-pages.pri0000664000175000017500000000022015167646234022125 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/vpnpage.h \ $$PWD/singlepage.h SOURCES += \ $$PWD/vpnpage.cpp \ $$PWD/singlepage.cpp kylin-nm/src-vpn/frontend/list-items/0000775000175000017500000000000015167651420016546 5ustar fengfengkylin-nm/src-vpn/frontend/list-items/list-items.pri0000664000175000017500000000022415167646234021361 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/listitem.h \ $$PWD/vpnlistitem.h SOURCES += \ $$PWD/listitem.cpp \ $$PWD/vpnlistitem.cpp kylin-nm/src-vpn/frontend/list-items/vpnlistitem.h0000664000175000017500000000464515167646234021315 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef VPNLISTITEM_H #define VPNLISTITEM_H #include "listitem.h" #include "kylinactiveconnectresource.h" #include #include #include #include #include "vpndetails/vpndetail.h" #include "kylinconnectresource.h" //#include "kylinwiredconnectoperation.h" #include "kyvpnconnectoperation.h" #define KYLIN_APP_MANAGER_NAME "com.kylin.AppManager" #define KYLIN_APP_MANAGER_PATH "/com/kylin/AppManager" #define KYLIN_APP_MANAGER_INTERFACE "com.kylin.AppManager" class VpnListItem : public ListItem { Q_OBJECT public: VpnListItem(const KyConnectItem *vpnConnectItem, QWidget *parent = nullptr); VpnListItem(QWidget *parent = nullptr); ~VpnListItem(); public: void updateConnectionState(ConnectState state); QString getConnectionName(); void updateConnectionName(QString connectionName); QString getConnectionPath(); void updateConnectionPath(QString connectionPath); void activeConnection(); protected: void setIcon(bool isOn); void onRightButtonClicked(); bool launchApp(QString desktopFile); void runExternalApp(); private: void connectItemCopy(const KyConnectItem *vpnConnectItem); public Q_SLOTS: void onInfoButtonClicked(); private Q_SLOTS: void onNetButtonClicked(); void onMenuTriggered(QAction *action); private: KyConnectItem m_vpnConnectItem; KyVpnConnectOperation *m_connectOperation = nullptr; KyNetworkDeviceResourse *m_deviceResource = nullptr; QString m_deviceName = ""; VpnDetail *m_vpnDetail = nullptr; }; #endif // VPNLISTITEM_H kylin-nm/src-vpn/frontend/list-items/listitem.h0000664000175000017500000000506015167646234020561 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef LISTITEM_H #define LISTITEM_H #include #include #include #include #include #include #include #include "radioitembutton.h" #include "infobutton.h" typedef enum{ UnknownState = 0, /**< The active connection is in an unknown state */ Activating, /**< The connection is activating */ Activated, /**< The connection is activated */ Deactivating, /**< The connection is being torn down and cleaned up */ Deactivated /**< The connection is no longer active */ }ConnectState; class ListItem : public QFrame { Q_OBJECT public: ListItem(QWidget *parent = nullptr); ~ListItem(); void setName(const QString &name); void setActive(const bool &isActive); void setConnectState(ConnectState state); static void showDesktopNotify(const QString &message, QString soundName); protected: void mousePressEvent(QMouseEvent *event); void enterEvent(QEvent *event); void leaveEvent(QEvent *event); void paintEvent(QPaintEvent *event); virtual void onRightButtonClicked() = 0; protected: QFrame * m_itemFrame = nullptr; QLabel * m_nameLabel = nullptr; RadioItemButton * m_netButton = nullptr; InfoButton * m_infoButton = nullptr; bool m_isActive = false; ConnectState m_connectState; QMenu *m_menu = nullptr; public: QVBoxLayout * m_mainLayout = nullptr; QHBoxLayout * m_hItemLayout = nullptr; private: void initUI(); void initConnection(); void onPaletteChanged(); public Q_SLOTS: virtual void onNetButtonClicked() = 0; virtual void onMenuTriggered(QAction *action)=0; Q_SIGNALS: void detailShow(bool isShow); }; #endif // LISTITEM_H kylin-nm/src-vpn/frontend/list-items/listitem.cpp0000664000175000017500000001150215167651420021103 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "listitem.h" #include #include "themepalette.h" #define MAIN_LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_SPACING 0 #define ITEM_FRAME_MARGINS 12,6,16,6 #define ITEM_FRAME_SPACING 8 #define FRAME_WIDTH 404 #define INFO_ICON_WIDTH 16 #define INFO_ICON_HEIGHT 16 #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" ListItem::ListItem(QWidget *parent) : QFrame(parent) { m_connectState = UnknownState; initUI(); initConnection(); connect(qApp, &QApplication::paletteChanged, this, &ListItem::onPaletteChanged); // m_itemFrame->installEventFilter(this); onPaletteChanged(); } ListItem::~ListItem() { if (nullptr != m_netButton) { delete m_netButton; m_netButton = nullptr; } if (nullptr != m_infoButton) { delete m_infoButton; m_infoButton = nullptr; } } void ListItem::setName(const QString &name) { m_nameLabel->setText(name); } //仅无线调用,有线自己获取 void ListItem::setActive(const bool &isActive) { m_netButton->setActive(isActive); m_isActive = isActive; } void ListItem::setConnectState(ConnectState state) { m_connectState = state; } void ListItem::mousePressEvent(QMouseEvent *event) { qDebug()<<"[ListItem]"<<"mousePressEvent"; if (event->button() == Qt::LeftButton) { onNetButtonClicked(); } else if (event->button() == Qt::RightButton) { onRightButtonClicked(); } return QFrame::mousePressEvent(event); } void ListItem::enterEvent(QEvent *event) { } void ListItem::leaveEvent(QEvent *event) { } void ListItem::paintEvent(QPaintEvent *event) { } void ListItem::initUI() { m_menu = new QMenu(this);//右键菜单 // m_menu->setStyleSheet("QMenu::item{border:3px; border-radius:3px}"); // m_menu->setStyleSheet("QMenu{border-radius:6px; margin:6px 6px 6px 6px}"); connect(m_menu, &QMenu::triggered, this, &ListItem::onMenuTriggered); m_mainLayout = new QVBoxLayout(this); m_mainLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); m_mainLayout->setSpacing(MAIN_LAYOUT_SPACING); this->setLayout(m_mainLayout); m_itemFrame = new QFrame(this); m_itemFrame->setFixedWidth(FRAME_WIDTH); m_hItemLayout = new QHBoxLayout(m_itemFrame); m_hItemLayout->setContentsMargins(ITEM_FRAME_MARGINS); m_hItemLayout->setSpacing(ITEM_FRAME_SPACING); m_hItemLayout->setAlignment(Qt::AlignHCenter); m_netButton = new RadioItemButton(m_itemFrame); m_nameLabel = new QLabel(m_itemFrame); m_nameLabel->setMinimumWidth(262); m_infoButton = new InfoButton(m_itemFrame); m_infoButton->setIconSize(QSize(INFO_ICON_WIDTH,INFO_ICON_HEIGHT)); m_hItemLayout->addWidget(m_netButton); m_hItemLayout->addWidget(m_nameLabel); m_hItemLayout->addStretch(); m_hItemLayout->addWidget(m_infoButton); m_infoButton->hide(); m_mainLayout->addWidget(m_itemFrame); // this->setAutoFillBackground(true); // this->setBackgroundRole(QPalette::Base); // QPalette pal = qApp->palette(); // pal.setColor(QPalette::Window, qApp->palette().base().color()); // this->setPalette(pal); } void ListItem::initConnection() { connect(this->m_netButton, &RadioItemButton::clicked, this, &ListItem::onNetButtonClicked); // connect(this->m_infoButton, &InfoButton::clicked, this, &ListItem::onInfoButtonClicked); } void ListItem::onPaletteChanged() { QPalette pal = qApp->palette(); QGSettings * styleGsettings = nullptr; const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { styleGsettings = new QGSettings(style_id, QByteArray(), this); QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); if(currentTheme == "ukui-default"){ pal = themePalette(true, this); } } this->setPalette(pal); if (m_menu != nullptr) { pal.setColor(QPalette::Base, pal.color(QPalette::Base)); pal.setColor(QPalette::Text, pal.color(QPalette::Text)); m_menu->setPalette(pal); } } kylin-nm/src-vpn/frontend/list-items/vpnlistitem.cpp0000664000175000017500000002064015167651420021632 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "vpnlistitem.h" #include "kylinconnectitem.h" #include #define LOG_FLAG "[VpnListItem]" VpnListItem::VpnListItem(const KyConnectItem *vpnConnectItem, QWidget *parent):ListItem(parent) { m_connectOperation = new KyVpnConnectOperation(this); m_deviceResource = new KyNetworkDeviceResourse(this); connectItemCopy(vpnConnectItem); char *envStr = getenv("LANGUAGE"); if (envStr && (strcmp(envStr, "ug_CN") == 0 || strcmp(envStr, "kk_KZ") == 0 || strcmp(envStr, "ky_KG")) == 0) { this->setFixedWidth(390); } m_nameLabel->setText(m_vpnConnectItem.m_connectName); m_netButton->setButtonIcon(QIcon::fromTheme("network-vpn-symbolic")); qDebug() << "VpnListItem init:" << m_vpnConnectItem.m_connectName << m_vpnConnectItem.m_connectState << m_vpnConnectItem.m_ifaceName; if (Deactivated == m_vpnConnectItem.m_connectState || Activated == m_vpnConnectItem.m_connectState) { m_netButton->stopLoading(); if (m_vpnConnectItem.m_connectState == Activated) { setIcon(true); } else { setIcon(false); } } else { m_netButton->startLoading(); } m_itemFrame->installEventFilter(this); connect(this->m_infoButton, &InfoButton::clicked, this, &VpnListItem::onInfoButtonClicked); connect(m_menu, &QMenu::triggered, this, &VpnListItem::onMenuTriggered); } VpnListItem::VpnListItem(QWidget *parent) : ListItem(parent) { m_isActive = false; m_netButton->setButtonIcon(QIcon::fromTheme("network-vpn-symbolic")); setIcon(false); const QString str=tr("Not connected"); m_nameLabel->setText(str); this->m_infoButton->hide(); } VpnListItem::~VpnListItem() { qDebug()<<"[LanPage] lan list item is deleted." << m_vpnConnectItem.m_connectName; } void VpnListItem::setIcon(bool isOn) { if (isOn) { m_netButton->setActive(true); //设置图标显示不同颜色 } else { m_netButton->setActive(false); } } void VpnListItem::connectItemCopy(const KyConnectItem *vpnConnectItem) { if (vpnConnectItem) { m_vpnConnectItem.m_connectName = vpnConnectItem->m_connectName; m_vpnConnectItem.m_connectPath = vpnConnectItem->m_connectPath; m_vpnConnectItem.m_connectState = vpnConnectItem->m_connectState; m_vpnConnectItem.m_connectUuid = vpnConnectItem->m_connectUuid; m_vpnConnectItem.m_ifaceName = vpnConnectItem->m_ifaceName; m_vpnConnectItem.m_itemType = vpnConnectItem->m_itemType; } else { qDebug() << LOG_FLAG <<"the connect item is nullptr"; m_vpnConnectItem.m_connectName = ""; m_vpnConnectItem.m_connectPath = ""; m_vpnConnectItem.m_connectState = NetworkManager::ActiveConnection::State::Unknown; m_vpnConnectItem.m_connectUuid = ""; m_vpnConnectItem.m_ifaceName = ""; m_vpnConnectItem.m_itemType = NetworkManager::ConnectionSettings::ConnectionType::Unknown; } } void VpnListItem::activeConnection() { if (m_vpnConnectItem.m_connectUuid.isEmpty()) { qDebug() << LOG_FLAG << "connect is empty, so can not connect or disconnect."; return; } if (Deactivated == m_vpnConnectItem.m_connectState) { //断开的连接,点击激活连接 m_connectOperation->activateVpnConnection(m_vpnConnectItem.m_connectUuid); qDebug() << LOG_FLAG << "it will activate connection" << m_vpnConnectItem.m_connectName; m_netButton->startLoading(); } else { qDebug() << LOG_FLAG <<"the connection" << m_vpnConnectItem.m_connectName << "is not deactived, so it can not be operation."; } } void VpnListItem::onNetButtonClicked() { if (m_vpnConnectItem.m_connectUuid.isEmpty()) { qDebug() << LOG_FLAG << "connect is empty, so can not connect or disconnect."; return; } if (Deactivated == m_vpnConnectItem.m_connectState) { //断开的连接,点击激活连接 m_connectOperation->activateVpnConnection(m_vpnConnectItem.m_connectUuid); qDebug() << LOG_FLAG << "it will activate connection" << m_vpnConnectItem.m_connectName; m_netButton->startLoading(); } else { qDebug() << LOG_FLAG <<"the connection" << m_vpnConnectItem.m_connectName << "is not deactived, so it can not be operation."; } } void VpnListItem::onRightButtonClicked() { //右键点击事件 qDebug()<< LOG_FLAG <<"onRightButtonClicked"; if (!m_menu) { return; } m_menu->clear(); if (Activated == m_vpnConnectItem.m_connectState || Activating == m_vpnConnectItem.m_connectState) { m_menu->addAction(new QAction(tr("Disconnect"), this)); } else if (Deactivated == m_vpnConnectItem.m_connectState) { m_menu->addAction(new QAction(tr("Connect"), this)); } else { return; } m_menu->move(cursor().pos()); m_menu->show(); } void VpnListItem::onMenuTriggered(QAction *action) { if (action->text() == tr("Connect")) { this->onNetButtonClicked(); } else if (action->text() == tr("Disconnect")) { m_connectOperation->deactivateVpnConnection(m_vpnConnectItem.m_connectName, m_vpnConnectItem.m_connectUuid); qDebug() << LOG_FLAG << "it will disconnect connection" << m_vpnConnectItem.m_connectName; m_netButton->startLoading(); } } bool VpnListItem::launchApp(QString desktopFile) { QDBusInterface appManagerDbusInterface(KYLIN_APP_MANAGER_NAME, KYLIN_APP_MANAGER_PATH, KYLIN_APP_MANAGER_INTERFACE, QDBusConnection::sessionBus()); if (!appManagerDbusInterface.isValid()) { qWarning()<<"appManagerDbusInterface init error"; return false; } else { QDBusReply reply = appManagerDbusInterface.call("LaunchApp", desktopFile); return reply; } } void VpnListItem::runExternalApp() { if (!launchApp("nm-connection-editor.desktop")){ QString cmd = "nm-connection-editor"; QProcess process(this); process.startDetached(cmd); } } void VpnListItem::onInfoButtonClicked() { #ifdef VPNDETAIL if (m_vpnConnectItem.m_itemType != NetworkManager::ConnectionSettings::ConnectionType::Vpn) { #else if (true) { #endif runExternalApp(); return; } #ifdef VPNDETAIL if(m_vpnDetail != nullptr){ m_vpnDetail->activateWindow(); return; } m_vpnDetail = new VpnDetail(m_vpnConnectItem.m_connectUuid, getConnectionName()); connect(m_vpnDetail, &VpnDetail::destroyed, [&](){ if (m_vpnDetail != nullptr) { m_vpnDetail = nullptr; } }); m_vpnDetail->show(); m_vpnDetail->centerToScreen(); #endif } void VpnListItem::updateConnectionState(ConnectState state) { m_vpnConnectItem.m_connectState = (NetworkManager::ActiveConnection::State)state; if (Deactivated == state || Activated == state) { m_netButton->stopLoading(); if (state == Activated) { setIcon(true); } else { setIcon(false); } } else { m_netButton->startLoading(); } } QString VpnListItem::getConnectionName() { return m_vpnConnectItem.m_connectName; } void VpnListItem::updateConnectionName(QString connectionName) { m_vpnConnectItem.m_connectName = connectionName; m_nameLabel->setText(m_vpnConnectItem.m_connectName); } QString VpnListItem::getConnectionPath() { return m_vpnConnectItem.m_connectPath; } void VpnListItem::updateConnectionPath(QString connectionPath) { m_vpnConnectItem.m_connectPath = connectionPath; } kylin-nm/src-vpn/backend/0000775000175000017500000000000015167651420014224 5ustar fengfengkylin-nm/src-vpn/backend/vpndbusadaptor.cpp0000664000175000017500000000471615167651420017774 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "vpndbusadaptor.h" #include #include #include #include #include #include #include /* * Implementation of adaptor class VpnDbusAdaptor */ VpnDbusAdaptor::VpnDbusAdaptor(vpnObject *parent) : QDBusAbstractAdaptor(parent) { qDBusRegisterMetaType >(); qDBusRegisterMetaType >(); qDBusRegisterMetaType >(); setAutoRelaySignals(true); } //虚拟连接列表 QVector VpnDbusAdaptor::getVirtualList() { QVector vector; parent()->getVirtualList(vector); return vector; } //删除 void VpnDbusAdaptor::deleteVpn(QString uuid) { qDebug() << "delete vpn" << uuid; parent()->deleteVpn(uuid); } //连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid void VpnDbusAdaptor::activateVpn(const QString& connUuid) { qDebug() << "activate vpn" << connUuid; parent()->activateVpn(connUuid); } //断开连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid void VpnDbusAdaptor::deactivateVpn(const QString& connUuid) { qDebug() << "deactivate vpn" << connUuid; parent()->deactivateVpn(connUuid); } void VpnDbusAdaptor::showKylinVpn() { parent()->onShowMainWindow(); } void VpnDbusAdaptor::showVpnAddWidget() { qDebug() << "showVpnAddWidget"; parent()->showVpnAddWidget(); } void VpnDbusAdaptor::showDetailPage(const QString& connUuid) { qDebug() << "showDetailPage vpn" << connUuid; parent()->showDetailPage(connUuid); } kylin-nm/src-vpn/backend/backend.pri0000664000175000017500000000026415167646234016340 0ustar fengfengINCLUDEPATH += $$PWD include(../../src/backend/dbus-interface/dbus-interface.pri) HEADERS += \ $$PWD/vpndbusadaptor.h SOURCES += \ $$PWD/vpndbusadaptor.cpp DISTFILES += kylin-nm/src-vpn/backend/vpndbusadaptor.h0000664000175000017500000000424615167651420017437 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef VPNDBUSADAPTOR_H #define VPNDBUSADAPTOR_H #include #include #include #include #include #include "singlepage.h" #include "kylinnetworkdeviceresource.h" #include "kyvpnconnectoperation.h" QT_BEGIN_NAMESPACE class QByteArray; template class QMap; class QString; class QVariant; QT_END_NAMESPACE #include "vpnobject.h" class VpnDbusAdaptor: public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "com.kylin.kylinvpn") public: VpnDbusAdaptor(vpnObject *parent); inline vpnObject *parent() const { return static_cast(QObject::parent()); } public Q_SLOTS: QVector getVirtualList(); Q_NOREPLY void deleteVpn(QString uuid); Q_NOREPLY void activateVpn(const QString& connUuid); Q_NOREPLY void deactivateVpn(const QString& connUuid); Q_NOREPLY void showVpnAddWidget(); Q_NOREPLY void showDetailPage(const QString& connUuid); void showKylinVpn(); Q_SIGNALS: void vpnAdd(QStringList info); void vpnRemove(QString dbusPath); void vpnUpdate(QStringList info); void vpnActiveConnectionStateChanged(QString uuid, int status); void activateFailed(QString errorMessage); void deactivateFailed(QString errorMessage); }; #endif kylin-nm/qml-network/0000775000175000017500000000000015167651420013525 5ustar fengfengkylin-nm/qml-network/translations/0000775000175000017500000000000015167654227016256 5ustar fengfengkylin-nm/qml-network/translations/ukui-shortcut-network_ug.ts0000664000175000017500000001223115167651420023625 0ustar fengfeng DeviceComboBox (Connected) ( ئۇلاندى ) (Not Connected) ( ئۇلانمىغان ) Current Network Card نۆۋەتتىكى تور كارتىسى LanComponent network settings 网络配置 connected ئۇلانغان Not connected ئۇلانمىدى disconnect ئۈزۈلۈپ ئېچىش connect ئۇلىنىش disconnect network 断开网络 connect network 连接网络 network property 网络属性 delete this network 删除此网络 Disconnect network تورنى ئۈزۈپ ئېچىش Connect network تور ئۇلاش Network property تور خۇسۇسىيىتى Delete this network بۇ تورنى ئۆچۈرۈش NetScrollViewArea Wired network سىملىق تور No wired network card was detected سىملىق تور كارتىسىنى تەكشۈرمىگەن Wireless network سىمسىز تور More network Settings تېخىمۇ كۆپ تور تەسىس قىلىش WlanComponent Network settings 网络配置 connected 已连接 Not connected 未连接 disconnect ئۈزۈلۈپ ئېچىش connect ئۇلىنىش AutoConnect ئاپتوماتىك ئۇلاش Disconnect network تورنى ئۈزۈپ ئېچىش Connect network تور ئۇلاش Network property تور خۇسۇسىيىتى Forget the network بۇ تورنى ئۇنتۇپ قالماق Add Others... باشقا تورغا قوشۇلۇش... Connected,network is very good ئۇلاندى، تور بەك ياخشى Connected,network is good ئۇلاندى ، تور ياخشى Connected,network is average ئاللىقاچان ئۇلاندى ، تور ئادەتتىكىچە Connected,network weak ئۇلاندى، تور ئاجىز Connected,network is weak ئاللىقاچان ئۇلاندى ، تور بەك ئاجىز kylin-nm/qml-network/translations/ukui-shortcut-network_kk.ts0000664000175000017500000001150415167651420023621 0ustar fengfeng DeviceComboBox (Connected) (Not Connected) Current Network Card LanComponent network settings 网络配置 connected جالعانعان Not connected جالعاۋنبادٸ disconnect connect disconnect network 断开网络 connect network 连接网络 network property 网络属性 delete this network 删除此网络 Disconnect network Connect network تور اۋلاۋ Network property Delete this network نۇ توردى ٴوشىرۋ NetScrollViewArea Wired network سىمدى تور No wired network card was detected Wireless network More network Settings WlanComponent Network settings 网络配置 connected 已连接 Not connected 未连接 disconnect connect AutoConnect Disconnect network Connect network تور اۋلاۋ Network property Forget the network Add Others... باسقا تورعا قوسىلۋ... Connected,network is very good Connected,network is good Connected,network is average Connected,network weak Connected,network is weak kylin-nm/qml-network/translations/ukui-shortcut-network_zh_CN.ts0000664000175000017500000001146315167651420024221 0ustar fengfeng DeviceComboBox (Connected) (已连接) (Not Connected) (未连接) Current Network Card 当前网卡 LanComponent network settings 网络配置 connected 已连接 Not connected 未连接 disconnect 断开 connect 连接 disconnect network 断开网络 connect network 连接网络 network property 网络属性 delete this network 删除此网络 Disconnect network 断开网络 Connect network 连接网络 Network property 网络属性 Delete this network 删除此网络 (network restricted) 网络受限 NetScrollViewArea Wired network 有线网络 No wired network card was detected 未检测到有线网卡 Wireless network 无线网络 More network Settings 更多网络设置 WlanComponent Network settings 网络配置 connected 已连接 Not connected 未连接 disconnect 断开 connect 连接 AutoConnect 自动连接 Disconnect network 断开网络 Connect network 连接网络 Network property 网络属性 Forget the network 忘记此网络 Add Others... 加入其他网络... Connected,network is very good 已连接,网络很好 Connected,network is good 已连接,网络好 Connected,network is average 已连接,网络一般 Connected,network weak 已连接,网络弱 Connected,network is weak 已连接,网络很弱 kylin-nm/qml-network/translations/ukui-shortcut-network_ky.ts0000664000175000017500000001150515167651420023640 0ustar fengfeng DeviceComboBox (Connected) (Not Connected) Current Network Card LanComponent network settings 网络配置 connected جالعانعان Not connected ۇلانباعان disconnect connect disconnect network 断开网络 connect network 连接网络 network property 网络属性 delete this network 删除此网络 Disconnect network Connect network تور ۇلوو Network property Delete this network بۇل توردۇ ۅچۉرۉۉ NetScrollViewArea Wired network سىمدۇۇ تور No wired network card was detected Wireless network More network Settings WlanComponent Network settings 网络配置 connected 已连接 Not connected 未连接 disconnect connect AutoConnect Disconnect network Connect network تور ۇلوو Network property Forget the network Add Others... باشقا تورعو قوشۇلۇۇ... Connected,network is very good Connected,network is good Connected,network is average Connected,network weak Connected,network is weak kylin-nm/qml-network/translations/ukui-shortcut-network_zh_Hant.ts0000664000175000017500000001130415167651420024605 0ustar fengfeng DeviceComboBox (Connected) (已連線) (Not Connected) ( 未連線 ) Current Network Card 當前網卡 LanComponent network settings 网络配置 connected 已連接 Not connected 未連接 disconnect 斷開 connect 連接 disconnect network 断开网络 connect network 连接网络 network property 网络属性 delete this network 删除此网络 Disconnect network 斷開網路 Connect network 連接網路 Network property 網路屬性 Delete this network 刪除此網路 NetScrollViewArea Wired network 有線網路 No wired network card was detected 未檢測到有線網卡 Wireless network 無線網路 More network Settings 更多網路設置 WlanComponent Network settings 网络配置 connected 已连接 Not connected 未连接 disconnect 斷開 connect 連接 AutoConnect 自動連接 Disconnect network 斷開網路 Connect network 連接網路 Network property 網路屬性 Forget the network 忘記此網路 Add Others... 加入其他網路... Connected,network is very good 已連接,網路很好 Connected,network is good 已連接,網路好 Connected,network is average 已連接,網路一般 Connected,network weak 已連接,網路弱 Connected,network is weak 已連接,網路很弱 kylin-nm/qml-network/translations/ukui-shortcut-network_bo_CN.ts0000664000175000017500000001450715167651420024202 0ustar fengfeng DeviceComboBox (Connected) (འབྲེལ་མཐུད་བྱས་ཟིན་པ། ) (Not Connected) (འབྲེལ་མཐུད་མ་བྱས་པ། ) Current Network Card མིག་སྔར་དྲ་བྱང་། LanComponent network settings 网络配置 connected འབྲེལ་མཐུད་བྱེད་ཟིན། Not connected འབྲེལ་མཐུད་མི་བྱེད་པ། disconnect བར་མཚམས་ཆད་པ་རེད། connect འབྲེལ་མཐུད་བཅས་བྱ་དགོས། disconnect network 断开网络 connect network 连接网络 network property 网络属性 delete this network 删除此网络 Disconnect network དྲ་བ་གཅོད་དགོས། Connect network དྲ་རྒྱ་དང་སྦྲེལ་མཐུད་བྱ་དགོས། Network property དྲ་རྒྱའི་ངོ་བོ། Delete this network དྲ་རྒྱ་དེ་བསུབ་དགོས། NetScrollViewArea Wired network སྐུད་ཡོད་དྲ་བ། No wired network card was detected སྐུད་ཡོད་དྲ་བའི་གཱ་ལ་ཞིབ་དཔྱད་ཚད་ལེན་མ་བྱས་པ། Wireless network སྐུད་མེད་དྲ་བ། More network Settings དྲ་བ་སྔར་ལས་མང་བ་བཀོད་སྒྲིག་བྱེད WlanComponent Network settings 网络配置 connected 已连接 Not connected 未连接 disconnect བར་མཚམས་ཆད་པ་རེད། connect འབྲེལ་མཐུད་བཅས་བྱ་དགོས། AutoConnect རང་འགུལ་གྱིས་སྦྲེལ་མཐུད་བྱ་དགོས། Disconnect network དྲ་བ་གཅོད་དགོས། Connect network དྲ་རྒྱ་དང་སྦྲེལ་མཐུད་བྱ་དགོས། Network property དྲ་རྒྱའི་ངོ་བོ། Forget the network དྲ་རྒྱ་དེ་བརྗེད་པ་རེད། Add Others... གཞན་པ་ཁ་སྣོན་བྱས་ནས་... Connected,network is very good འབྲེལ་མཐུད་བྱས་ཟིན་པས་དྲ་རྒྱ་ཧ་ཅང་བཟང་། Connected,network is good འབྲེལ་མཐུད་བྱས་ཟིན་པས་དྲ་རྒྱ་ཡག་པོ་ཡོད། Connected,network is average འབྲེལ་མཐུད་བྱས་ཟིན་པས་དྲ་རྒྱ་སྤྱིར་བཏང་ཡིན། Connected,network weak འབྲེལ་མཐུད་བྱས་ཟིན་པས་དྲ་རྒྱ་ཉམས་པ། Connected,network is weak འབྲེལ་མཐུད་བྱས་ཟིན་པས་དྲ་རྒྱ་ཧ་ཅང་ཞན། kylin-nm/qml-network/translations/ukui-shortcut-network_mn.ts0000664000175000017500000001446415167651420023636 0ustar fengfeng DeviceComboBox (Connected) ( ᠨᠢᠭᠡᠨᠲᠡ ᠬᠣᠯᠪᠣᠭᠳᠠᠨ᠎ᠠ ) (Not Connected) ( ᠬᠣᠯᠪᠣᠯᠳᠤᠭᠰᠠᠨ ᠦᠭᠡᠢ ) Current Network Card ᠣᠳᠣᠬᠠᠨ ᠳᠤ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠺᠣᠮᠫᠠᠨᠢ ᠃ LanComponent network settings 网络配置 connected ᠴᠦᠷᠬᠡᠯᠡᠪᠡ Not connected ᠵᠠᠯᠭᠠᠭ᠎ᠠ ᠦᠭᠡᠢ disconnect ᠲᠠᠰᠤᠷᠠᠪᠠ ᠃ connect ᠵᠠᠯᠭᠠᠬᠤ ᠃ disconnect network 断开网络 connect network 连接网络 network property 网络属性 delete this network 删除此网络 Disconnect network ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠶᠢ ᠲᠠᠰᠤᠯᠤᠨ᠎ᠠ ᠃ Connect network ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠵᠠᠯᠭᠠᠬᠤ Network property ᠲᠣᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠰᠢᠨᠵᠢ ᠴᠢᠨᠠᠷ ᠃ Delete this network ᠲᠤᠰ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠬᠠᠰᠤᠬᠤ NetScrollViewArea Wired network ᠤᠳᠠᠰᠤᠳᠤ ᠰᠦᠯᠵᠢᠶ᠎ᠡ No wired network card was detected ᠤᠲᠠᠰᠤᠲᠤ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠺᠣᠮᠫᠢᠦᠢᠲ᠋ᠧᠷ ᠢ ᠪᠠᠶᠢᠴᠠᠭᠠᠨ ᠰᠢᠯᠭᠠᠭᠰᠠᠨ ᠦᠭᠡᠶ ᠃ Wireless network ᠤᠲᠠᠰᠤ ᠦᠭᠡᠢ ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠃ More network Settings ᠨᠡᠩ ᠣᠯᠠᠨ ᠲᠣᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠪᠠᠶᠢᠷᠢᠯᠠᠭᠤᠯᠤᠯᠲᠠ ᠃ WlanComponent Network settings 网络配置 connected 已连接 Not connected 未连接 disconnect ᠲᠠᠰᠤᠷᠠᠪᠠ ᠃ connect ᠵᠠᠯᠭᠠᠬᠤ ᠃ AutoConnect ᠠᠦᠢᠲ᠋ᠣ᠋ ᠬᠣᠯᠪᠣᠭ᠎ᠠ ᠃ Disconnect network ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠶᠢ ᠲᠠᠰᠤᠯᠤᠨ᠎ᠠ ᠃ Connect network ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠵᠠᠯᠭᠠᠬᠤ Network property ᠲᠣᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠰᠢᠨᠵᠢ ᠴᠢᠨᠠᠷ ᠃ Forget the network ᠡᠨᠡ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠶᠢ ᠮᠠᠷᠲᠠ ᠃ Add Others... ᠪᠤᠰᠤᠳ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠵᠠᠯᠭᠠᠬᠤ··· Connected,network is very good ᠨᠢᠭᠡᠨᠲᠡ ᠬᠣᠯᠪᠣᠭᠳᠠᠵᠠᠢ ᠂ ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠲᠣᠩ ᠰᠠᠢ᠌ᠨ ᠃ Connected,network is good ᠨᠢᠭᠡᠨᠲᠡ ᠬᠣᠯᠪᠣᠭᠳᠠᠵᠠᠢ ᠂ ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠰᠠᠶᠢᠨ ᠃ Connected,network is average ᠨᠢᠭᠡᠨᠲᠡ ᠬᠣᠯᠪᠣᠭᠳᠠᠵᠤ ᠂ ᠲᠣᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠨᠢ ᠡᠩ ᠦᠨ ᠪᠠᠶᠢᠳᠠᠭ ᠃ Connected,network weak ᠨᠢᠭᠡᠨᠲᠡ ᠬᠣᠯᠪᠣᠭᠳᠠᠵᠤ ᠂ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠪᠠᠭᠤᠷᠠᠶ ᠃ Connected,network is weak ᠨᠢᠭᠡᠨᠲᠡ ᠬᠣᠯᠪᠣᠭᠳᠠᠵᠠᠢ ᠂ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠲᠤᠩ ᠪᠠᠭᠤᠷᠠᠢ ᠃ kylin-nm/qml-network/translations/ukui-shortcut-network_zh_HK.ts0000664000175000017500000001130415167651420024215 0ustar fengfeng DeviceComboBox (Connected) (已連線) (Not Connected) ( 未連線 ) Current Network Card 當前網卡 LanComponent network settings 网络配置 connected 已連接 Not connected 未連接 disconnect 斷開 connect 連接 disconnect network 断开网络 connect network 连接网络 network property 网络属性 delete this network 删除此网络 Disconnect network 斷開網路 Connect network 連接網路 Network property 網路屬性 Delete this network 刪除此網路 NetScrollViewArea Wired network 有線網路 No wired network card was detected 未檢測到有線網卡 Wireless network 無線網路 More network Settings 更多網路設置 WlanComponent Network settings 网络配置 connected 已连接 Not connected 未连接 disconnect 斷開 connect 連接 AutoConnect 自動連接 Disconnect network 斷開網路 Connect network 連接網路 Network property 網路屬性 Forget the network 忘記此網路 Add Others... 加入其他網路... Connected,network is very good 已連接,網路很好 Connected,network is good 已連接,網路好 Connected,network is average 已連接,網路一般 Connected,network weak 已連接,網路弱 Connected,network is weak 已連接,網路很弱 kylin-nm/qml-network/widget/0000775000175000017500000000000015167651420015010 5ustar fengfengkylin-nm/qml-network/widget/load-up.png0000664000175000017500000000030215167651420017052 0ustar fengfengPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<dIDATxb`WB|Ƨ  P6VC:&lȶ`5 @,&| X43@K#63ĂQ`~F0>IENDB`kylin-nm/qml-network/widget/view-wrapped-symbolic.svg0000664000175000017500000000131315167651420021760 0ustar fengfengkylin-nm/qml-network/widget/ui/0000775000175000017500000000000015167651420015425 5ustar fengfengkylin-nm/qml-network/widget/ui/NetScrollViewArea.qml0000664000175000017500000004002315167651420021470 0ustar fengfengimport QtQuick 2.12 import QtQuick.Window 2.12 import QtQuick.Controls 2.5 import QtQuick.Layouts 1.15 import QtQuick.Controls.Material 2.3 import org.ukui.shortcut.network 1.0 import org.ukui.quick.items 1.0 as UkuiItems import org.ukui.quick.platform 1.0 as Platform UkuiItems.DtThemeBackground { id: root backgroundColor: Platform.GlobalTheme.kContainSecondaryAlphaNormal radius: Platform.GlobalTheme.kRadiusWindow ColumnLayout { anchors.fill: parent spacing: 0 RowLayout { id: nttop width: parent.width Layout.alignment: Qt.AlignTop Layout.preferredHeight: 56 Item { Layout.fillWidth: true } } MenuSeparator { Layout.alignment: Qt.AlignTop Layout.fillWidth: true height: 1 } ScrollView { visible: true Layout.alignment: Qt.AlignTop Layout.fillWidth: true Layout.fillHeight: true ScrollBar.vertical.policy: ScrollBar.AsNeeded ScrollBar.horizontal.policy: ScrollBar.AlwaysOff clip: true Flickable { anchors.fill: parent contentWidth : parent.width contentHeight: wlanTop.height + lanTop.height + (lanDeviceComboBox.visible ? lanDeviceComboBox.height : 0) + (lanContentArea.visible ? lanContentArea.height : 0) + (wlanDeviceComboBox.visible ? wlanDeviceComboBox.height : 0) + (wlanContentArea.visible ? wlanContentArea.height : 0) + 40 ColumnLayout { width: parent.width RowLayout { id : lanTop width: parent.width Layout.alignment: Qt.AlignTop visible: lanDeviceComboBox.count >= 1 UkuiItems.DtThemeText { text: qsTr("Wired network") Layout.alignment: Qt.AlignLeft Layout.leftMargin: 24 } UkuiItems.Icon { id: lanVisibleButton visible: KInterface.wiredMainSwitch source: "file:///usr/share/ukui/widgets/org.ukui.shortcut.network/ukui-up-symbolic.svg" width: 16 height: 16 mode: UkuiItems.Icon.AutoHighlight property bool visibleState : true MouseArea { anchors.fill: lanVisibleButton hoverEnabled: true onClicked: { lanVisibleButton.visibleState = !lanVisibleButton.visibleState; if (lanVisibleButton.visibleState) { lanVisibleButton.source = "file:///usr/share/ukui/widgets/org.ukui.shortcut.network/ukui-up-symbolic.svg" } else { lanVisibleButton.source = "file:///usr/share/ukui/widgets/org.ukui.shortcut.network/arrow-down.svg" } if (!lanswitchBtn.checked) return lanContentArea.visible = lanVisibleButton.visibleState lanDeviceComboBox.visible = lanVisibleButton.visibleState && !lanDeviceComboBox.ishide && (lanDeviceComboBox.count >= 2) //lanNoWiredItem.visible = lanVisibleButton.visibleState && (lanDeviceComboBox.count === 0) } } Layout.preferredWidth: 16 } Item { Layout.fillWidth: true } SwitchDelegate { id: lanswitchBtn checked: KInterface.wiredMainSwitch enabled: (lanDeviceComboBox.count !== 0) onClicked: { KInterface.wiredMainSwitch = lanswitchBtn.checked if (lanVisibleButton.visibleState) { lanContentArea.visible = lanswitchBtn.checked lanDeviceComboBox.visible = lanswitchBtn.checked && !lanDeviceComboBox.ishide && (lanDeviceComboBox.count >= 2) } else { lanContentArea.visible = false lanDeviceComboBox.visible = false } } Layout.alignment: Qt.AlignRight Layout.rightMargin: 24 spacing:0 rightPadding: 0 Layout.preferredWidth: 44 } } Rectangle { id: lanNoWiredItem Layout.fillWidth: true Layout.preferredHeight: 60 Layout.alignment: Qt.AlignTop visible: false Image { width: 16 height: 16 anchors.right: lanNoWiredText.left Layout.rightMargin: 5 anchors.verticalCenter: parent.verticalCenter source: "file:///usr/share/ukui/widgets/org.ukui.shortcut.network/dialog-warning.svg" } UkuiItems.DtThemeText { id: lanNoWiredText anchors.leftMargin: 20 anchors.verticalCenter: parent.verticalCenter anchors.horizontalCenter: parent.horizontalCenter text: qsTr("No wired network card was detected") } } DeviceComboBox { id: lanDeviceComboBox width: parent.width spacing: 0 model: KInterface.wiredDevList visible: lanswitchBtn.checked && lanVisibleButton.visibleState && !lanNoWiredItem.visible && (lanDeviceComboBox.count>=2) property bool ishide : false currentConnect: lanContentArea.connectMac onCurrentTextChanged: { KInterface.getWiredDevConnList(lanDeviceComboBox.currentText); } Connections { target: KInterface onUpdateWiredDeviceList: { if (lanDeviceComboBox.count <= 0) { lanDeviceComboBox.ishide = true lanContentArea.visible = false //lanNoWiredItem.visible = true lanDeviceComboBox.enabled = false; } else { //lanNoWiredItem.visible = false lanDeviceComboBox.enabled = true; } if (lanDeviceComboBox.count <= 1) { lanDeviceComboBox.ishide = true lanDeviceComboBox.visible = false } else { lanDeviceComboBox.ishide = false lanContentArea.visible = true && lanswitchBtn.checked && lanVisibleButton.visibleState && !lanNoWiredItem.visible lanDeviceComboBox.visible = true && lanswitchBtn.checked && lanVisibleButton.visibleState && !lanNoWiredItem.visible } KInterface.getWiredDevConnList(lanDeviceComboBox.currentText); } } } LanComponent{ id: lanContentArea Layout.alignment: Qt.AlignTop interactive: false implicitHeight: lanContentArea.contentHeight width: 396 } MenuSeparator { Layout.fillWidth: true Layout.leftMargin: 16 Layout.rightMargin: 16 height: 1 visible: (wlanDeviceComboBox.count >= 1 && lanDeviceComboBox.count >= 1) } RowLayout { id : wlanTop width: parent.width Layout.alignment: Qt.AlignTop UkuiItems.DtThemeText { text: qsTr("Wireless network") Layout.alignment: Qt.AlignLeft Layout.leftMargin: 24 visible: wlanDeviceComboBox.count >= 1 } UkuiItems.Icon { id: wlanRescanButton source: "file:///usr/share/ukui/widgets/org.ukui.shortcut.network/view-wrapped-symbolic.svg" width: 16 height: 16 mode: UkuiItems.Icon.AutoHighlight visible: wlanswitchBtn.checked && (wlanDeviceComboBox.count >= 1) MouseArea { anchors.fill: parent hoverEnabled: true onClicked: { srotation.start() animationTimer.start() KInterface.rescanWirelessConn() } } Layout.preferredWidth: 16 } RotationAnimator { id: srotation target: wlanRescanButton from: 0 to: 360 duration: 2000 // 旋转一圈需要的时间,单位为毫秒 loops: Animation.Infinite // 无限循环 } Timer { id: animationTimer interval: 5000 // 计时器间隔时间,单位为毫秒(1000毫秒 = 1秒) repeat: false // 是否重复计时 running: false // 默认不启动计时器 onTriggered: { // 这里定义计时器触发时执行的代码 srotation.stop() } } Item { Layout.fillWidth: true } SwitchDelegate { id: wlanswitchBtn checked: KInterface.wirelessSwitch enabled: (wlanDeviceComboBox.count >= 1) onClicked: { if(!enabled) { wlanswitchBtn.checked=false KInterface.wirelessSwitch = wlanswitchBtn.checked return } KInterface.wirelessSwitch = wlanswitchBtn.checked wlanDeviceComboBox.visible = !wlanDeviceComboBox.ishide && wlanswitchBtn.checked && (wlanDeviceComboBox.count >= 2) wlanContentArea.visible = wlanswitchBtn.checked } Layout.alignment: Qt.AlignRight Layout.rightMargin: 24 spacing:0 rightPadding: 0 visible: wlanDeviceComboBox.count >= 1 Layout.preferredWidth: 44 } } Item { Layout.fillWidth: true } DeviceComboBox { id: wlanDeviceComboBox spacing: 0 visible: wlanswitchBtn.checked && wlanDeviceComboBox.count > 1 model: KInterface.wirelessDevList width: parent.width property bool ishide : wlanDeviceComboBox.count > 1 currentConnect: wlanContentArea.connectMac onCurrentTextChanged: { KInterface.getWirelessDevConnList(wlanDeviceComboBox.currentText); KInterface.rebuildCurrentWirelessList() } Connections { target: KInterface onUpdateWirelessDeviceList: { if (wlanDeviceComboBox.count <= 1) { wlanDeviceComboBox.ishide = true wlanDeviceComboBox.visible = false } else { wlanDeviceComboBox.ishide = false wlanContentArea.visible = true && wlanswitchBtn.checked wlanDeviceComboBox.visible = true && wlanswitchBtn.checked } if (wlanDeviceComboBox.count <= 0) { wlanDeviceComboBox.ishide = true wlanContentArea.visible = false } KInterface.getWirelessDevConnList(wlanDeviceComboBox.currentText); } } } WlanComponent{ id: wlanContentArea Layout.alignment: Qt.AlignBottom interactive: false implicitHeight: wlanContentArea.contentHeight width: 396 } } } } MenuSeparator { Layout.alignment: Qt.AlignBottom Layout.fillWidth: true Layout.bottomMargin: 1 height: 1 } Item { Layout.fillWidth: true Layout.preferredHeight: 56 Layout.alignment: Qt.AlignBottom opacity: Theme.windowOpacity UkuiItems.DtThemeText { id: networkSettingText height: 22 anchors.verticalCenter: parent.verticalCenter anchors.left: parent.left anchors.leftMargin: 24 text: qsTr("More network Settings") textColor: Platform.GlobalTheme.kFontStrong MouseArea { anchors.fill: parent hoverEnabled: true onClicked: { console.log("NetworkSettingArea.qml onClicked") KInterface.openNetworkSetting() } onEntered: { networkSettingText.textColor = Platform.GlobalTheme.highlightActive } onExited: { networkSettingText.textColor = Platform.GlobalTheme.kFontStrong } } } } } } kylin-nm/qml-network/widget/ui/WlanComponent.qml0000664000175000017500000005737715167651420020747 0ustar fengfengimport QtQuick 2.15 import QtQuick.Window 2.15 import QtQuick.Controls 2.5 import QtQuick.Layouts 1.1 import QtQuick.Controls.Material 2.3 import org.ukui.shortcut.network 1.0 import org.ukui.quick.items 1.0 as UkuiItems import org.ukui.quick.platform 1.0 as Platform ListView { id: wlanlistView visible: true model: KInterface.wirelessConLists spacing: 0 property int baseItemHeight: 56 property int expandedItemHeight: 145 Component.onCompleted: { // map font size to heights (simple scaling) function updateHeights(fontSize) { var size = parseInt(fontSize) if (!isNaN(size)) { baseItemHeight = Math.round(56 * size / 10) expandedItemHeight = Math.round(145 * size / 10) } } updateHeights(KInterface.fontSize) } Connections { target: KInterface function onFontSizeChanged(fontSize) { var size = parseInt(fontSize) if (!isNaN(size)) { wlanlistView.baseItemHeight = Math.round(56 * size / 10) wlanlistView.expandedItemHeight = Math.round(145 * size / 10) } } } property bool connectMac : false property int detailShowIndex : -1 property var currentOpenMenu: null function updateMacConnAttr(ipos, status) { if (0 === ipos) { connectMac = status } } function updateShowDetailIndex(ipos) { console.log("detail index: ", ipos) detailShowIndex = ipos for(var i=0; i 5000 ? 1 : 2; color: "transparent" radius: 4 border { color: Platform.GlobalTheme.kFontPlaceholderText.pureColor width: 1 } TextMetrics { id: textMetrics font: dtThemeText.font text: dtThemeText.text } UkuiItems.DtThemeText { id: dtThemeText anchors.centerIn: parent property int wlan_type : model.isMix ? 0 : model.frequency > 5000 ? 1 : 2; text: wlan_type === 0 ? "2.4G/5G" : wlan_type === 1 ? "5G" : "2.4G" textColor: Platform.GlobalTheme.kFontPlaceholderText } } } RowLayout { visible: false id: textEditLayout Layout.topMargin: 10 // 动态加载TextField Loader { id: textEditLoader active: false sourceComponent: TextField { id: textEdit width: 208 height: 36 Layout.leftMargin: 10 echoMode: TextInput.Password property bool passMode: true property int textLength: textEdit.text.length onTextLengthChanged: { if(textLength>=8) { if (pwdConnectBtnLoader.item) { pwdConnectBtnLoader.item.enabled = true } } else { if (pwdConnectBtnLoader.item) { pwdConnectBtnLoader.item.enabled = false } } } onAccepted: { typeicon.visible = false; loadingicon.visible = true; KInterface.passwordConnect(wlanDeviceComboBox.currentText, model.ssid, model.security, textEdit.text, autoConnectCheckBoxLoader.item ? autoConnectCheckBoxLoader.item.checkState : true) } } } // 动态加载Button Loader { id: pwdConnectBtnLoader active: false sourceComponent: Button { id: pwdConnectBtn highlighted: true width: 88 height: 36 Layout.rightMargin: 24 Layout.alignment: Qt.AlignRight | Qt.AlignVCenter text: qsTr("connect") onClicked: { typeicon.visible = false; loadingicon.visible = true; KInterface.passwordConnect(wlanDeviceComboBox.currentText, model.ssid, model.security, textEditLoader.item ? textEditLoader.item.text : "", autoConnectCheckBoxLoader.item ? autoConnectCheckBoxLoader.item.checkState : true) } Component.onCompleted: { pwdConnectBtn.enabled = (textEditLoader.item && textEditLoader.item.textLength>=8 ? true : false) } } } } RowLayout { UkuiItems.DtThemeText { visible: model.status === 2 Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter Layout.topMargin: 0 Layout.leftMargin: 12 text: { const signal = parseInt(model.signal); return signal > 80 ? qsTr("Connected,network is very good") : signal > 55 ? qsTr("Connected,network is good") : signal > 30 ? qsTr("Connected,network is average") : signal > 5 ? qsTr("Connected,network weak") : qsTr("Connected,network is weak"); } textColor: Platform.GlobalTheme.kFontPlaceholderText height: 16 elide: Text.ElideRight } // 动态加载CheckBox Loader { id: autoConnectCheckBoxLoader active: false sourceComponent: CheckBox { id: autoConnectCheckBox Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter visible: false Layout.leftMargin: 8 Layout.topMargin: 0 text: qsTr("AutoConnect") checked: true onClicked: { mouse.accepted = true } onVisibleChanged: { if (visible) { updateShowDetailIndex(index) } } } } } } Item { Layout.fillWidth: true } Rectangle { id: speedLabel visible: true Layout.preferredWidth: 140 Layout.alignment: Qt.AlignRight | Qt.AlignVCenter Image { id: upLoadicon visible: model.status === 2 anchors.right: upLoadWirelessText.left anchors.verticalCenter: parent.verticalCenter source: "file:///usr/share/ukui/widgets/org.ukui.shortcut.network/load-up.png" } UkuiItems.DtThemeText { id: upLoadWirelessText visible: model.status === 2 anchors.right: downLoadIcon.left anchors.verticalCenter: parent.verticalCenter text: "0KB/s" Connections { target: KInterface function onUpdateUpLoadWirelessStr(str) { upLoadWirelessText.text = str } } } Image { id: downLoadIcon visible: model.status === 2 anchors.right: downLoadWirelessText.left anchors.verticalCenter: parent.verticalCenter source: "file:///usr/share/ukui/widgets/org.ukui.shortcut.network/load-down.png" } UkuiItems.DtThemeText { id: downLoadWirelessText visible: model.status === 2 anchors.rightMargin: 32 anchors.right: parent.right anchors.verticalCenter: parent.verticalCenter text: "0KB/s" Connections { target: KInterface function onUpdateDownLoadWirelessStr(str) { downLoadWirelessText.text = str } } } } Button { id: connectBtn visible: false width: 88 height: 36 Layout.rightMargin: 24 Layout.alignment: Qt.AlignRight | Qt.AlignVCenter text: (model.status === 2) ? qsTr("disconnect") : qsTr("connect") highlighted: (model.status === 2) ? 0 : 1 MouseArea { id: connectBtnHandler propagateComposedEvents: true hoverEnabled: true property bool showButton: containsMouse anchors.fill: parent onEntered: { if (textEditLayout.visible) return enteritem = true connectBtn.visible = true speedLabel.visible = false } onExited: { wlanlistView.currentIndex = -1 enteritem = false connectBtn.visible = false speedLabel.visible = (model.status === 2) } onClicked: { mouse.accepted = false } } } } } } footer: Button { id: addOtherBtn visible: wlanDeviceComboBox.count >= 1 width: parent.width height: 40 Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter hoverEnabled: true UkuiItems.DtThemeText { text: qsTr("Add Others...") anchors.top: parent.top anchors.topMargin: (parent.height-height)/2 //垂直居中设置不生效使用边距控制居中 anchors.left: parent.left anchors.leftMargin: 26 } onClicked: { console.log("addOtherBtn onClicked ",parent.verticalCenter,anchors.verticalCenter) KInterface.showAddOtherWlanPage(wlanDeviceComboBox.currentText); mouse.accepted = true } } } kylin-nm/qml-network/widget/ui/LanComponent.qml0000664000175000017500000002574715167651420020554 0ustar fengfengimport QtQuick 2.15 import QtQuick.Window 2.15 import QtQuick.Controls 2.5 import QtQuick.Layouts 1.1 import QtQuick.Controls.Material 2.3 import org.ukui.shortcut.network 1.0 import org.ukui.quick.items 1.0 as UkuiItems import org.ukui.quick.platform 1.0 as Platform ListView { id: lanlistView visible: lanswitchBtn.checked && lanVisibleButton.visibleState && !lanNoWiredItem.visible model: KInterface.wiredConList spacing: 0 property bool connectMac : false function updateMacConnAttr(ipos, status) { if(0 === ipos) connectMac = status } // 定义每个项的显示方式 delegate: ItemDelegate { highlighted: enteritem && lanlistView.currentIndex === index width: lanlistView.width height: 56 property bool enteritem : false property bool conConnected: modelData.State === 2 onConConnectedChanged: { updateMacConnAttr(index, conConnected) } Component.onCompleted: { updateMacConnAttr(index, conConnected) } RowLayout { anchors.fill: parent Menu { id: propertyMenu MenuItem { text:(modelData.State === 2)?qsTr("Disconnect network"):qsTr("Connect network") onTriggered: { console.log("connect/disconnect network") if (modelData.State === 2) KInterface.deActivateConnect(lanDeviceComboBox.currentText, modelData.Uuid, 0); else if (modelData.State === 4) KInterface.activateConnect(lanDeviceComboBox.currentText, modelData.Uuid, 0); typeicon.visible = false; loadingicon.visible = true; } } MenuItem { text:qsTr("Network property") onTriggered: { console.log("network property") console.log("network property",lanDeviceComboBox.currentText,modelData.Name,modelData.Uuid) KInterface.showPropertyWidget(lanDeviceComboBox.currentText, modelData.Uuid) } } MenuItem { text:qsTr("Delete this network") onTriggered: { console.log("delete this network",modelData.Uuid) KInterface.deleteConnect(0,modelData.Uuid) } } } Item { Layout.alignment: Qt.AlignLeft Layout.leftMargin: 26 width: 36 height: 36 UkuiItems.IconButton { id: typeicon //这里添加拨号的类型 visible: modelData.State === 2 || modelData.State === 4 iconSource: { if (modelData.IsDSL) { // 假设modelData中有Type属性表示连接类型 ("ukui-dial-up-symbolic") } else { (modelData.State === 2) ? ("network-wired-connected-symbolic") : ("network-wired-disconnected-symbolic") } } anchors.fill: parent radius: 19 isHighLight: modelData.State === 2 width: parent.width height: parent.height } UkuiItems.IconButton { id: loadingicon visible: modelData.State === 1 || modelData.State === 3 iconSource: "ukui-loading-" + String(loadingicon.loading_num % 8) + "-symbolic" anchors.fill: parent radius: 19 isHighLight: modelData.State === 3 width: parent.width height: parent.height property int loading_num : 0 } Timer { interval: 100 running: true//modelData.State === 1 || modelData.State === 3 repeat: true onTriggered:{ loadingicon.loading_num += 1; loadingicon.iconSource = "ukui-loading-" + String(loadingicon.loading_num % 8) + "-symbolic"; } } MouseArea { onClicked: { nameLabel.visible = false nameStateLabel.visible = true } } } UkuiItems.DtThemeText { id: nameLabel Layout.alignment: Qt.AlignLeft Layout.leftMargin: 8 Layout.preferredWidth: 150 text: modelData.Name elide: Text.ElideRight MouseArea { onClicked: { nameLabel.visible = false nameStateLabel.visible = true } } } UkuiItems.DtThemeText { id: nameStateLabel visible: false Layout.alignment: Qt.AlignLeft | Qt.AlignTop Layout.leftMargin: 8 Layout.topMargin: 8 Layout.preferredWidth: 150 text: modelData.Name elide: Text.ElideRight UkuiItems.DtThemeText { id: stateLabel Layout.alignment: Qt.AlignLeft | Qt.AlignBottom Layout.leftMargin: 8 Layout.bottomMargin: 8 anchors.top: nameStateLabel.bottom text: modelData.State === 2 ? (modelData.Connectivity === 3 ? qsTr("connected") + "," + qsTr("(network restricted)") : qsTr("connected")) : qsTr("Not connected") } } Item { Layout.fillWidth: true } Rectangle { id: speedLabel visible: true Layout.preferredWidth: 140 Layout.alignment: Qt.AlignRight | Qt.AlignVCenter Image { id: upLoadicon visible: modelData.State === 2 anchors.right: upLoadWiredText.left anchors.verticalCenter: parent.verticalCenter source: "file:///usr/share/ukui/widgets/org.ukui.shortcut.network/load-up.png" } UkuiItems.DtThemeText { id: upLoadWiredText visible: modelData.State === 2 anchors.right: downLoadIcon.left anchors.verticalCenter: parent.verticalCenter text: "0KB/s" Connections { target: KInterface onUpdateUpLoadWiredStr : { upLoadWiredText.text = KInterface.upwareRate } } } Image { id: downLoadIcon visible: modelData.State === 2 anchors.right: downLoadWiredText.left anchors.verticalCenter: parent.verticalCenter source: "file:///usr/share/ukui/widgets/org.ukui.shortcut.network/load-down.png" } UkuiItems.DtThemeText { id: downLoadWiredText visible: modelData.State === 2 anchors.rightMargin: 32 anchors.right: parent.right anchors.verticalCenter: parent.verticalCenter text: "0KB/s" Connections { target: KInterface onUpdateDownLoadWiredStr : { downLoadWiredText.text = KInterface.downwareRate } } } } Button { id: connectBtn visible: false width: 88 height: 36 Layout.rightMargin: 24 Layout.alignment: Qt.AlignRight | Qt.AlignVCenter text: (modelData.State === 2) ? qsTr("disconnect") : qsTr("connect") highlighted: (modelData.State === 2) ? 0 : 1 MouseArea { anchors.fill: parent onClicked: { // // 设置当前选中项 if (modelData.State === 2) KInterface.deActivateConnect(lanDeviceComboBox.currentText, modelData.Uuid, 0); else if (modelData.State === 4) KInterface.activateConnect(lanDeviceComboBox.currentText, modelData.Uuid, 0); //typeicon.visible = false; //loadingicon.visible = true; } } } } MouseArea { anchors.fill: parent hoverEnabled: true acceptedButtons: Qt.AllButtons propagateComposedEvents: true onReleased: { nameLabel.visible = false nameStateLabel.visible = true } onEntered: { //console.log("index: " , index) enteritem = true connectBtn.visible = true speedLabel.visible = false } onExited: { //console.log("index: " , index) lanlistView.currentIndex = -1 enteritem = false connectBtn.visible = false speedLabel.visible = (modelData.State === 2) nameLabel.visible = true nameStateLabel.visible = false } onClicked: { mouse.accepted = false if (mouse.button == Qt.RightButton) { propertyMenu.popup() } } } Connections { target: KInterface // onUpdatePairedDevice : { // if(device === modelData.Addr) { // if(attrs.hasOwnProperty("Connecting")) { // typeicon.visible = !attrs.Connecting; // loadingicon.visible = attrs.Connecting; // } // if(attrs.hasOwnProperty("Battery")) { // batteryicon.source = KInterface.getBluetoothBatteryIcon(attrs.Battery); // batterytext.text = attrs.Battery + "%" // } // } // } } } } kylin-nm/qml-network/widget/ui/DeviceComboBox.qml0000664000175000017500000000643715167651420021002 0ustar fengfengimport QtQuick 2.15 import QtQuick.Window 2.15 import QtQuick.Controls 2.5 import QtQuick.Layouts 1.1 import QtQuick.Controls.Material 2.3 import org.ukui.quick.items 1.0 as UkuiItems import org.ukui.quick.platform 1.0 as Platform import org.ukui.shortcut.network 1.0 ComboBox { id: comboBoxOrigin Layout.alignment: Qt.AlignVCenter visible: true Layout.maximumHeight: 50 Layout.minimumHeight: 36 Layout.fillWidth: true Layout.leftMargin: 24 Layout.rightMargin: 24 property bool currentConnect: false property var delegates: [] onCurrentConnectChanged: { for(var i=0; ikylin-nm/qml-network/widget/qml.qrc0000664000175000017500000000040615167651420016310 0ustar fengfeng ui/main.qml ui/WlanComponent.qml ui/NetScrollViewArea.qml ui/LanComponent.qml ui/DeviceComboBox.qml kylin-nm/qml-network/widget/metadata.json0000664000175000017500000000105415167651420017463 0ustar fengfeng{ "Authors": [ { "Name": "lixiang1", "Email": "lixiang1@kylinos.cn" } ], "Id": "org.ukui.shortcut.network", "Icon": "", "Name": "org-ukui-shortcut-network", "Name[zh_CN]": "快捷面板网络插件", "Tooltip": "network", "Tooltip[zh_CN]": "网络", "Description": "org.ukui.shortcut.network", "Description[zh_CN]": "快捷面板网络插件", "Version": "1.0", "ShowIn": "Shortcut", "WidgetType": "Widget", "Contents": { "Main": "ui/main.qml", "I18n": "translations/ukui-shortcut-network" } } kylin-nm/qml-network/widget/ukui-up-symbolic.svg0000664000175000017500000000234015167651420020746 0ustar fengfengkylin-nm/qml-network/widget/load-down.png0000664000175000017500000000030015167651420017373 0ustar fengfengPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<bIDATxb`hK"BdBX2QQ`#; pNCB.X?@{hl AbP9aTxH" BH &q_1DIENDB`kylin-nm/qml-network/widget/dialog-warning.svg0000664000175000017500000001506215167651420020437 0ustar fengfengkylin-nm/qml-network/translate_generation.sh0000775000175000017500000000056615167651420020303 0ustar fengfeng#!/bin/bash export PATH="/usr/lib/qt6/bin:$PATH" ts_list=(`ls translations/*.ts`) source /etc/os-release version=(`echo $ID`) for ts in "${ts_list[@]}" do printf "\nprocess ${ts}\n" if [ "$version" == "fedora" ] || [ "$version" == "opensuse-leap" ] || [ "$version" == "opensuse-tumbleweed" ];then lrelease-qt5 "${ts}" else lrelease "${ts}" fi done kylin-nm/qml-network/qml-network.pro0000664000175000017500000000444315167651420016534 0ustar fengfengTEMPLATE = lib TARGET = ukui-shortcut-network QT += quick dbus core CONFIG += plugin c++11 link_pkgconfig DEFINES += QT_DEPRECATED_WARNINGS PKGCONFIG += gsettings-qt6 LIBS += -lpthread # You can make your code fail to compile if it uses deprecated APIs. # In order to do so, uncomment the following line. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 HEADERS += \ plugin/CSingleton.h \ plugin/knmdatakeeper.h \ plugin/knmdbuscaller.h \ plugin/knminterface.h \ plugin/knmlandatakeeper.h \ plugin/knmwlandatakeeper.h \ plugin/netdevice.h \ plugin/networkqml_plugin.h \ plugin/wirelessconnectionmodel.h SOURCES += \ plugin/knmdatakeeper.cpp \ plugin/knmdbuscaller.cpp \ plugin/knminterface.cpp \ plugin/knmlandatakeeper.cpp \ plugin/knmwlandatakeeper.cpp \ plugin/netdevice.cpp \ plugin/networkqml_plugin.cpp \ plugin/wirelessconnectionmodel.cpp RESOURCES += widget/qml.qrc CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } inst1.files += widget/** inst1.path = /usr/share/ukui/widgets/org.ukui.shortcut.network inst2.files += plugin/qmldir inst2.path = $$[QT_INSTALL_LIBS]/qt6/qml/org/ukui/shortcut/network qm_files.files += translations/*.qm qm_files.path = /usr/share/ukui/widgets/org.ukui.shortcut.network/translations ts_files.files += translations/*.ts ts_files.path = /usr/share/ukui/widgets/org.ukui.shortcut.network/translations target.path = $$[QT_INSTALL_LIBS]/qt6/qml/org/ukui/shortcut/network TRANSLATIONS += \ translations/ukui-shortcut-network_zh_CN.ts \ translations/ukui-shortcut-network_zh_Hant.ts \ translations/ukui-shortcut-network_zh_HK.ts \ translations/ukui-shortcut-network_ug.ts \ translations/ukui-shortcut-network_mn.ts \ translations/ukui-shortcut-network_ky.ts \ translations/ukui-shortcut-network_kk.ts \ translations/ukui-shortcut-network_bo_CN.ts INSTALLS += inst1 \ inst2 \ qm_files \ ts_files \ target OBJECTS_DIR = ./obj/ MOC_DIR = ./moc/ DISTFILES += \ widget/ui/LanTop.qml \ widget/ui/NetScrollViewArea.qml \ widget/ui/WlanTop.qml kylin-nm/qml-network/plugin/0000775000175000017500000000000015167651420015023 5ustar fengfengkylin-nm/qml-network/plugin/knmwlandatakeeper.cpp0000664000175000017500000003265015167651420021232 0ustar fengfeng#include "knmwlandatakeeper.h" #include "knminterface.h" #include "knmdbuscaller.h" #define EXCELLENT_SIGNAL 80 #define GOOD_SIGNAL 55 #define OK_SIGNAL 30 #define LOW_SIGNAL 5 #define NONE_SIGNAL 0 #define SIGNAL_EXCELLENT 1 #define SIGNAL_GOOD 2 #define SIGNAL_OK 3 #define SIGNAL_LOW 4 #define SIGNAL_NONE 5 #define ICON_SIZE 16,16 const QString WIRELESS_SWITCH = "wirelessswitch"; const QByteArray GSETTINGS_SCHEMA = "org.ukui.kylin-nm.switch"; const QString KWifiSymbolic = "network-wireless-signal-excellent"; const QString KWifiLockSymbolic = "network-wireless-secure-signal-excellent"; const QString KWifiGood = "network-wireless-signal-good"; const QString KWifiLockGood = "network-wireless-secure-signal-good"; const QString KWifiOK = "network-wireless-signal-ok"; const QString KWifiLockOK = "network-wireless-secure-signal-ok"; const QString KWifiLow = "network-wireless-signal-low"; const QString KWifiLockLow = "network-wireless-secure-signal-low"; const QString KWifiNone = "network-wireless-signal-none"; const QString KWifiLockNone = "network-wireless-secure-signal-none"; const QString KWifi6Symbolic = "ukui-wifi6-full-symbolic"; const QString KWifi6PlusSymbolic = "ukui-wifi6+-full-symbolic"; const QString KWifi6LockSymbolic = "ukui-wifi6-full-pwd-symbolic"; const QString KWifi6PlusLockSymbolic= "ukui-wifi6+-full-pwd-symbolic"; const QString KWifi6Good = "ukui-wifi6-high-symbolic"; const QString KWifi6PlusGood = "ukui-wifi6+-high-symbolic"; const QString KWifi6LockGood = "ukui-wifi6-high-pwd-symbolic"; const QString KWifi6PlusLockGood = "ukui-wifi6+-high-pwd-symbolic"; const QString KWifi6OK = "ukui-wifi6-medium-symbolic"; const QString KWifi6PlusOK = "ukui-wifi6+-high-medium-symbolic"; const QString KWifi6LockOK = "ukui-wifi6-medium-pwd-symbolic"; const QString KWifi6PlusLockOK = "ukui-wifi6+-medium-pwd-symbolic"; const QString KWifi6Low = "ukui-wifi6-low-symbolic"; const QString KWifi6PlusLow = "ukui-wifi6+-low-symbolic"; const QString KWifi6LockLow = "ukui-wifi6-low-pwd-symbolic"; const QString KWifi6PlusLockLow = "ukui-wifi6+-low-pwd-symbolic"; const QString KWifi6None = "ukui-wifi6-none-symbolic"; const QString KWifi6PlusNone = "ukui-wifi6+-none-symbolic"; const QString KWifi6LockNone = "ukui-wifi6-none-pwd-symbolic"; const QString KWifi6PlusLockNone = "ukui-wifi6+-none-pwd-symbolic"; const QString KLanSymbolic = ":/img/plugins/netconnect/eth.svg"; const QString NoNetSymbolic = ":/img/plugins/netconnect/nonet.svg"; const QString KApSymbolic = "network-wireless-hotspot-symbolic"; const QString IsApConnection = "1"; KnmWlanDataKeeper::KnmWlanDataKeeper(QObject *parent) : KnmDataKeeper(parent) { m_pInterface = new QDBusInterface("com.kylin.network", "/com/kylin/network", "com.kylin.network", QDBusConnection::sessionBus()); if(!m_pInterface->isValid()) { qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } qDBusRegisterMetaType>(); // 无线网络断开或连接时刷新可用网络列表 connect(m_pInterface, SIGNAL(wlanactiveConnectionStateChanged(QString, QString, QString, int)), this, SLOT(onActiveConnectionChanged(QString, QString, QString, int)), Qt::QueuedConnection); //无线网络新增时添加网络 connect(m_pInterface, SIGNAL(wlanAdd(QString, QStringList)), this, SLOT(onNetworkAdd(QString, QStringList)), Qt::QueuedConnection); //删除无线网络 connect(m_pInterface, SIGNAL(wlanRemove(QString, QString)), this, SLOT(onNetworkRemove(QString, QString)), Qt::QueuedConnection); //网卡插拔处理 connect(m_pInterface, SIGNAL(wirelessDeviceStatusChanged()), this, SIGNAL(onDeviceStatusChanged()), Qt::QueuedConnection); //网卡name处理 connect(m_pInterface, SIGNAL(deviceNameChanged(QString, QString, int)), this, SLOT(onDeviceNameChanged(QString, QString, int)), Qt::QueuedConnection); //无线开关处理 connect(m_pInterface, SIGNAL(wirelessSwitchBtnChanged(bool)), this, SLOT(onSwitchBtnChanged(bool)), Qt::QueuedConnection); //更新列表顺序 //对部分QML功能有影响,待完善 // connect(m_pInterface, SIGNAL(timeToUpdate()), this, SLOT(updateList()), Qt::QueuedConnection); netSpeedInit(); } KnmWlanDataKeeper::~KnmWlanDataKeeper() { } QMap KnmWlanDataKeeper::makeConnectionMap(int status, QStringList conPath) { //属性个数偏移量,已连接的WiFi比未连接的WiFi属性多一个uuid //qWarning() << Q_FUNC_INFO << __LINE__ << "status:" << status << "conPath:" << conPath; int index = 0; QMap connectionMap; connectionMap.insert("Name", conPath.at(0)); connectionMap.insert("Signal", conPath.at(1)); connectionMap.insert("Security", conPath.at(2)); /*这个9根据后端链表每个项添加的参数来的,改了后端需要改这里,这里补充判断是否大>=9起保护作用*/ if (status == ACTIVATED || conPath.count()>=9) { connectionMap.insert("Uuid", conPath.at(3)); index = 1; } connectionMap.insert("isApConn", conPath.at(3 + index)); connectionMap.insert("category", conPath.at(4 + index).toInt()); connectionMap.insert("State", status); connectionMap.insert("Loading", false); connectionMap.insert("Configured", conPath.at(5 + index).toInt()); connectionMap.insert("frequency", conPath.at(6 + index).toUInt()); connectionMap.insert("isMix", conPath.at(7 + index).toInt()); return connectionMap; } int KnmWlanDataKeeper::setSignal(QString sg) { int signal = sg.toInt(); int signalLv = 0; if (signal > EXCELLENT_SIGNAL) { signalLv = 1; } else if (signal > GOOD_SIGNAL) { signalLv = 2; } else if (signal > OK_SIGNAL) { signalLv = 3; } else if (signal > LOW_SIGNAL) { signalLv = 4; } else { signalLv = 5; } return signalLv; } QString KnmWlanDataKeeper::getWiFiIconString(bool isLock, int strength, int category) { if (category == 0) { switch (strength) { case SIGNAL_EXCELLENT: return isLock ? KWifiLockSymbolic : KWifiSymbolic; case SIGNAL_GOOD: return isLock ? KWifiLockGood : KWifiGood; case SIGNAL_OK: return isLock ? KWifiLockOK : KWifiOK; case SIGNAL_LOW: return isLock ? KWifiLockLow : KWifiLow; case SIGNAL_NONE: return isLock ? KWifiLockNone : KWifiNone; default: return ""; } } else if (category == 1) { switch (strength) { case SIGNAL_EXCELLENT: return isLock ? KWifi6LockSymbolic : KWifi6Symbolic; case SIGNAL_GOOD: return isLock ? KWifi6LockGood : KWifi6Good; case SIGNAL_OK: return isLock ? KWifi6LockOK : KWifi6OK; case SIGNAL_LOW: return isLock ? KWifi6LockLow : KWifi6Low; case SIGNAL_NONE: return isLock ? KWifi6LockNone : KWifi6None; default: return ""; } } else { switch (strength) { case SIGNAL_EXCELLENT: return isLock ? KWifi6PlusLockSymbolic : KWifi6PlusSymbolic; case SIGNAL_GOOD: return isLock ? KWifi6PlusLockGood : KWifi6PlusGood; case SIGNAL_OK: return isLock ? KWifi6PlusLockOK : KWifi6PlusOK; case SIGNAL_LOW: return isLock ? KWifi6PlusLockLow : KWifi6PlusLow; case SIGNAL_NONE: return isLock ? KWifi6PlusLockNone : KWifi6PlusNone; default: return ""; } } } QString KnmWlanDataKeeper::getWiFiIcon(QString signalStrength, QString security, QString isApConnection, int category) { qDebug() << "sig: " << signalStrength << " sec: " << security << " isAp: " << isApConnection << " cat: " << category; int sign = setSignal(signalStrength); bool isLock = true; if (security.isEmpty()) { isLock = false; } else { isLock = true; } QString iconamePath; if (isApConnection == IsApConnection) { iconamePath = KApSymbolic; } else { iconamePath = getWiFiIconString(isLock, sign, category); } return iconamePath; } void KnmWlanDataKeeper::addDevConnection(QString devName, QList conPath) { qDebug() << Q_FUNC_INFO << __LINE__ << "devName:" << devName << "conPath:" << conPath; if (conPath.isEmpty()) return; NetDevicePtr dev = m_deviceList.take(devName); if (!conPath.at(0).contains("--")) { dev->addConnection(makeConnectionMap(ACTIVATED, conPath.at(0))); m_connected = true; } conPath.takeAt(0); for (int i = 0; i < conPath.count(); i++) { dev->addConnection(makeConnectionMap(DEACTIVATED, conPath.at(i))); } m_deviceList.insert(devName, dev); } /*连接状态变化全量更新*/ void KnmWlanDataKeeper::onActiveConnectionChanged(QString deviceName, QString ssid, QString uuid, int status) { qDebug() << Q_FUNC_INFO << __LINE__ << "deviceName:" << deviceName << "ssid:" << ssid << "uuid:" << uuid << "status:" << status; QMapvalueMap; if (!m_switchState) return; if (uuid.isEmpty()) return; if (status == ACTIVATED || status == ACTIVATING) { if (!m_deviceList.contains(deviceName)) return; if(m_deviceList.value(deviceName)->containsConnectionName(ssid)) { NetDevicePtr dev = m_deviceList.value(deviceName); QMap conn = dev->getConnectionByName(ssid); dev->removeConnection(conn); if (conn.contains("Uuid")) conn.remove("Uuid"); conn.insert("Uuid", uuid); conn.remove("State"); conn.insert("State", status); if(status == ACTIVATED) { conn["Configured"]=1; } dev->addConnection(conn); } KInterface::getInstance()->rebuildCurrentWirelessList(); return; } QStringList devList = m_deviceList.keys(); for (int i = 0; i < devList.count(); i++) { QVariantList connList = m_deviceList.value(devList.at(i))->getConnections(); if(connList.isEmpty()) { qDebug() << Q_FUNC_INFO << __LINE__ << "deviceName:" << devList.at(i); continue; } valueMap=connList.at(0).toMap(); if (!valueMap.contains("Uuid")) continue; if (valueMap.value("Uuid").toString() != uuid) continue; NetDevicePtr dev = m_deviceList.value(devList.at(i)); QMap conn = dev->updateConnection(uuid, status); qDebug() << Q_FUNC_INFO << __LINE__ << "deviceName:" << dev->devName() << "ssid:" << conn["Name"] << "uuid:" << conn["Uuid"] << "status:" << status; if (status == DEACTIVATED) { /*临时规避方案这里可能存在dbus调用阻塞,待正向把老kylin-nm数据同步问题解决后解*/ KNMDC::getInstance()->updateWirelessConListSync(dev->devName()); } } KInterface::getInstance()->rebuildCurrentWirelessList(); return; } void KnmWlanDataKeeper::onNetworkAdd(QString deviceName, QStringList wlanInfo) { qDebug() << Q_FUNC_INFO << __LINE__ << deviceName << wlanInfo; if (!m_switchState || deviceName.isEmpty()) return; if (!m_deviceList.contains(deviceName)) return; qDebug() << deviceName << wlanInfo << wlanInfo.count(); NetDevicePtr dev = m_deviceList.value(deviceName); /*根据后端链表每个项添加的参数来的,改了后端需要改这里,只有6项表示未连接,7项表示已连接;后面需要优化可一样的项数通过赋特定空值区分,不然维护,容易改漏且容易歧义*/ if (wlanInfo.count() == 8) dev->addConnection(makeConnectionMap(DEACTIVATED, wlanInfo)); if (wlanInfo.count() == 9) dev->addConnection(makeConnectionMap(ACTIVATED, wlanInfo)); KInterface::getInstance()->getWirelessDevConnList(); } void KnmWlanDataKeeper::onNetworkRemove(QString deviceName, QString wlanName) { if (deviceName.isEmpty()) return; if (!m_deviceList.contains(deviceName)) return; NetDevicePtr dev = m_deviceList.value(deviceName); if(dev.isNull()) { qWarning() << Q_FUNC_INFO << __LINE__ << deviceName << "no device"; return; } dev->removeConnectionByName(wlanName); KInterface::getInstance()->getWirelessDevConnList(); } void KnmWlanDataKeeper::onDeviceNameChanged(QString oldName, QString newName, int type) { if (type != WIRELESS_DEVICE) return; if (!m_deviceList.contains(oldName)) return; if (m_deviceList.keys().contains(newName)) return; emit onDeviceStatusChanged(); } void KnmWlanDataKeeper::onSwitchBtnChanged(bool status) { m_switchState = status; KInterface::getInstance()->updateWirelessSwitch(); } //对部分QML功能有影响,待完善 void KnmWlanDataKeeper::updateList() { if (!m_switchState) return; // emit onDeviceStatusChanged(); } kylin-nm/qml-network/plugin/knmlandatakeeper.h0000775000175000017500000000242415167651420020507 0ustar fengfeng#ifndef KNMLANDATAKEEPER_H #define KNMLANDATAKEEPER_H #include #include "knmdatakeeper.h" class KnmLanDataKeeper; typedef QSharedPointer KnmLanDataKeeperPtr; class KnmLanDataKeeper : public KnmDataKeeper { Q_OBJECT public: explicit KnmLanDataKeeper(QObject *parent = nullptr); ~KnmLanDataKeeper(); //添加网卡设备的连接 void addDevConnection(QString devName, QList conPath); signals: void onDeviceStatusChanged(); private: QMap makeConnectionMap(int status, QStringList conPath); bool isDslConnection(const QString &uuid); private slots: //已激活连接状态更新 void onActiveConnectionChanged(QString deviceName, QString uuid, int status); //新增连接 void onLanAdd(QString deviceName, QStringList lanInfo); //删除连接 void onLanRemove(QString path); //连接更新属性(名称)或更改从属网卡设备 void updateLanInfo(QString deviceName, QStringList lanInfo); //更新网卡设备名称 void onDeviceNameChanged(QString oldName, QString newName, int type); //更新 开关状态 void onSwitchBtnChanged(bool status); private: QDBusInterface *m_pInterface = nullptr; }; #endif // KNMLANDATAKEEPER_H kylin-nm/qml-network/plugin/wirelessconnectionmodel.h0000664000175000017500000000560415167651420022137 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #pragma once #include #include #include class WirelessConnectionModel : public QAbstractListModel { Q_OBJECT //Q_PROPERTY(WirelessConnectionModel wirelessConList READ wirelessConList NOTIFY updateWirelessDevConnList) public: enum Roles { SSIDRole = Qt::UserRole + 1, StrengthRole, SecurityTypeRole, UUIDRole, IsAPRole, CategoryRole, ConnectStatusRole, IsLoadingRole, ConfiguredRole, FrequencyRole, IsMixRole, }; struct ST_ConnectionInfo { QString ssid; // 网络名称 QString signal; // 信号强度 QString security; // 安全类型 QString uuid; // 网络名称 QString isApConn; uint category; uint frequency; // int status; // bool Loading; int Configured; bool isMix; }; explicit WirelessConnectionModel(QObject *parent = nullptr); ST_ConnectionInfo mapToConnectionInfo(QMap value); // QAbstractListModel 接口 int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; QHash roleNames() const override; public slots: // 添加连接项 void addConnection(struct ST_ConnectionInfo *pConnection); // 移除连接项 void removeConnection(const QString &connectionId); // 更新连接属性 void updateConnectionStrength(const QString &connectionId, int newStrength); void updateConnectionStatus(const QString &connectionId, int status); // 批量添加/更新 void refreshConnections(const QVariantList newList); private: /*makeConnectionMap*/ int findIndexById(const QString &id) const; QString generateUniqueId() const; QVector m_connections; }; kylin-nm/qml-network/plugin/qmldir0000664000175000017500000000007615167651420016241 0ustar fengfengmodule org.ukui.shortcut.network plugin ukui-shortcut-network kylin-nm/qml-network/plugin/wirelessconnectionmodel.cpp0000664000175000017500000001573115167651420022474 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "wirelessconnectionmodel.h" #include #include #include WirelessConnectionModel::WirelessConnectionModel(QObject *parent) : QAbstractListModel(parent) { } int WirelessConnectionModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return m_connections.size(); } QVariant WirelessConnectionModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= m_connections.size()) return QVariant(); const ST_ConnectionInfo &connection = m_connections.at(index.row()); switch (role) { case SSIDRole: return connection.ssid; case StrengthRole: return connection.signal; case ConnectStatusRole: return connection.status; case SecurityTypeRole: return connection.security; case CategoryRole: return connection.category; case IsAPRole: return connection.isApConn; case UUIDRole: return connection.uuid; case IsLoadingRole: return connection.Loading; case ConfiguredRole: return connection.Configured; case FrequencyRole: return connection.frequency; case IsMixRole: return connection.isMix; default: return QVariant(); } } bool WirelessConnectionModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid() || index.row() >= m_connections.size()) return false; ST_ConnectionInfo &connection = m_connections[index.row()]; switch (role) { case SSIDRole: connection.ssid = value.toString(); break; case StrengthRole: connection.signal = value.toString(); break; case IsAPRole: connection.isApConn = value.toString(); break; case SecurityTypeRole: connection.security = value.toString(); break; case UUIDRole: connection.uuid = value.toString(); break; case CategoryRole: connection.category = value.toUInt(); break; case ConnectStatusRole: connection.status = value.toInt(); break; case IsLoadingRole: connection.Loading = value.toBool(); break; case ConfiguredRole: connection.Configured = value.toBool(); break; case FrequencyRole: connection.frequency = value.toUInt(); break; case IsMixRole: connection.isMix = value.toBool(); break; default: return false; } emit dataChanged(index, index, {role}); return true; } QHash WirelessConnectionModel::roleNames() const { return { {SSIDRole, "ssid"}, {StrengthRole, "signal"}, {SecurityTypeRole, "security"}, {UUIDRole, "uuid"}, {IsAPRole, "isApConn"}, {CategoryRole, "category"}, {ConnectStatusRole,"status"}, {IsLoadingRole,"Loading"}, {ConfiguredRole,"Configured"}, {FrequencyRole, "frequency"}, {IsMixRole, "isMix"} }; } void WirelessConnectionModel::addConnection(struct ST_ConnectionInfo *pConnection) { // 确保ID唯一性 QString id = generateUniqueId(); // if(pConnection->status==1 || pConnection->status == 2) { beginInsertRows(QModelIndex(), 0, 0); m_connections.push_front(*pConnection); endInsertRows(); } else { beginInsertRows(QModelIndex(), rowCount(), rowCount()); m_connections.append(*pConnection); endInsertRows(); } qDebug() << "Added connection:" << pConnection->ssid << "(" << pConnection->uuid << ")"; } void WirelessConnectionModel::removeConnection(const QString &connectionId) { int index = findIndexById(connectionId); if (index != -1) { beginRemoveRows(QModelIndex(), index, index); m_connections.remove(index); endRemoveRows(); qDebug() << "Removed connection:" << connectionId; } } void WirelessConnectionModel::updateConnectionStrength(const QString &connectionId, int newStrength) { int index = findIndexById(connectionId); if (index != -1) { m_connections[index].signal = QString::number(newStrength); QModelIndex modelIndex = createIndex(index, 0); emit dataChanged(modelIndex, modelIndex, {StrengthRole}); } } void WirelessConnectionModel::updateConnectionStatus(const QString &connectionId, int status) { int index = findIndexById(connectionId); if (index != -1) { m_connections[index].status = status; QModelIndex modelIndex = createIndex(index, 0); emit dataChanged(modelIndex, modelIndex, {ConnectStatusRole}); } } WirelessConnectionModel::ST_ConnectionInfo WirelessConnectionModel::mapToConnectionInfo(QMap value) { ST_ConnectionInfo connect; connect.ssid=value.value("Name").toString(); connect.signal=value.value("Signal").toString(); connect.security=value.value("Security").toString(); connect.uuid=value.value("Uuid").toString(); connect.isApConn=value.value("isApConn").toString(); connect.category=value.value("category").toUInt(); connect.frequency=value.value("frequency").toUInt(); connect.status=value.value("State").toInt(); connect.Loading=value.value("Loading").toBool(); connect.Configured=value.value("Configured").toInt(); connect.isMix=value.value("isMix").toBool(); return connect; } void WirelessConnectionModel::refreshConnections(const QVariantList newList) { m_connections.clear(); beginResetModel(); for(int i=0;igenerate() % 10000); } kylin-nm/qml-network/plugin/knminterface.h0000775000175000017500000001150115167651420017643 0ustar fengfeng#ifndef KNMINTERFACE_H #define KNMINTERFACE_H #include #include #include #include #include #include #include #include #include "CSingleton.h" #include "wirelessconnectionmodel.h" enum ConnectStatus{ All, // 有线无线都连接 Wire, // 仅有有线连接 Wireless, // 仅有无线连接 NoConnect // 都没连接 }; //前端接口类,用于调取keeper数据并展示在前端 class KnmInterface : public QObject { Q_OBJECT Q_PROPERTY(QVariantList wiredDevList READ wiredDeviceList NOTIFY updateWiredDeviceList) Q_PROPERTY(QVariantList wirelessDevList READ wirelessDeviceList NOTIFY updateWirelessDeviceList) Q_PROPERTY(QVariantList wiredConList READ wiredDevConnList NOTIFY updateWiredDevConnList) Q_PROPERTY(QVariantList wirelessConList READ wirelessDevConnList NOTIFY updateWirelessDevConnList) Q_PROPERTY(bool wirelessSwitch READ wirelessSwitchState WRITE setWirelessSwitch NOTIFY updateWirelessSwitch) Q_PROPERTY(bool wiredMainSwitch READ wiredMainSwitchState WRITE setWiredMainSwitch NOTIFY updateWiredMainSwitch) Q_PROPERTY(QString upwareRate READ upwareRateDate WRITE setUpwareRateData NOTIFY updateUpLoadWiredStr) Q_PROPERTY(QString downwareRate READ downwareRateDate WRITE setDownwareRateData NOTIFY updateDownLoadWiredStr) Q_PROPERTY(WirelessConnectionModel* wirelessConLists READ wirelessConLists NOTIFY wirelessConListChanged) Q_PROPERTY(bool cableStatus READ getCableStatus NOTIFY updateCable) Q_PROPERTY(QString fontSize READ fontSize NOTIFY fontSizeChanged) public: KnmInterface(); WirelessConnectionModel* wirelessConLists() { return &mWirelessConnecModel; } ~KnmInterface(); public slots: QVariantList wiredDeviceList(); QVariantList wirelessDeviceList(); QVariantList wiredDevConnList(); QVariantList wirelessDevConnList(); bool wirelessSwitchState(); bool wiredMainSwitchState(); QVariant getLoadingIcon(); void setWiredMainSwitch(bool switched); void setWirelessSwitch(bool switched); void setUpwareRateData(QString str); void setDownwareRateData(QString str); void rescanWirelessConn(); void openNetworkSetting(); void openwLanNetworkSetting(); //用于切换网卡设备时显示的连接列表更新 void getWiredDevConnList(QString devName); void getWiredDevConnList(); void getWirelessDevConnList(QString devName); void getWirelessDevConnList(); void rebuildCurrentWirelessList(); QString getIconData(QString name, int size = 16); void activateConnect(QString devName, QString conUid, int type); void deActivateConnect(QString devName, QString conUid, int type); void passwordConnect(QString devName, QString ssid, QString type, QString psk, bool autoConnect); QVariant getWiFiIcon(QString signalStrength, QString security, QString isApConnection, int category); QString upwareRateDate(); QString downwareRateDate(); bool getNetMacConnectStatus(QString devmac); void showPropertyWidget(QString devname, QString ssid); void deleteConnect(int type,QString ssid); void showAddOtherWlanPage(QString devName); private slots: void slotRefreshTimeout(); public: ConnectStatus getConnectionStatus(); bool getCableStatusByDev(const QString &devName); bool getCableStatus(); QString fontSize(); signals: void updateWiredDeviceList(); void updateWirelessDeviceList(); void updateWiredDevConnList(); void updateWirelessDevConnList(); void updateWiredMainSwitch(); void updateWirelessSwitch(); void updateLoadingIcon(QVariant icon); void updateUpLoadWiredStr(QString str); void updateUpLoadWirelessStr(QString str); void updateDownLoadWiredStr(QString str); void updateDownLoadWirelessStr(QString str); void wirelessConListChanged(); void updateCable(bool status); void fontSizeChanged(QString fontSize); private: QVariantList m_wiredDevConnList; QVariantList m_wirelessDevConnList; QString m_currentWiredDevice; QString m_currentWirelessDevice; int loadCount = 0; QTimer *loadTimer = nullptr; QTimer *m_pRefreshTimer = nullptr; QProcess * m_pProcess = nullptr; WirelessConnectionModel mWirelessConnecModel;//显示模型使用QAbstractListModel 可控制显示区域与数据变化。基于object的qvariantlist数据变化或项变化都会引起界面的全量更新 friend class SingleTon; QString m_fontSize; class QGSettings *m_fontSettings = nullptr; }; typedef SingleTon KInterface; #endif // KNMINTERFACE_H kylin-nm/qml-network/plugin/CSingleton.h0000664000175000017500000000260315167651420017242 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * **/ #ifndef CSINGLETON_H #define CSINGLETON_H template class SingleTon { public: // 创建单例实例 template static T* instance(Args&&... args) { if (m_pInstance == nullptr) { m_pInstance = new T(std::forward(args)...); } return m_pInstance; } // 获取单例 static T* getInstance() { return m_pInstance; } // 删除单例 static void destroyInstance() { delete m_pInstance; m_pInstance = nullptr; } private: SingleTon(); virtual ~SingleTon(); private: static T* m_pInstance; }; template T* SingleTon::m_pInstance = nullptr; #endif kylin-nm/qml-network/plugin/knmlandatakeeper.cpp0000775000175000017500000002510015167651420021036 0ustar fengfeng#include "knmlandatakeeper.h" #include "knminterface.h" KnmLanDataKeeper::KnmLanDataKeeper(QObject *parent) : KnmDataKeeper(parent) { m_pInterface = new QDBusInterface("com.kylin.network", "/com/kylin/network", "com.kylin.network", QDBusConnection::sessionBus()); if(!m_pInterface->isValid()) { qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } qDBusRegisterMetaType>(); // 有线网络断开或连接时刷新可用网络列表 connect(m_pInterface, SIGNAL(lanActiveConnectionStateChanged(QString, QString, int)), this, SLOT(onActiveConnectionChanged(QString, QString, int)), Qt::QueuedConnection); //有线网络新增时添加网络 connect(m_pInterface, SIGNAL(lanAdd(QString, QStringList)), this, SLOT(onLanAdd(QString, QStringList)), Qt::QueuedConnection); //删除有线网络 connect(m_pInterface, SIGNAL(lanRemove(QString)), this, SLOT(onLanRemove(QString)), Qt::QueuedConnection); //更新有线网络 connect(m_pInterface, SIGNAL(lanUpdate(QString, QStringList)), this, SLOT(updateLanInfo(QString, QStringList)),Qt::QueuedConnection); //网卡插拔处理,此信号处理需要优化 connect(m_pInterface, SIGNAL(deviceStatusChanged()), this, SIGNAL(onDeviceStatusChanged()),Qt::QueuedConnection); //网卡name处理 connect(m_pInterface, SIGNAL(deviceNameChanged(QString, QString, int)), this, SLOT(onDeviceNameChanged(QString, QString, int)),Qt::QueuedConnection); connect(m_pInterface, SIGNAL(wiredMainSwitchBtnChanged(bool)), this, SLOT(onSwitchBtnChanged(bool)), Qt::QueuedConnection); netSpeedInit(); } KnmLanDataKeeper::~KnmLanDataKeeper() { if (nullptr != m_pInterface) { delete m_pInterface; m_pInterface = nullptr; } } QMap KnmLanDataKeeper::makeConnectionMap(int status, QStringList conPath) { QMap connectionMap; connectionMap.insert("Name", conPath.at(0)); connectionMap.insert("Uuid", conPath.at(1)); connectionMap.insert("Path", conPath.at(2)); connectionMap.insert("State", status); connectionMap.insert("Loading", false); // Add DSL detection logic bool isDSL = false; if (isDslConnection(conPath.at(1))) { isDSL = true; } connectionMap.insert("IsDSL", isDSL); // 默认设置为完全连通 connectionMap.insert("Connectivity", 4); return connectionMap; } void KnmLanDataKeeper::addDevConnection(QString devName, QList conPath) { if (conPath.isEmpty()) return; if (!m_deviceList.contains(devName)) return; NetDevicePtr dev =m_deviceList.take(devName); //列表首个连接为空或为已激活的连接,单独处理 if (!conPath.at(0).contains("--")) { dev->addConnection(makeConnectionMap(ACTIVATED, conPath.at(0))); m_connected = true; } //单独处理后抛出 conPath.takeAt(0); //剩下的为已保存的未激活连接 for (int i = 0; i < conPath.count(); i++) { dev->addConnection(makeConnectionMap(DEACTIVATED, conPath.at(i))); } m_deviceList.insert(devName, dev); } void KnmLanDataKeeper::onActiveConnectionChanged(QString deviceName, QString uuid, int status) { if (uuid.isEmpty()) return; if (deviceName.isEmpty() && status != DEACTIVATED) return; // 获取设备连通性状态 int connectivity = 4; // 默认为完全连通 if (status == ACTIVATED) { QDBusReply reply = m_pInterface->call(QStringLiteral("getDeviceConnectivity"), deviceName); if (reply.isValid()) { connectivity = reply.value(); qDebug() << "Device connectivity:" << deviceName << connectivity; } } // 断开时处理 if (deviceName.isEmpty()) { QMap conn; QStringList devList = m_deviceList.keys(); for (int i = 0; i < devList.count(); i++) { NetDevicePtr dev = m_deviceList.value(devList.at(i)); QMap conn = dev->updateConnection(uuid, status); dev->updateConnectivity(uuid, status, connectivity); if (!conn.isEmpty()) { m_deviceList.remove(devList.at(i)); m_deviceList.insert(devList.at(i), dev); break; } } for (int i = 0; i < devList.count(); i++) { NetDevicePtr dev = m_deviceList.take(devList.at(i)); dev->addConnection(conn); m_deviceList.insert(devList.at(i), dev); } KInterface::getInstance()->getWiredDevConnList(); return; } //若已指定设备且存在该连接时 if (m_deviceList.contains(deviceName)) { if (!m_deviceList.value(deviceName)->containsConnection(uuid)) return; NetDevicePtr dev = m_deviceList.value(deviceName); QMap conn = dev->updateConnection(uuid, status); dev->updateConnectivity(uuid, status, connectivity); if (!conn.isEmpty()) { m_deviceList.remove(deviceName); m_deviceList.insert(deviceName, dev); KInterface::getInstance()->getWiredDevConnList(); } return; } //若非以上情况,则为虚拟网卡 if (status != ACTIVATED && status != DEACTIVATED) return; if (!m_deviceList.value(deviceName)->containsConnection(uuid)) { return; } NetDevicePtr dev = m_deviceList.take(deviceName); dev->removeConnection(uuid); m_deviceList.insert(deviceName, dev); KInterface::getInstance()->getWiredDevConnList(); } void KnmLanDataKeeper::onLanAdd(QString deviceName, QStringList lanInfo) { if (!deviceName.isEmpty() && !m_deviceList.contains(deviceName)) return; //设备名为空时,表示该连接不从属任何设备,所有设备需要添加该连接 if (deviceName.isEmpty()) { QStringList devList = m_deviceList.keys(); for (int i = 0; i < devList.count(); i++) { NetDevicePtr dev = m_deviceList.take(devList.at(i)); dev->addConnection(makeConnectionMap(DEACTIVATED, lanInfo)); m_deviceList.insert(devList.at(i), dev); } KInterface::getInstance()->getWiredDevConnList(); return; } //设备名不为空,即该连接从属于某设备,更新该设备连接的属性即可 NetDevicePtr dev = m_deviceList.take(deviceName); dev->addConnection(makeConnectionMap(DEACTIVATED, lanInfo)); m_deviceList.insert(deviceName, dev); KInterface::getInstance()->getWiredDevConnList(); } void KnmLanDataKeeper::onLanRemove(QString path) { QStringList devList = m_deviceList.keys(); for (int i = 0; i < devList.count(); i++) { //所有网卡设备均删除该连接 if (m_deviceList.value(devList.at(i))->containsConnection(path)) { NetDevicePtr dev = m_deviceList.take(devList.at(i)); dev->removeConnection(path); m_deviceList.insert(devList.at(i), dev); } } KInterface::getInstance()->getWiredDevConnList(); } void KnmLanDataKeeper::updateLanInfo(QString deviceName, QStringList lanInfo) { qDebug() << "dddname: " << deviceName << " info:" << lanInfo; QStringList devList = m_deviceList.keys(); if (deviceName.isEmpty()) { for (int i = 0; i < devList.count(); i++) { //连接不属于任何设备,任何设备均需要添加该连接 if (!m_deviceList.value(devList.at(i))->containsConnection(lanInfo.at(1))) { NetDevicePtr dev = m_deviceList.take(devList.at(i)); dev->addConnection(makeConnectionMap(DEACTIVATED, lanInfo)); m_deviceList.insert(devList.at(i), dev); continue; } //连接不属于任何设备,且修改属性 NetDevicePtr dev = m_deviceList.take(devList.at(i)); int status = DEACTIVATED; QMapvalueMap=dev->getConnections().at(0).toMap(); if(valueMap.value("State").toInt() && valueMap.value("Uuid").toString() == lanInfo.at(1)) { status = lanInfo.at(4).toInt(); } dev->removeConnection(lanInfo.at(2)); dev->addConnection(makeConnectionMap(status, lanInfo)); m_deviceList.insert(devList.at(i), dev); } KInterface::getInstance()->getWiredDevConnList(); return; } for (int i = 0; i < devList.count(); i++) { //连接被修改为不属于列表第i个设备,故而删除 if (devList.at(i) != deviceName) { NetDevicePtr dev = m_deviceList.take(devList.at(i)); dev->removeConnection(lanInfo.at(2)); m_deviceList.insert(devList.at(i), dev); continue; } //连接被修改为属于列表第i个设备,故而新增 if(!m_deviceList.value(devList.at(i))->containsConnection(lanInfo.at(1))){ NetDevicePtr dev = m_deviceList.take(devList.at(i)); dev->addConnection(makeConnectionMap(DEACTIVATED, lanInfo)); m_deviceList.insert(devList.at(i), dev); continue; } //连接被修改了名称 NetDevicePtr dev = m_deviceList.take(devList.at(i)); int status = DEACTIVATED; QMapvalueMap=dev->getConnections().at(0).toMap(); if(valueMap.value("State").toInt() && valueMap.value("Uuid").toString() == lanInfo.at(1)) { status = lanInfo.at(4).toInt(); } dev->removeConnection(lanInfo.at(2)); dev->addConnection(makeConnectionMap(status, lanInfo)); m_deviceList.insert(devList.at(i), dev); } KInterface::getInstance()->getWiredDevConnList(); } void KnmLanDataKeeper::onDeviceNameChanged(QString oldName, QString newName, int type) { if (type != WIRED_DEVICE) return; if (!m_deviceList.contains(oldName)) return; if (m_deviceList.keys().contains(newName)) return; emit onDeviceStatusChanged(); } void KnmLanDataKeeper::onSwitchBtnChanged(bool status) { m_wiredMainSwitchState = status; m_switchState = status; KInterface::getInstance()->updateWiredMainSwitch(); } bool KnmLanDataKeeper::isDslConnection(const QString &uuid) { QProcess process; process.start("nmcli", {"-g", "connection.type", "con", "show", uuid}); process.waitForFinished(); QString output = process.readAllStandardOutput().trimmed(); return (output == "pppoe"); // 如果是pppoe类型则返回true } kylin-nm/qml-network/plugin/knmdatakeeper.cpp0000775000175000017500000001620515167651420020351 0ustar fengfeng#include "knmdatakeeper.h" #include "knminterface.h" KnmDataKeeper::KnmDataKeeper(QObject *parent) : QObject{parent} { } KnmDataKeeper::~KnmDataKeeper() { if (nullptr != m_pSpeedTimer) { delete m_pSpeedTimer; m_pSpeedTimer = nullptr; } } void KnmDataKeeper::addDevice(QString devName, bool isAvailable, DeviceType type) { if (!isAvailable) return; NetDevicePtr dev(new NetDevice(devName, type)); dev->setAvailable(isAvailable); m_deviceList.insert(devName, dev); } void KnmDataKeeper::clearDevice() { m_deviceList.clear(); } QMap KnmDataKeeper::getDeviceList() { return m_deviceList; } bool KnmDataKeeper::getWiredMainSwitchState() { return m_wiredMainSwitchState; } void KnmDataKeeper::setWiredMainSwitchState(bool switched) { qWarning()<< Q_FUNC_INFO <<__LINE__ << switched; m_wiredMainSwitchState = switched; } bool KnmDataKeeper::getSwitchState() { return m_switchState; } void KnmDataKeeper::setSwitchState(bool switched) { m_switchState = switched; } QVariantList KnmDataKeeper::getDevConnections(QString devName) { QVariantList ret; if (m_deviceList.isEmpty() || !m_deviceList.contains(devName)) return ret; m_currentDev = devName; // m_pSpeedTimer->start(); NetDevicePtr dev = m_deviceList.value(devName); if(dev.isNull()) { qWarning() << Q_FUNC_INFO << __LINE__ << devName << "no device"; return ret; } return m_deviceList.value(devName)->getConnections(); } void KnmDataKeeper::clearConnectionList(QString devName) { if (!m_deviceList.contains(devName)) return; NetDevicePtr dev = m_deviceList.take(devName); dev->clearConnections(); m_deviceList.insert(devName, dev); } int KnmDataKeeper::getCurrentLoadRate(QString dev, long *save_rate, long *tx_rate) { FILE * net_dev_file; //文件指针 char buffer[1024]; //文件中的内容暂存在字符缓冲区里 //size_t bytes_read; //实际读取的内容大小 char * match; //用以保存所匹配字符串及之后的内容 char * device;//将QString转为Char * QByteArray ba = dev.toLatin1(); // must device = ba.data(); int counter = 0; //int i = 0; char tmp_value[128]; if ((NULL == device) || (NULL == save_rate) || (NULL == tx_rate)) { qDebug() << "parameter pass error" ; return -1; } if ((net_dev_file = fopen("/proc/net/dev", "r")) == NULL) { //打开文件/pro/net/dev/,从中读取流量数据 qDebug() << "error occurred when try to open file /proc/net/dev/"; return -1; } memset(buffer, 0, sizeof(buffer)); while (fgets(buffer, sizeof(buffer), net_dev_file) != NULL) { match = strstr(buffer, device); if (NULL == match) { // qDebug()<<"No eth0 keyword to find!"; continue; } else { match = match + qstrlen(device) + qstrlen(":"); //地址偏移到冒号 sscanf(match, "%ld ", save_rate); memset(tmp_value, 0, sizeof(tmp_value)); sscanf(match, "%s ", tmp_value); match = match + qstrlen(tmp_value); for (size_t i=0; igetDevType()==WIRED_DEVICE) { emit KInterface::getInstance()->updateUpLoadWiredStr(upLoad); emit KInterface::getInstance()->updateDownLoadWiredStr(downLoad); } else { emit KInterface::getInstance()->updateUpLoadWirelessStr(upLoad); emit KInterface::getInstance()->updateDownLoadWirelessStr(downLoad); } } void KnmDataKeeper::netSpeedInit() { //定时获取网速 m_pSpeedTimer = new QTimer(this); m_pSpeedTimer->setTimerType(Qt::PreciseTimer); m_pSpeedTimer->start(1000); connect(m_pSpeedTimer, &QTimer::timeout, this,&KnmDataKeeper::slotSpeedTimeout); // //定时获取网速 // m_pSpeedTimer = new QTimer(this); // m_pSpeedTimer = new QTimer(this); // m_pSpeedTimer->setInterval(500); // m_pSpeedTimer->setInterval(500); // connect(m_pSpeedTimer, &QTimer::timeout, [&]() { // QString upLoad, downLoad; // netSpeedHandler(m_currentDev, upLoad, downLoad); // KInterface::getInstance()->updateUpLoadWiredStr(upLoad); // KInterface::getInstance()->updateDownLoadWiredStr(downLoad); // }); // connect(m_pSpeedTimer, &QTimer::timeout, [&]() { // QString upLoad, downLoad; // netSpeedHandler(m_currentDev, upLoad, downLoad); // KInterface::getInstance()->updateUpLoadWirelessStr(upLoad); // KInterface::getInstance()->updateDownLoadWirelessStr(downLoad); // }); } void KnmDataKeeper::setUpwardRate(QString str) { m_upward_rate = str; } QString KnmDataKeeper::getUpwardRate() { return m_upward_rate; } void KnmDataKeeper::setDownwardRate(QString str) { m_downward_rate = str; } QString KnmDataKeeper::getDownwardRate() { return m_downward_rate; } kylin-nm/qml-network/plugin/knmdbuscaller.h0000664000175000017500000000634415167651420020031 0ustar fengfeng#ifndef KNMDBUSCALLER_H #define KNMDBUSCALLER_H #include #include #include #include #include #include #include #include "knmlandatakeeper.h" #include "knmwlandatakeeper.h" #include "CSingleton.h" //dbus调用类 class KnmDBusCaller : public QObject { Q_OBJECT protected: explicit KnmDBusCaller(QObject *parent = nullptr); ~KnmDBusCaller(void); //用于interface调用数据 public: QMap wiredDeviceList(); QMap wirelessDeviceList(); QVariantList wiredDeviceConnList(QString devName); QVariantList wirelessDeviceConnList(QString devName); QString getWiFiIcon(QString signalStrength, QString security, QString isApConnection, int category); bool wirelessSwitchState(); bool wiredMainSwitchState(); QString upwardRateDate(); QString downwardRateDate(); void rescanWirelessConn(); void activateConnect(QString devName, QString conUid, int type); void deActivateConnect(QString devName, QString conUid, int type); void setWirelessSwitchEnable(bool enable); void passwordConnect(QString devName, QString ssid, QString type, QString psk, bool autoConnect); void setWiredMainSwitchEnable(bool enable); void setUpwareRateData(QString str); void setDownwareRateData(QString str); void showPropertyWidget(QString devName, QString ssid); void deleteConnect(int type, QString ssid); void showAddOtherWlanPage(QString devName); void getWirelessConList(QString dev); void updateWirelessConListSync(QString dev); void getCableStateByDevice(const QString &dev); //用于调用kylin-nm的dbus protected: QDBusPendingCallWatcher * asyncCall(const QString & methed, const QList & params); void getWiredDeviceMap(); void getWirelessDeviceMap(); void getWiredConList(QString dev); void getWirelessSwitchState(); void getWiredMainSwitchState(); void getWiredConListFinished(QDBusPendingCallWatcher *watcher, QString dev); void getWirelessConListFinished(QDBusPendingCallWatcher *watcher, QString dev); //dbus调用的响应槽函数 protected slots: void updateWiredDeviceMap(); void updateWirelessDeviceMap(); void updateWirelessDevice(); void updateWiredDeviceMapFinished(QDBusPendingCallWatcher *watcher); void updateWirelessDeviceMapFinished(QDBusPendingCallWatcher *watcher); void setWirelessSwitchEnableFinished(QDBusPendingCallWatcher *watcher); void getWiredDeviceMapFinished(QDBusPendingCallWatcher *watcher); void getWirelessDeviceMapFinished(QDBusPendingCallWatcher *watcher); void getWirelessSwitchStateFinished(QDBusPendingCallWatcher *watcher); void getWiredMainSwitchStateFinished(QDBusPendingCallWatcher *watcher); void setWiredMainSwitchEnableFinished(QDBusPendingCallWatcher *watcher); void updateCableState(QDBusPendingCallWatcher *watcher); protected: QDBusInterface *m_pInterface = nullptr; private: int m_pendingCount = 0; KnmLanDataKeeperPtr lanDataKeeper; KnmWlanDataKeeperPtr wlanDataKeeper; protected: friend class SingleTon; }; typedef SingleTon KNMDC; #endif // KNMDBUSCALLER_H kylin-nm/qml-network/plugin/knminterface.cpp0000775000175000017500000003036015167651420020202 0ustar fengfeng#include "knminterface.h" #include "knmdbuscaller.h" #include KnmInterface::KnmInterface() { KNMDC::instance(this); loadTimer = new QTimer(this); loadTimer->setInterval(100); connect(loadTimer, &QTimer::timeout, this, [=]() { QString icon = getIconData("ukui-loading-" + QString::number(loadCount) + "-symbolic"); loadCount += 1; if (loadCount == 8) loadCount = 0; emit updateLoadingIcon(QVariant(icon)); }); m_pRefreshTimer = new QTimer(this); m_pRefreshTimer->start(20000); connect(m_pRefreshTimer, &QTimer::timeout, this,&KnmInterface::slotRefreshTimeout); // init font settings from org.ukui.style if (QGSettings::isSchemaInstalled("org.ukui.style")) { m_fontSettings = new QGSettings("org.ukui.style", QByteArray(), this); QVariant val = m_fontSettings->get("systemFontSize"); if (val.isValid()) { m_fontSize = val.toString(); emit fontSizeChanged(m_fontSize); } connect(m_fontSettings, &QGSettings::changed, this, [this](const QString &key) { if (key == "systemFontSize") { QString fontSize = m_fontSettings->get(key).toString(); if (m_fontSize != fontSize) { m_fontSize = fontSize; emit fontSizeChanged(m_fontSize); } } }); } } KnmInterface::~KnmInterface() { if (nullptr != loadTimer) { delete loadTimer ; loadTimer = nullptr; } } QString KnmInterface::getIconData(QString name, int size /*= 24*/) { QIcon icon =QIcon::fromTheme(name); QPixmap pixmap = icon.pixmap(size, size); QByteArray data; QBuffer buffer(&data); buffer.open(QIODevice::WriteOnly); pixmap.save(&buffer, "PNG"); return "data:image/png;base64," + data.toBase64(); } //这里是返回给qml连接信息 //fixbug 377873,已经连接的网卡需要在第一个显示 //遍历连接列表,将已经连接的网卡swap到第0个位置 QVariantList KnmInterface::wiredDeviceList() { QVariantList list; auto dev = KNMDC::getInstance()->wiredDeviceList(); // fixbug=377873 已经连接的网卡需要在第一个显示 int connect_id = -1; for (auto iter : dev) { if (!iter.isNull()) { if (connect_id == -1) { for (auto devices : iter->getConnections()) { int status = devices.toMap().value("State").toInt(); if (2 == status) { //2==已连接 connect_id = list.size(); break; } } } list.append(iter->devName()); } } if (connect_id != -1) { list.swapItemsAt(0, connect_id); } return list; } QVariantList KnmInterface::wirelessDeviceList() { QVariantList list; auto dev = KNMDC::getInstance()->wirelessDeviceList(); for(auto iter : dev){ if(!iter.isNull()) list.append(iter->devName()); } return list; } QVariantList KnmInterface::wiredDevConnList() { return m_wiredDevConnList; } QVariantList KnmInterface::wirelessDevConnList() { return m_wirelessDevConnList; } bool KnmInterface::wirelessSwitchState() { return KNMDC::getInstance()->wirelessSwitchState(); } bool KnmInterface::wiredMainSwitchState() { qWarning()<< Q_FUNC_INFO << __LINE__; return KNMDC::getInstance()->wiredMainSwitchState(); } QString KnmInterface::upwareRateDate() { return KNMDC::getInstance()->upwardRateDate(); } QString KnmInterface::downwareRateDate() { return KNMDC::getInstance()->downwardRateDate(); } bool KnmInterface::getNetMacConnectStatus(QString devmac) { qWarning() << devmac; int status = 0; auto conList = KNMDC::getInstance()->wiredDeviceConnList(devmac); qWarning() << conList; if(conList.count() != 0) { for (auto iter : conList) { status = iter.toMap().value("State").toInt(); if(2 == status) return true; } } conList = KNMDC::getInstance()->wirelessDeviceConnList(devmac); qWarning() << conList; if(conList.count() != 0) { for (auto iter : conList) { status = iter.toMap().value("State").toInt(); if(2 == status) return true; } } return false; } //网络托盘-更多网络设置的跳转问题: //1、若连接了无线网络且没有连接有线网络 跳转至无线网络 //2、否则跳转有线网络 void KnmInterface::openNetworkSetting() { if(m_pProcess) { m_pProcess->deleteLater(); } //获取当前的网络状态 ConnectStatus connect_status = getConnectionStatus(); QProcess process; if (connect_status == ConnectStatus::Wireless){ process.startDetached("ukui-control-center", QStringList() << "-m" << "wlanconnect"); } else { process.startDetached("ukui-control-center", QStringList() << "-m" << "netconnect"); } } void KnmInterface::openwLanNetworkSetting() { if(m_pProcess) { m_pProcess->deleteLater(); } m_pProcess = new QProcess(); QString cmd = "ukui-control-center"; QStringList arg; arg.clear(); arg << "-m"; arg << "wlanconnect"; m_pProcess->startDetached(cmd,arg); } void KnmInterface::getWiredDevConnList(QString devName) { m_currentWiredDevice = devName; m_wiredDevConnList = KNMDC::getInstance()->wiredDeviceConnList(devName); emit updateWiredDevConnList(); } void KnmInterface::getWiredDevConnList() { getWiredDevConnList(m_currentWiredDevice); } void KnmInterface::getWirelessDevConnList() { getWirelessDevConnList(m_currentWirelessDevice); } /*全量更新*/ void KnmInterface::rebuildCurrentWirelessList() { if(m_currentWirelessDevice.isEmpty()) { QMapdevMap=KNMDC::getInstance()->wirelessDeviceList(); if(!devMap.isEmpty()) m_currentWirelessDevice=devMap.first()->devName(); qWarning() << Q_FUNC_INFO <<__LINE__ << "set currentdevice"<wirelessDeviceConnList(m_currentWirelessDevice); mWirelessConnecModel.refreshConnections(m_wirelessDevConnList); emit wirelessConListChanged(); } /*增量更新*/ void KnmInterface::getWirelessDevConnList(QString devName) { QVariantList conList; /*后端add与remove信号可能先于qml的设备名传递,造成崩溃,先做保护,后边要重新优化下,规避方案不影响实际效果,设备变化会重建列表不影响*/ if(devName.isEmpty()) { qWarning() << Q_FUNC_INFO <<__LINE__ << devName<<"devname is empty"; return; } m_currentWirelessDevice = devName; if(m_wirelessDevConnList.isEmpty()) { m_wirelessDevConnList=KNMDC::getInstance()->wirelessDeviceConnList(devName); mWirelessConnecModel.refreshConnections(m_wirelessDevConnList); emit updateWirelessDevConnList(); emit wirelessConListChanged(); return; } conList = KNMDC::getInstance()->wirelessDeviceConnList(devName); for(int i=0;igetWiFiIcon(signalStrength, security, isApConnection, category); } void KnmInterface::activateConnect(QString devName, QString conUid, int type) { loadTimer->start(); KNMDC::getInstance()->activateConnect(devName, conUid, type); } void KnmInterface::deActivateConnect(QString devName, QString conUid, int type) { loadTimer->start(); KNMDC::getInstance()->deActivateConnect(devName, conUid, type); } void KnmInterface::setWiredMainSwitch(bool switched) { qWarning() << Q_FUNC_INFO << __LINE__ << switched; KNMDC::getInstance()->setWiredMainSwitchEnable(switched); } void KnmInterface::setWirelessSwitch(bool switched) { KNMDC::getInstance()->setWirelessSwitchEnable(switched); } void KnmInterface::setUpwareRateData(QString str) { qDebug() << Q_FUNC_INFO <<__LINE__ << str; KNMDC::getInstance()->setUpwareRateData(str); } void KnmInterface::setDownwareRateData(QString str) { qDebug() << Q_FUNC_INFO <<__LINE__ << str; //KNMDC::getInstance()->setDownwareRateData(str); } void KnmInterface::rescanWirelessConn() { KNMDC::getInstance()->rescanWirelessConn(); } void KnmInterface::passwordConnect(QString devName, QString ssid, QString type, QString psk, bool autoConnect) { KNMDC::getInstance()->passwordConnect(devName, ssid, type, psk, autoConnect); } void KnmInterface::showPropertyWidget(QString devName, QString ssid) { qDebug() << Q_FUNC_INFO <<__LINE__ << devName << ssid; KNMDC::getInstance()->showPropertyWidget(devName, ssid); } void KnmInterface::deleteConnect(int type, QString ssid) { qDebug() << Q_FUNC_INFO <<__LINE__ << type << ssid; KNMDC::getInstance()->deleteConnect(type, ssid); } void KnmInterface::showAddOtherWlanPage(QString devName) { qDebug() << Q_FUNC_INFO <<__LINE__ << devName; KNMDC::getInstance()->showAddOtherWlanPage(devName); } /* * 获取有线和无线的连接状态 * 1、无线有线都有连接 * 2、仅有有线连接 * 3、仅有无线连接 * 3、都未连接 */ ConnectStatus KnmInterface::getConnectionStatus() { auto wiredDev = KNMDC::getInstance()->wiredDeviceList(); bool wiredConnect = false; for (auto iter : wiredDev) { if (!iter.isNull()) { if (!wiredConnect) { for (auto devices : iter->getConnections()) { int status = devices.toMap().value("State").toInt(); if (2 == status) { //2==已连接 wiredConnect = true; break; } } } } if (wiredConnect) { break; } } auto wirelessDev = KNMDC::getInstance()->wirelessDeviceList(); bool wirelessConnect = false; for (auto iter : wirelessDev) { if (!iter.isNull()) { if (!wirelessConnect) { for (auto devices : iter->getConnections()) { int status = devices.toMap().value("State").toInt(); if (2 == status) { //2==已连接 wirelessConnect = true; break; } } } } if (wirelessConnect) { break; } } if (wiredConnect && wirelessConnect){ return ConnectStatus::All; } else if (wiredConnect) { return ConnectStatus::Wire; } else if (wirelessConnect) { return ConnectStatus::Wireless; } else { return ConnectStatus::NoConnect; } } void KnmInterface::slotRefreshTimeout() { rescanWirelessConn(); } bool KnmInterface::getCableStatus() { KNMDC::getInstance()->getCableStateByDevice(""); return false; } bool KnmInterface::getCableStatusByDev(const QString &devName) { KNMDC::getInstance()->getCableStateByDevice(devName); return false; } QString KnmInterface::fontSize() { return m_fontSize; } kylin-nm/qml-network/plugin/knmdbuscaller.cpp0000664000175000017500000004140715167651420020363 0ustar fengfeng #include "knmdbuscaller.h" #include "knminterface.h" KnmDBusCaller::KnmDBusCaller(QObject *parent) : QObject{parent} { KnmLanDataKeeperPtr ldk(new KnmLanDataKeeper(this)); lanDataKeeper = ldk; KnmWlanDataKeeperPtr wdk(new KnmWlanDataKeeper(this)); wlanDataKeeper = wdk; m_pInterface = new QDBusInterface("com.kylin.network", "/com/kylin/network", "com.kylin.network", QDBusConnection::sessionBus()); if(!m_pInterface->isValid()) { qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } qDBusRegisterMetaType>(); this->connect(lanDataKeeper.data(), &KnmLanDataKeeper::onDeviceStatusChanged, this, &KnmDBusCaller::updateWiredDeviceMap); this->connect(wlanDataKeeper.data(), &KnmWlanDataKeeper::onDeviceStatusChanged, this, &KnmDBusCaller::updateWirelessDevice); getWiredDeviceMap(); getWiredMainSwitchState(); getWirelessSwitchState(); getWirelessDeviceMap(); } KnmDBusCaller::~KnmDBusCaller() { } QMap KnmDBusCaller::wiredDeviceList() { return lanDataKeeper->getDeviceList(); } QMap KnmDBusCaller::wirelessDeviceList() { return wlanDataKeeper->getDeviceList(); } QVariantList KnmDBusCaller::wiredDeviceConnList(QString devName) { return lanDataKeeper->getDevConnections(devName); } QVariantList KnmDBusCaller::wirelessDeviceConnList(QString devName) { return wlanDataKeeper->getDevConnections(devName); } bool KnmDBusCaller::wirelessSwitchState() { return wlanDataKeeper->getSwitchState(); } bool KnmDBusCaller::wiredMainSwitchState() { qWarning()<< Q_FUNC_INFO << __LINE__; return lanDataKeeper->getWiredMainSwitchState(); } QString KnmDBusCaller::upwardRateDate() { return lanDataKeeper->getUpwardRate(); } QString KnmDBusCaller::downwardRateDate() { return lanDataKeeper->getDownwardRate(); } QString KnmDBusCaller::getWiFiIcon(QString signalStrength, QString security, QString isApConnection, int category) { return wlanDataKeeper->getWiFiIcon(signalStrength, security, isApConnection, category); } QDBusPendingCallWatcher *KnmDBusCaller::asyncCall(const QString & methed, const QList & params) { if (!m_pInterface->isValid()) { qWarning() << "not connect dbus server: " << m_pInterface->lastError().message(); return nullptr; } QDBusPendingCall pendingCall = m_pInterface->asyncCallWithArgumentList(methed, params); return new QDBusPendingCallWatcher(pendingCall); } void KnmDBusCaller::activateConnect(QString devName, QString conUid, int type) { QList list; list.append(type); list.append(devName); list.append(conUid); this->asyncCall("activateConnect", list); } void KnmDBusCaller::deActivateConnect(QString devName, QString conUid, int type) { QList list; list.append(type); list.append(devName); list.append(conUid); this->asyncCall("deActivateConnect", list); } void KnmDBusCaller::passwordConnect(QString devName, QString ssid, QString type, QString psk, bool autoConnect) { QList list; list.append(devName); list.append(ssid); list.append(type); list.append(psk); list.append(autoConnect); this->asyncCall("passwordConnect", list); } void KnmDBusCaller::showPropertyWidget(QString devName, QString ssid) { QList list; list.append(devName); list.append(ssid); this->asyncCall("showPropertyWidget", list); } void KnmDBusCaller::deleteConnect(int type, QString ssid) { QList list; list.append(type); list.append(ssid); this->asyncCall("deleteConnect", list); } void KnmDBusCaller::getWirelessSwitchState() { QList list; QDBusPendingCallWatcher * watcher = this->asyncCall("getWirelessSwitchBtnState", list); if(watcher) { m_pendingCount++; this->connect(watcher, &QDBusPendingCallWatcher::finished, this, &KnmDBusCaller::getWirelessSwitchStateFinished); } else { qWarning() << "null pending"; } } void KnmDBusCaller::getWiredMainSwitchState() { qDebug() << Q_FUNC_INFO << __LINE__; QList list; QDBusPendingCallWatcher * watcher = this->asyncCall("getWiredMainSwitchBtnState", list); if(watcher) { m_pendingCount++; this->connect(watcher, &QDBusPendingCallWatcher::finished, this, &KnmDBusCaller::getWiredMainSwitchStateFinished); } else { qWarning() << "null pending"; } } void KnmDBusCaller::getWiredDeviceMap() { QList list; list.append(0); QDBusPendingCallWatcher * watcher = this->asyncCall("getDeviceListAndEnabled", list); if(watcher) { m_pendingCount++; this->connect(watcher, &QDBusPendingCallWatcher::finished, this, &KnmDBusCaller::getWiredDeviceMapFinished); } else { qWarning() << "null pending"; } } void KnmDBusCaller::getWirelessDeviceMap() { QList list; list.append(1); QDBusPendingCallWatcher * watcher = this->asyncCall("getDeviceListAndEnabled", list); if(watcher) { m_pendingCount++; this->connect(watcher, &QDBusPendingCallWatcher::finished, this, &KnmDBusCaller::getWirelessDeviceMapFinished); } else { qWarning() << "null pending"; } } void KnmDBusCaller::setWirelessSwitchEnable(bool enable) { QList list; list.append(enable); QDBusPendingCallWatcher * watcher = this->asyncCall("setWirelessSwitchEnable", list); if(watcher) { m_pendingCount++; this->connect(watcher, &QDBusPendingCallWatcher::finished, this, &KnmDBusCaller::setWirelessSwitchEnableFinished); } else { qWarning() << "null pending"; } } void KnmDBusCaller::setUpwareRateData(QString str) { } void KnmDBusCaller::setDownwareRateData(QString str) { } void KnmDBusCaller::updateWiredDeviceMap() { QList list; list.append(0); QDBusPendingCallWatcher * watcher = this->asyncCall("getDeviceListAndEnabled", list); if(watcher) { m_pendingCount++; this->connect(watcher, &QDBusPendingCallWatcher::finished, this, &KnmDBusCaller::updateWiredDeviceMapFinished); } else { qWarning() << "null pending"; } } void KnmDBusCaller::updateWirelessDeviceMap() { QList list; list.append(1); QDBusPendingCallWatcher * watcher = this->asyncCall("getDeviceListAndEnabled", list); if(watcher) { m_pendingCount++; this->connect(watcher, &QDBusPendingCallWatcher::finished, this, &KnmDBusCaller::updateWirelessDeviceMapFinished); } else { qWarning() << "null pending"; } } void KnmDBusCaller::updateWirelessDevice() { getWirelessSwitchState(); updateWirelessDeviceMap(); // qWarning() << "mqtets updateWirelessDevice"; } void KnmDBusCaller::rescanWirelessConn() { QList list; this->asyncCall("reScan", list); } void KnmDBusCaller::getWiredConList(QString dev) { QList list; list.append(dev); QDBusPendingCallWatcher * watcher = this->asyncCall("getWiredList", list); if(watcher) { m_pendingCount++; this->connect(watcher, &QDBusPendingCallWatcher::finished, this, [=](QDBusPendingCallWatcher *watcher) { getWiredConListFinished(watcher, dev); }); } else { qWarning() << "null pending"; } } void KnmDBusCaller::getWirelessConList(QString dev) { QList list; list.append(dev); QDBusPendingCallWatcher * watcher = this->asyncCall("getWirelessList", list); if(watcher) { m_pendingCount++; this->connect(watcher, &QDBusPendingCallWatcher::finished, this, [=](QDBusPendingCallWatcher *watcher) { getWirelessConListFinished(watcher, dev); }); } else { qWarning() << "null pending"; } } void KnmDBusCaller::getWiredDeviceMapFinished(QDBusPendingCallWatcher *watcher) { m_pendingCount--; QDBusMessage reply = watcher->reply(); if(reply.type() == QDBusMessage::ReplyMessage) { if(reply.arguments().size() > 0) { QDBusReply retMap = reply; QVariantMap::const_iterator item = retMap.value().cbegin(); while (item != retMap.value().cend()) { lanDataKeeper->addDevice(item.key(), item.value().toBool(),WIRED_DEVICE); getWiredConList(item.key()); item++; } KInterface::getInstance()->updateWiredDeviceList(); } } else { qWarning() << reply.errorMessage(); } } void KnmDBusCaller::updateWiredDeviceMapFinished(QDBusPendingCallWatcher *watcher) { m_pendingCount--; QDBusMessage reply = watcher->reply(); if(reply.type() == QDBusMessage::ReplyMessage) { if(reply.arguments().size() > 0) { QDBusReply retMap = reply; QVariantMap::const_iterator item = retMap.value().cbegin(); lanDataKeeper->clearDevice(); while (item != retMap.value().cend()) { lanDataKeeper->addDevice(item.key(), item.value().toBool(),WIRED_DEVICE); lanDataKeeper->clearConnectionList(item.key()); getWiredConList(item.key()); item++; } KInterface::getInstance()->updateWiredDeviceList(); } } else { qWarning() << reply.errorMessage(); } } void KnmDBusCaller::updateWirelessDeviceMapFinished(QDBusPendingCallWatcher *watcher) { m_pendingCount--; QDBusMessage reply = watcher->reply(); if(reply.type() == QDBusMessage::ReplyMessage) { if(reply.arguments().size() > 0) { QDBusReply retMap = reply; QVariantMap::const_iterator item = retMap.value().cbegin(); wlanDataKeeper->clearDevice(); while (item != retMap.value().cend()) { wlanDataKeeper->addDevice(item.key(), item.value().toBool(),WIRELESS_DEVICE); wlanDataKeeper->clearConnectionList(item.key()); updateWirelessConListSync(item.key()); item++; } KInterface::getInstance()->rebuildCurrentWirelessList();//设备状态变更应该全量更新合理点 emit KInterface::getInstance()->updateWirelessDeviceList(); } } else { qWarning() << reply.errorMessage(); } } void KnmDBusCaller::getWirelessDeviceMapFinished(QDBusPendingCallWatcher *watcher) { m_pendingCount--; QDBusMessage reply = watcher->reply(); if(reply.type() == QDBusMessage::ReplyMessage) { if(reply.arguments().size() > 0) { QDBusReply retMap = reply; QVariantMap::const_iterator item = retMap.value().cbegin(); while (item != retMap.value().cend()) { wlanDataKeeper->addDevice(item.key(), item.value().toBool(), WIRELESS_DEVICE); updateWirelessConListSync(item.key()); item++; } KInterface::getInstance()->rebuildCurrentWirelessList();//设备状态变更应该全量更新合理点 } } else { qWarning() << reply.errorMessage(); } } void KnmDBusCaller::getWiredConListFinished(QDBusPendingCallWatcher *watcher, QString dev) { m_pendingCount--; QDBusMessage reply = watcher->reply(); if(reply.type() == QDBusMessage::ReplyMessage) { if(reply.arguments().size() > 0) { QDBusReply retList = reply; QList list; for (int j = 0; j < retList.value().size(); ++j) { list << retList.value().at(j).toStringList(); } lanDataKeeper->addDevConnection(dev, list); KInterface::getInstance()->updateWiredDeviceList(); } } else { qWarning() << reply.errorMessage(); } } void KnmDBusCaller::getWirelessConListFinished(QDBusPendingCallWatcher *watcher, QString dev) { m_pendingCount--; QDBusMessage reply = watcher->reply(); if(reply.type() == QDBusMessage::ReplyMessage) { if(reply.arguments().size() > 0) { QDBusReply retList = reply; QList list; for (int j = 0; j < retList.value().size(); ++j) { list << retList.value().at(j).toStringList(); } wlanDataKeeper->clearConnectionList(dev); wlanDataKeeper->addDevConnection(dev, list); KInterface::getInstance()->updateWirelessDeviceList(); } } else { qWarning() << reply.errorMessage(); } } void KnmDBusCaller::getWirelessSwitchStateFinished(QDBusPendingCallWatcher *watcher) { m_pendingCount--; QDBusMessage reply = watcher->reply(); if(reply.type() == QDBusMessage::ReplyMessage) { if(reply.arguments().size() > 0) { QDBusReply retList = reply; wlanDataKeeper->setSwitchState(retList.value()); KInterface::getInstance()->updateWirelessSwitch(); } } else { qWarning() << reply.errorMessage(); } } void KnmDBusCaller::getWiredMainSwitchStateFinished(QDBusPendingCallWatcher *watcher) { qDebug() << Q_FUNC_INFO << __LINE__; m_pendingCount--; QDBusMessage reply = watcher->reply(); qDebug() << Q_FUNC_INFO << __LINE__ << reply; if(reply.type() == QDBusMessage::ReplyMessage) { if(reply.arguments().size() > 0) { QDBusReply retList = reply; lanDataKeeper->setWiredMainSwitchState(retList.value()); KInterface::getInstance()->updateWiredMainSwitch(); } } else { qWarning() << reply.errorMessage(); } } void KnmDBusCaller::setWirelessSwitchEnableFinished(QDBusPendingCallWatcher *watcher) { m_pendingCount--; QDBusMessage reply = watcher->reply(); if(reply.type() == QDBusMessage::ReplyMessage) { updateWirelessDeviceMap(); } else { qWarning() << reply.errorMessage(); } } void KnmDBusCaller::setWiredMainSwitchEnable(bool enable) { qDebug() << Q_FUNC_INFO << __LINE__ << enable; QList list; list.append(enable); QDBusPendingCallWatcher * watcher = this->asyncCall("setWiredSwitchEnable", list); if(watcher) { m_pendingCount++; this->connect(watcher, &QDBusPendingCallWatcher::finished, this, &KnmDBusCaller::setWiredMainSwitchEnableFinished); } else { qWarning() << "null pending"; } } void KnmDBusCaller::setWiredMainSwitchEnableFinished(QDBusPendingCallWatcher *watcher) { m_pendingCount--; QDBusMessage reply = watcher->reply(); if(reply.type() == QDBusMessage::ReplyMessage) { getWiredMainSwitchState(); updateWiredDeviceMap(); } else { qWarning() << reply.errorMessage(); } } void KnmDBusCaller::showAddOtherWlanPage(QString devName) { QList list; list.append(devName); this->asyncCall("showAddOtherWlanWidget",list); } void KnmDBusCaller::updateWirelessConListSync(QString dev) { QDBusReply reply = m_pInterface->call(QStringLiteral("getWirelessList"), dev); //qDebug() << "[NetConnect]call getWirelessList respond" << __LINE__; if(!reply.isValid()) { qWarning() << "getWirelessList error:" << reply.error().message(); return; } QList list; for (int j = 0; j < reply.value().size(); ++j) { list << reply.value().at(j).toStringList(); } wlanDataKeeper->clearConnectionList(dev); wlanDataKeeper->addDevConnection(dev, list); KInterface::getInstance()->updateWirelessDeviceList(); } // void KnmDBusCaller::getWiredMainSwitchState() // { // QList list; // QDBusPendingCallWatcher * watcher = this->asyncCall("getWirelessSwitchBtnState", list); // if(watcher) { // m_pendingCount++; // this->connect(watcher, &QDBusPendingCallWatcher::finished, this, &KnmDBusCaller::getWirelessSwitchStateFinished); // } // else { // qWarning() << "null pending"; // } // } /* * 调用getCableStateByDevice dbus接口,返回值为 bool:是否插入网线 */ void KnmDBusCaller::getCableStateByDevice(const QString &dev) { QList list; list.append(dev); QDBusPendingCallWatcher * watcher = this->asyncCall("getCableStateByDevice", list); if(watcher) { m_pendingCount++; this->connect(watcher, &QDBusPendingCallWatcher::finished, this, &KnmDBusCaller::updateCableState); } else { qWarning() << "null pending"; } } /* * getCableStateByDevice dbus返回槽函数 */ void KnmDBusCaller::updateCableState(QDBusPendingCallWatcher *watcher) { m_pendingCount--; QDBusPendingReply reply = *watcher; if (!reply.isError()) { bool ret = reply.value(); KInterface::getInstance()->updateCable(ret); } else { qWarning() << reply.isError(); } } kylin-nm/qml-network/plugin/networkqml_plugin.cpp0000664000175000017500000000071615167651420021314 0ustar fengfeng#include "networkqml_plugin.h" #include "knminterface.h" #include #include void NetworkhqmlPlugin::registerTypes(const char *uri) { Q_ASSERT(QString(uri) == QLatin1String("org.ukui.shortcut.network")); qmlRegisterModule(uri, 1, 0); qmlRegisterSingletonType(uri, 1, 0, "KInterface", [] (QQmlEngine *, QJSEngine *) -> QObject* { KInterface::instance(); return KInterface::getInstance(); }); } kylin-nm/qml-network/plugin/netdevice.cpp0000775000175000017500000001061615167651420017504 0ustar fengfeng#include "netdevice.h" NetDevice::NetDevice(QString devName, DeviceType type) { this->m_Name = devName; this->m_DevType = type; } NetDevice::~NetDevice() { } bool NetDevice::isAvailable() { return this->m_Available; } QString NetDevice::devName() { return this->m_Name; } void NetDevice::setAvailable(bool available) { this->m_Available = available; } DeviceType NetDevice::getDevType() { return this->m_DevType; } void NetDevice::addConnection(QMap connections) { if (m_connectionsList.contains(connections)) return; if (connections.value("State").toInt() == ACTIVATED || connections.value("State").toInt() == ACTIVATING) m_connectionsList.push_front(connections); else m_connectionsList.append(connections); } void NetDevice::removeConnection(QMap connections) { if (!m_connectionsList.contains(connections)) return; m_connectionsList.removeOne(connections); } void NetDevice::removeConnection(QString path) { for (int i = 0; i < m_connectionsList.count(); i++) { QMapvalueMap=m_connectionsList.at(i).toMap(); if (valueMap.value("Path").toString() == path) { m_connectionsList.removeAt(i); } } } void NetDevice::removeConnectionByName(QString devName) { for (int i = 0; i < m_connectionsList.count(); i++) { QMapvalueMap=m_connectionsList.at(i).toMap(); if (valueMap.value("Name").toString() == devName) { m_connectionsList.removeAt(i); } } } QVariantList NetDevice::getConnections() { QVariantList list; if(m_connectionsList.isEmpty()) { return list; } return m_connectionsList; } QMap NetDevice::updateConnection(QString uuid, int status) { int i = 0; QMap conn; while (i < m_connectionsList.count()) { QMapvalueMap=m_connectionsList.at(i).toMap(); if (valueMap.value("Uuid").toString() == uuid) { conn = m_connectionsList.takeAt(i).toMap(); conn.remove("State"); conn.insert("State", status); if (status == ACTIVATED) { m_connectionsList.push_front(conn); } else m_connectionsList.insert(i, conn); break; } i++; } return conn; } bool NetDevice::containsConnection(QString uuidOrPath) { for (int i = 0; i < m_connectionsList.count(); i++) { QMapvalueMap=m_connectionsList.at(i).toMap(); if (valueMap.value("Uuid").toString() == uuidOrPath) { return true; } if (m_DevType == WIRELESS_DEVICE) continue; if (valueMap.value("Path").toString() == uuidOrPath) { return true; } } return false; } bool NetDevice::containsConnectionName(QString connName) { for (int i = 0; i < m_connectionsList.count(); i++) { QMapvalueMap=m_connectionsList.at(i).toMap(); if (valueMap.value("Name").toString() == connName) { return true; } } return false; } void NetDevice::clearConnections() { m_connectionsList.clear(); } QMap NetDevice::getConnectionByName(QString connName) { QMap ret; for (int i = 0; i < m_connectionsList.count(); i++) { QMapvalueMap=m_connectionsList.at(i).toMap(); if (valueMap.value("Name").toString() == connName) { return m_connectionsList.at(i).toMap(); } } return ret; } QMap NetDevice::updateConnectivity(QString uuid, int status, int connectivity) { int i = 0; QMap conn; while (i < m_connectionsList.count()) { QMap valueMap = m_connectionsList.at(i).toMap(); if (valueMap.value("Uuid").toString() == uuid) { conn = m_connectionsList.takeAt(i).toMap(); conn.remove("State"); conn.insert("State", status); conn.remove("Connectivity"); conn.insert("Connectivity", connectivity); if (status == ACTIVATED) { m_connectionsList.push_front(conn); } else { m_connectionsList.insert(i, conn); } break; } i++; } return conn; } kylin-nm/qml-network/plugin/knmdatakeeper.h0000775000175000017500000000431215167651420020012 0ustar fengfeng#ifndef KNMDATAKEEPER_H #define KNMDATAKEEPER_H #include #include #include #include #include #include #include #include #include #include "netdevice.h" class NetDevice; //共享指针初始化 typedef QSharedPointer NetDevicePtr; //dbus调用之后用于保存数据的类 class KnmDataKeeper : public QObject { Q_OBJECT public: explicit KnmDataKeeper(QObject *parent = nullptr); ~KnmDataKeeper(); //添加一个网卡设备 void addDevice(QString devName, bool isAvailable, DeviceType type); //清空列表(用于刷新) void clearDevice(); //清空网卡设备连接(用于列表更新) void clearConnectionList(QString devName); //获取网卡设备列表 QMap getDeviceList(); //获取单个网卡设备的连接列表 QVariantList getDevConnections(QString devName); void setSwitchState(bool switched); bool getSwitchState(); void setWiredMainSwitchState(bool switched); bool getWiredMainSwitchState(); QString getUpwardRate(); QString getDownwardRate(); void setUpwardRate(QString); void setDownwardRate(QString); protected: //网速计时器初始化 void netSpeedInit(); //网速获取和计算函数 void netSpeedHandler(QString dev, QString &upLoad, QString &downLoad); //获取当前网卡负载率 int getCurrentLoadRate(QString dev, long *save_rate, long *tx_rate); void slotSpeedTimeout(); protected: bool m_connected = false; bool m_wiredMainSwitchState = false; bool m_switchState = false; QTimer *m_pSpeedTimer = nullptr; QString m_currentDev; //保存开始时的流量计数 long int start_rcv_rates = 0; //保存结束时的流量计数 long int end_rcv_rates = 0; //保存开始时的流量计数 long int start_tx_rates = 0; //保存结束时的流量计数 long int end_tx_rates = 0; // QString m_upward_rate; QString m_downward_rate; //设备列表,QString为网卡名,NetDevicePtr为网卡数据类 QMap m_deviceList; }; #endif // KNMDATAKEEPER_H kylin-nm/qml-network/plugin/knmwlandatakeeper.h0000664000175000017500000000264715167651420020702 0ustar fengfeng#ifndef KNMWLANDATAKEEPER_H #define KNMWLANDATAKEEPER_H #include #include "knmdatakeeper.h" class KnmWlanDataKeeper; typedef QSharedPointer KnmWlanDataKeeperPtr; class KnmWlanDataKeeper : public KnmDataKeeper { Q_OBJECT public: explicit KnmWlanDataKeeper(QObject *parent = nullptr); ~KnmWlanDataKeeper(); //添加网卡设备的连接 void addDevConnection(QString devName, QList conPath); QString getWiFiIcon(QString signalStrength, QString security, QString isApConnection, int category); signals: void onDeviceStatusChanged(); private: QMap makeConnectionMap(int status, QStringList conPath); int setSignal(QString sg); QString getWiFiIconString(bool isLock, int strength, int category); private slots: //已激活连接状态更新 void onActiveConnectionChanged(QString deviceName, QString ssid, QString uuid, int status); //新增连接 void onNetworkAdd(QString deviceName, QStringList wlanInfo); //删除连接 void onNetworkRemove(QString deviceName, QString wlanName); //更新网卡设备名称 void onDeviceNameChanged(QString oldName, QString newName, int type); //更新开关状态 void onSwitchBtnChanged(bool status); //更新连接列表顺序 void updateList(); private: QDBusInterface *m_pInterface = nullptr; }; #endif // KNMWLANDATAKEEPER_H kylin-nm/qml-network/plugin/netdevice.h0000775000175000017500000000237615167651420017155 0ustar fengfeng#ifndef NETDEVICE_H #define NETDEVICE_H #include #include #include #include #define ACTIVATING 1 #define ACTIVATED 2 #define DEACTIVATING 3 #define DEACTIVATED 4 typedef enum { WIRED_DEVICE, WIRELESS_DEVICE } DeviceType; //网卡对象 class NetDevice { public: NetDevice(QString devName, DeviceType type); ~NetDevice(); bool isAvailable(); QString devName(); DeviceType getDevType(); void setAvailable(bool available); bool containsConnection(QString uuidOrPath); bool containsConnectionName(QString connName); void addConnection(QMap connections); void removeConnection(QMap connections); void removeConnection(QString path); void removeConnectionByName(QString devName); QMap updateConnection(QString uuid, int status); QMap getConnectionByName(QString connName); QVariantList getConnections(); void clearConnections(); QMap updateConnectivity(QString uuid, int status, int connectivity); private: QString m_Name; bool m_Available; DeviceType m_DevType; QVariantList m_connectionsList; }; #endif // NETDEVICE_H kylin-nm/qml-network/plugin/networkqml_plugin.h0000664000175000017500000000046015167651420020755 0ustar fengfeng#ifndef NETWORKQML_PLUGIN_H #define NETWORKQML_PLUGIN_H #include class NetworkhqmlPlugin : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID QQmlExtensionInterface_iid) public: void registerTypes(const char *uri) override; }; #endif // NETWORKQML_PLUGIN_H kylin-nm/tests/0000775000175000017500000000000015167651420012407 5ustar fengfengkylin-nm/tests/unit_test_alltest/0000775000175000017500000000000015167651420016155 5ustar fengfengkylin-nm/tests/unit_test_alltest/unit_test_kylinconnectitem.cpp0000664000175000017500000000357715167651420024352 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kylinconnectitem.h" using namespace stub_ext; class KyConnectItemTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *KyConnectItemTest::m_pDBus = nullptr; TEST_F(KyConnectItemTest, allParameter) { KyConnectItem *wiredConnectItem = new KyConnectItem(); wiredConnectItem->m_connectName = "connectPtr->name()"; wiredConnectItem->m_connectUuid = "activeConnectPtr->uuid()"; wiredConnectItem->m_ifaceName = "settingPtr->interfaceName()"; wiredConnectItem->m_connectState = NetworkManager::ActiveConnection::State::Unknown; wiredConnectItem->m_itemType = NetworkManager::ConnectionSettings::ConnectionType::Unknown; ASSERT_EQ(100, 100); delete wiredConnectItem; } kylin-nm/tests/unit_test_alltest/unit_test_kywirelessnetitem.cpp0000664000175000017500000000435615167651420024556 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kywirelessnetitem.h" using namespace stub_ext; class KyWirelessNetItemTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *KyWirelessNetItemTest::m_pDBus = nullptr; TEST_F(KyWirelessNetItemTest, allParameter) { KyWirelessNetItem wirelessNetItem = KyWirelessNetItem(); wirelessNetItem.m_networkResourceInstance = KyNetworkResourceManager::getInstance(); wirelessNetItem.m_bssid = "m_bssid"; wirelessNetItem.m_connectUuid = "m_connectUuid"; wirelessNetItem.m_isConfigured = false; wirelessNetItem.m_connName = "m_connName"; wirelessNetItem.m_connDbusPath = "m_connDbusPath"; wirelessNetItem.m_secuType = "m_secuType"; wirelessNetItem.m_kySecuType = KYLIN_NM::NONE; wirelessNetItem.m_device = "m_device"; wirelessNetItem.m_channel = 0; wirelessNetItem.m_isMix = false; ASSERT_EQ(100, 100); } TEST_F(KyWirelessNetItemTest, getDevice) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessNetItemTest, getCategory) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessNetItemTest, setKySecuType) { ASSERT_EQ(100, 100); } kylin-nm/tests/unit_test_alltest/unit_test_kylinvpnconnectitem.cpp0000664000175000017500000000377215167651420025073 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kylinvpnconnectitem.h" using namespace stub_ext; class KyVpnConnectItemTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *KyVpnConnectItemTest::m_pDBus = nullptr; TEST_F(KyVpnConnectItemTest, allParameter) { KyVpnConnectItem *vpnConnectItem = new KyVpnConnectItem(); vpnConnectItem->m_vpnName = "connectPtr->name()"; vpnConnectItem->m_vpnUuid = "activeConnectPtr->uuid()"; vpnConnectItem->m_vpnUser = "settingPtr->interfaceName()"; vpnConnectItem->m_vpnGateWay = "wirelessSetting->ssid()"; vpnConnectItem->m_vpnIpv4Address = "apConnectItem->ipv4"; vpnConnectItem->m_vpnIpv6Address = "apConnectItem->ipv6"; vpnConnectItem->m_vpnMppe = false; vpnConnectItem->m_vpnState = NetworkManager::VpnConnection::State::Disconnected; ASSERT_EQ(100, 100); delete vpnConnectItem; } kylin-nm/tests/unit_test_alltest/unit_test_kylinbluetoothconnectitem.cpp0000664000175000017500000000370515167651420026271 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kylinbluetoothconnectitem.h" using namespace stub_ext; class KyBluetoothConnectItemTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *KyBluetoothConnectItemTest::m_pDBus = nullptr; TEST_F(KyBluetoothConnectItemTest, allParameters) { KyBluetoothConnectItem *btConnectItem = new KyBluetoothConnectItem(); btConnectItem->m_connectName = "connectPtr->name()"; btConnectItem->m_connectUuid = "activeConnectPtr->uuid()"; btConnectItem->m_deviceAddress = "settingPtr->interfaceName()"; btConnectItem->m_ipv4Address = "wirelessSetting->ssid()"; btConnectItem->m_ipv6Address = "apConnectItem->m_connectUuid"; btConnectItem->m_state = NetworkManager::ActiveConnection::State::Deactivated; ASSERT_EQ(100, 100); delete btConnectItem; } kylin-nm/tests/unit_test_alltest/unit_test_kyenterpricesettinginfo.cpp0000664000175000017500000000510115167651420025732 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kyenterpricesettinginfo.h" using namespace stub_ext; class KyEnterpriceSettingInfoTest : public testing::Test { protected: static void SetUpTestSuite() { // m_pNetworkModeConfigDBus = new QDBusInterface("org.freedesktop.NetworkManager", // connectPath, // "org.freedesktop.NetworkManager.Settings.Connection", // QDBusConnection::systemBus()); } static void TearDownTestSuite() { // if (m_pNetworkModeConfigDBus) { // delete m_pNetworkModeConfigDBus; // m_pNetworkModeConfigDBus = nullptr; // } } static QDBusInterface* m_pDBus; }; QDBusInterface *KyEnterpriceSettingInfoTest::m_pDBus = nullptr; TEST_F(KyEnterpriceSettingInfoTest, modifyEapMethodFastSettings) { ASSERT_EQ(100, 100); } TEST_F(KyEnterpriceSettingInfoTest, modifyEapMethodTtlsSettings) { ASSERT_EQ(100, 100); } TEST_F(KyEnterpriceSettingInfoTest, modifyEapMethodPeapSettings) { ASSERT_EQ(100, 100); } TEST_F(KyEnterpriceSettingInfoTest, modifyEapMethodTlsSettings) { ASSERT_EQ(100, 100); } TEST_F(KyEnterpriceSettingInfoTest, assembleEapMethodFastSettings) { ASSERT_EQ(100, 100); } TEST_F(KyEnterpriceSettingInfoTest, assembleEapMethodTlsSettings) { ASSERT_EQ(100, 100); } TEST_F(KyEnterpriceSettingInfoTest, assembleEapMethodPeapSettings) { ASSERT_EQ(100, 100); } TEST_F(KyEnterpriceSettingInfoTest, assembleEapMethodTtlsSettings) { ASSERT_EQ(100, 100); } kylin-nm/tests/unit_test_alltest/main.cpp0000664000175000017500000000202115167651420017600 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include int main(int argc, char **argv) { QGuiApplication a(argc, argv); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } kylin-nm/tests/unit_test_alltest/unit_test_kylinactiveconnectresource.cpp0000664000175000017500000000457615167651420026437 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kylinactiveconnectresource.h" using namespace stub_ext; class KyActiveConnectResourseInterfaceTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *KyActiveConnectResourseInterfaceTest::m_pDBus = nullptr; TEST_F(KyActiveConnectResourseInterfaceTest, getActiveConnectionByUuid) { ASSERT_EQ(100, 100); } TEST_F(KyActiveConnectResourseInterfaceTest, getActiveConnectionList) { ASSERT_EQ(100, 100); } TEST_F(KyActiveConnectResourseInterfaceTest, getActiveConnectIpInfo) { ASSERT_EQ(100, 100); } TEST_F(KyActiveConnectResourseInterfaceTest, getActiveConnectDnsInfo) { ASSERT_EQ(100, 100); } TEST_F(KyActiveConnectResourseInterfaceTest, getVpnActivateConnect) { ASSERT_EQ(100, 100); } TEST_F(KyActiveConnectResourseInterfaceTest, getBtActivateConnect) { ASSERT_EQ(100, 100); } TEST_F(KyActiveConnectResourseInterfaceTest, getApActivateConnect) { ASSERT_EQ(100, 100); } TEST_F(KyActiveConnectResourseInterfaceTest, getDeviceOfActivateConnect) { ASSERT_EQ(100, 100); } TEST_F(KyActiveConnectResourseInterfaceTest, getAcitveConnectionPathByUuid) { ASSERT_EQ(100, 100); } TEST_F(KyActiveConnectResourseInterfaceTest, getActivateWifiSignal) { ASSERT_EQ(100, 100); } kylin-nm/tests/unit_test_alltest/unit_test_alltest.pro0000664000175000017500000000543515167651420022454 0ustar fengfeng#------------------------------------------------- # # Project created by QtCreator 2019-08-22T11:12:59 # #------------------------------------------------- QT += core gui x11extras dbus KWindowSystem svg concurrent network #greaterThan(QT_MAJOR_VERSION, 4): QT += widgets concurrent sql xml TEMPLATE = app TARGET = unit_test_alltest target.source += $$TARGET target.path = ./ #代码覆盖率工具gcov QMAKE_LFLAGS +=-fprofile-arcs -ftest-coverage QMAKE_CXXFLAGS += --coverage -fno-inline -fno-access-control -fno-exceptions LIBS += -lgtest_main -lpthread LIBS += -L$$[QT_INSTALL_LIBS] -lgsettings-qt -lgtest -lgcov # -ldconf -lfontconfig -lfreetype CONFIG += c++14 qt warn_on link_pkgconfig no_keywords #CONFIG += release PKGCONFIG +=gio-2.0 glib-2.0 gio-unix-2.0 libnm libnma libsecret-1 gtk+-3.0 gsettings-qt libcap kysdk-qtwidgets kysdk-waylandhelper PKGCONFIG +=kysdk-sysinfo INCLUDEPATH += /usr/include/KF5/NetworkManagerQt LIBS += -L/usr/lib/ -lgsettings-qt -lX11 -lKF5NetworkManagerQt -lukui-log4qt -lgcov -lgtest_main -lpthread #INCLUDEPATH += /usr/include/dconf #打桩工具 TEST_UTILS_PATH = $$PWD/../kt-test-utils # Include directories INCLUDEPATH += $$PROJECT_ROOTDIR \ $$TEST_UTILS_PATH/cpp-stub \ $$TEST_UTILS_PATH/cpp-stub-ext \ SOURCES += unit_test_kywirelessconnectoperation.cpp \ unit_test_wifi-auth-thread.cpp \ unit_test_kywirelessnetitem.cpp \ unit_test_kylinutil.cpp \ unit_test_kylinnetworkdeviceresource.cpp \ unit_test_kyenterpricesettinginfo.cpp \ unit_test_kylinapconnectitem.cpp \ unit_test_kylinbluetoothconnectitem.cpp \ unit_test_kylinconnectitem.cpp \ unit_test_kylinvpnconnectitem.cpp \ unit_test_kyvpnconnectoperation.cpp \ unit_test_kylinactiveconnectresource.cpp \ unit_test_kylinnetworkresourcemanager.cpp \ unit_test_kylinconnectoperation.cpp \ unit_test_kylinconnectresource.cpp \ main.cpp include(../../src/backend/dbus-interface/dbus-interface.pri) HEADERS += ../../src/backend/dbus-interface/kywirelessconnectoperation.h \ ../../src/backend/wifi-auth-thread.h \ ../../src/backend/dbus-interface/kywirelessnetitem.h \ ../../src/backend/dbus-interface/kylinutil.h \ ../../src/backend/dbus-interface/kylinnetworkdeviceresource.h \ ../../src/backend/dbus-interface/kylinapconnectitem.h \ ../../src/backend/dbus-interface/kylinbluetoothconnectitem.h \ ../../src/backend/dbus-interface/kyenterpricesettinginfo.h \ ../../src/backend/dbus-interface/kylinconnectitem.h \ ../../src/backend/dbus-interface/kylinvpnconnectitem.h \ ../../src/backend/dbus-interface/kylinactiveconnectresource.h \ ../../src/backend/dbus-interface/kylinnetworkresourcemanager.h \ ../../src/backend/dbus-interface/kyvpnconnectoperation.h \ ../../src/backend/dbus-interface/kylinconnectoperation.h \ ../../src/backend/dbus-interface/kylinconnectresource.h \ kylin-nm/tests/unit_test_alltest/unit_test_wifi-auth-thread.cpp0000664000175000017500000000266115167651420024126 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/wifi-auth-thread.h" using namespace stub_ext; class WifiAuthThredInterfaceTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *WifiAuthThredInterfaceTest::m_pDBus = nullptr; TEST_F(WifiAuthThredInterfaceTest, run) { ASSERT_EQ(100, 100); } kylin-nm/tests/unit_test_alltest/unit_test_kywirelessconnectoperation.cpp0000664000175000017500000000444615167651420026463 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kywirelessconnectoperation.h" #define PSK_SETTING_NAME "802-11-wireless-security" #define PRIVATE_PSK_SETTING_NAME "802-1x" using namespace stub_ext; class KyWirelessConnectOperationInterfaceTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *KyWirelessConnectOperationInterfaceTest::m_pDBus = nullptr; TEST_F(KyWirelessConnectOperationInterfaceTest, getPrivateKeyPassword) { QString connectUuid = ""; NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(connectUuid); if (connectPtr.isNull()) { QString errorMessage = connectUuid; qWarning()< #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kylinconnectresource.h" using namespace stub_ext; class KyConnectResourseTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *KyConnectResourseTest::m_pDBus = nullptr; TEST_F(KyConnectResourseTest, getConnectionItemByUuid) { KyConnectResourse resource; QString uuid = "11111"; KyConnectItem *ret = resource.getConnectionItemByUuid(uuid); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, getConnectionItemByUuidWithoutActivateChecking) { KyConnectResourse resource; QString uuid = "11111"; KyConnectItem *ret = resource.getConnectionItemByUuidWithoutActivateChecking(uuid); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, getVpnAndVirtualConnections) { KyConnectResourse resource; QList list; list.append(new KyConnectItem()); list.append(new KyConnectItem()); list.append(new KyConnectItem()); resource.getVpnAndVirtualConnections(list); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, getConnectionList) { KyConnectResourse resource; QString deviceName = "test"; NetworkManager::ConnectionSettings::ConnectionType connectionType; QList list; list.append(new KyConnectItem()); list.append(new KyConnectItem()); list.append(new KyConnectItem()); resource.getConnectionList(deviceName, connectionType, list); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, getVpnConnections) { KyConnectResourse resource; QList list; list.append(new KyVpnConnectItem()); list.append(new KyVpnConnectItem()); list.append(new KyVpnConnectItem()); resource.getVpnConnections(list); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, getBluetoothConnections) { KyConnectResourse resource; QList list; list.append(new KyBluetoothConnectItem()); list.append(new KyBluetoothConnectItem()); list.append(new KyBluetoothConnectItem()); resource.getBluetoothConnections(list); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, getApConnections) { KyConnectResourse resource; QList list; list.append(new KyApConnectItem()); list.append(new KyApConnectItem()); list.append(new KyApConnectItem()); resource.getApConnections(list); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, getApConnectionByUuid) { KyConnectResourse resource; QString connectUuid = "id"; KyApConnectItem *ret = resource.getApConnectionByUuid(connectUuid); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, getApConnectionPathByUuid) { KyConnectResourse resource; QString connectUuid = "id"; QString ret = resource.getApConnectionPathByUuid(connectUuid); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, getConnectionSetting) { KyConnectResourse resource; QString connectUuid = "id"; KyConnectSetting connectSetting; resource.getConnectionSetting(connectUuid, connectSetting); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, getInterfaceByUuid) { KyConnectResourse resource; QString deviceName = "devName"; QString connUuid = "id"; bool ret = resource.getInterfaceByUuid(deviceName, connUuid); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, getConnectivity) { KyConnectResourse resource; NetworkManager::Connectivity connectivity; resource.getConnectivity(connectivity); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, isVirtualConncection) { KyConnectResourse resource; QString uuid = "id"; bool ret = resource.isVirtualConncection(uuid); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, isWiredConnection) { KyConnectResourse resource; QString uuid = "id"; bool ret = resource.isWiredConnection(uuid); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, isActivatedConnection) { KyConnectResourse resource; QString uuid = "id"; bool ret = resource.isActivatedConnection(uuid); ASSERT_EQ(100, 100); } TEST_F(KyConnectResourseTest, isApConnection) { KyConnectResourse resource; QString uuid = "id"; bool ret = resource.isApConnection(uuid); ASSERT_EQ(100, 100); } kylin-nm/tests/unit_test_alltest/unit_test_kylinnetworkdeviceresource.cpp0000664000175000017500000000524115167651420026451 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kywirelessnetresource.h" using namespace stub_ext; class KyWirelessDeviceResourceInterfaceTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *KyWirelessDeviceResourceInterfaceTest::m_pDBus = nullptr; TEST_F(KyWirelessDeviceResourceInterfaceTest, getDeviceConnectivity) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessDeviceResourceInterfaceTest, getWirelessDeviceCapability) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessDeviceResourceInterfaceTest, getWifiNetwork) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessDeviceResourceInterfaceTest, getAllDeviceWifiNetwork) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessDeviceResourceInterfaceTest, getDeviceWifiNetwork) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessDeviceResourceInterfaceTest, getEnterPriseInfoTls) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessDeviceResourceInterfaceTest, getEnterPriseInfoPeap) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessDeviceResourceInterfaceTest, getEnterPriseInfoTtls) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessDeviceResourceInterfaceTest, getEnterPriseInfoLeap) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessDeviceResourceInterfaceTest, getEnterPriseInfoPwd) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessDeviceResourceInterfaceTest, getEnterPriseInfoFast) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessDeviceResourceInterfaceTest, getWirelessActiveConnection) { ASSERT_EQ(100, 100); } TEST_F(KyWirelessDeviceResourceInterfaceTest, getActiveWirelessNetItem) { ASSERT_EQ(100, 100); } kylin-nm/tests/unit_test_alltest/unit_test_kylinnetworkresourcemanager.cpp0000664000175000017500000000451415167651420026626 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kylinnetworkresourcemanager.h" using namespace stub_ext; class KyNetworkResourceManagerInterfaceTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *KyNetworkResourceManagerInterfaceTest::m_pDBus = nullptr; TEST_F(KyNetworkResourceManagerInterfaceTest, getNetworkDevice) { ASSERT_EQ(100, 100); } TEST_F(KyNetworkResourceManagerInterfaceTest, getActiveConnect) { ASSERT_EQ(100, 100); } TEST_F(KyNetworkResourceManagerInterfaceTest, getConnect) { ASSERT_EQ(100, 100); } TEST_F(KyNetworkResourceManagerInterfaceTest, getWifiNetwork) { ASSERT_EQ(100, 100); } TEST_F(KyNetworkResourceManagerInterfaceTest, getActiveConnectList) { ASSERT_EQ(100, 100); } TEST_F(KyNetworkResourceManagerInterfaceTest, getConnectList) { ASSERT_EQ(100, 100); } TEST_F(KyNetworkResourceManagerInterfaceTest, getNetworkDeviceList) { ASSERT_EQ(100, 100); } TEST_F(KyNetworkResourceManagerInterfaceTest, getConnectivity) { ASSERT_EQ(100, 100); } TEST_F(KyNetworkResourceManagerInterfaceTest, NetworkManagerIsInited) { ASSERT_EQ(100, 100); } TEST_F(KyNetworkResourceManagerInterfaceTest, getEnterPriseInfoPwd) { ASSERT_EQ(100, 100); } kylin-nm/tests/unit_test_alltest/unit_test_kylinapconnectitem.cpp0000664000175000017500000000356215167651420024665 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kylinapconnectitem.h" #define PASSWORD_TEST "password123123" using namespace stub_ext; class KyApConnectItemInterfaceTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *KyApConnectItemInterfaceTest::m_pDBus = nullptr; TEST_F(KyApConnectItemInterfaceTest, allParameter) { KyApConnectItem *apConnectItem = new KyApConnectItem(); apConnectItem->m_connectName = "connectPtr->name()"; apConnectItem->m_connectUuid = "activeConnectPtr->uuid()"; apConnectItem->m_ifaceName = "settingPtr->interfaceName()"; apConnectItem->m_connectSsid = "wirelessSetting->ssid()"; apConnectItem->m_password = PASSWORD_TEST; ASSERT_EQ(100, 100); delete apConnectItem; } kylin-nm/tests/unit_test_alltest/unit_test_kylinconnectoperation.cpp0000664000175000017500000000513515167651420025404 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kylinconnectoperation.h" using namespace stub_ext; class KyConnectOperationTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *KyConnectOperationTest::m_pDBus = nullptr; TEST_F(KyConnectOperationTest, createConnect) { KyConnectOperation classKyConnectOperation; KyConnectSetting connectSettingsInfo; classKyConnectOperation.createConnect(connectSettingsInfo); ASSERT_EQ(100, 100); } TEST_F(KyConnectOperationTest, updateConnect) { KyConnectOperation classKyConnectOperation; NetworkManager::ConnectionSettings::Ptr connectionSettings; const KyConnectSetting connectSettingsInfo; classKyConnectOperation.updateConnect(connectionSettings, connectSettingsInfo); ASSERT_EQ(100, 100); } TEST_F(KyConnectOperationTest, deleteConnect) { KyConnectOperation classKyConnectOperation; QString uuid = "111111"; classKyConnectOperation.deleteConnect(uuid); ASSERT_EQ(100, 100); } TEST_F(KyConnectOperationTest, activateConnection) { KyConnectOperation classKyConnectOperation; QString uuid = "111111"; QString devName = "222"; classKyConnectOperation.activateConnection(uuid, devName); ASSERT_EQ(100, 100); } TEST_F(KyConnectOperationTest, deactivateConnection) { KyConnectOperation classKyConnectOperation; QString uuid = "111111"; QString devName = "222"; classKyConnectOperation.deactivateConnection(devName, uuid); ASSERT_EQ(100, 100); } kylin-nm/tests/unit_test_alltest/unit_test_kyvpnconnectoperation.cpp0000664000175000017500000001340615167651420025425 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kyvpnconnectoperation.h" using namespace stub_ext; class KyVpnConnectOperationTest : public testing::Test { protected: static void SetUpTestSuite() { } static void TearDownTestSuite() { } static QDBusInterface* m_pDBus; }; QDBusInterface *KyVpnConnectOperationTest::m_pDBus = nullptr; TEST_F(KyVpnConnectOperationTest, allParameter) { KyVpnConfig vpnConfig; vpnConfig.m_vpnName = ""; vpnConfig.m_gateway = ""; //VPN用户密码信息 vpnConfig.m_userName = ""; //用户密码 vpnConfig.m_userPasswd = ""; //密码策略 //NT域 vpnConfig.m_ntDomain = ""; //CA证书 vpnConfig.m_caCertificate = ""; //用户证书 vpnConfig.m_userCertificate = ""; //用户私钥 vpnConfig.m_userKey = ""; //静态密钥 vpnConfig.m_staticKey = ""; //用户私有密钥密码 vpnConfig.m_privatePasswd = ""; //密钥方向 vpnConfig.m_vpnKeyDir = ""; //本地IP地址 vpnConfig.m_localAddress = ""; //远程IP地址 vpnConfig.m_remoteAddress = ""; //PIN码 vpnConfig.m_pinId = ""; //MPPE加密开关 vpnConfig.m_mppeEnable = false; //使用有状态加密 vpnConfig.m_isAllowStatefulEncryption = false; //发送PPP回显包 vpnConfig.m_sendPppPackage = false; //MRU 最大接收单元 vpnConfig.m_mru = ""; //MTU 最大传输单元 vpnConfig.m_mtu = ""; //请求使用内部IP vpnConfig.m_virtual = ""; //强制UDP封装 vpnConfig.m_encap = ""; //使用IP压缩 vpnConfig.m_ipcomp = ""; //启用自定义密码建议 vpnConfig.m_proposal = ""; //IKE vpnConfig.m_ike = ""; //ESP vpnConfig.m_esp = ""; //使用自定义网关端口 vpnConfig.m_useAssignPort = ""; vpnConfig.m_assignPort = ""; //使用自定义重协商间隔 vpnConfig.m_useRenegSeconds = ""; vpnConfig.m_renegSeconds = ""; //使用压缩 vpnConfig.m_useCompress = ""; //使用TCP连接 vpnConfig.m_useTcpLink = ""; //设置虚拟设备类型 vpnConfig.m_setDevType = ""; //设置虚拟设备名称 vpnConfig.m_setDevName = ""; vpnConfig.m_devName = ""; //使用自定义隧道最大单元传输 vpnConfig.m_useTunnelMtu = ""; vpnConfig.m_tunnelMtu = ""; //使用自定义UDP分片大小 vpnConfig.m_useFragmentSize = ""; vpnConfig.m_fragmentSize = ""; //限制TCP最大段尺寸 vpnConfig.m_mssfix = ""; //随机化远程主机 vpnConfig.m_remoteRandom = ""; //IPv6 tun link vpnConfig.m_ipv6TunLink = ""; //指定Ping周期 vpnConfig.m_setPingCycle = ""; vpnConfig.m_pingCycle = ""; //指定退出或重启Ping vpnConfig.m_usePingMethod = ""; vpnConfig.m_pingMethodTime = ""; //接受来自任何地址(Float)已通过身份验证的数据包 vpnConfig.m_float = ""; //指定路由上限 vpnConfig.m_setMaxRoute = ""; vpnConfig.m_maxRoute = ""; //主题匹配 vpnConfig.m_verifyName = ""; //验证对等(服务器)证书用法签名 vpnConfig.m_useRemoteCertTls = ""; //验证对等(服务器)证书nsCertType签名 vpnConfig.m_useNsCertTls = ""; //密钥文件 vpnConfig.m_vpnKeyFile = ""; //密钥方向 vpnConfig.m_vpnTlsTaDir = ""; //服务器地址 vpnConfig.m_vpnProxyServer = ""; //端口 vpnConfig.m_vpnProxyPort = ""; //出错时无限重试 vpnConfig.m_vpnProxyRetry = ""; //代理用户名 vpnConfig.m_vpnProxyName = ""; //代理用户名 vpnConfig.m_vpnProxyPasswd = ""; vpnConfig.m_useKeysize = ""; vpnConfig.m_keySize = ""; vpnConfig.m_ipv4DhcpClientId = ""; ASSERT_EQ(100, 100); } TEST_F(KyVpnConnectOperationTest, createVpnConnect) { ASSERT_EQ(100, 100); } TEST_F(KyVpnConnectOperationTest, setVpnConfig) { ASSERT_EQ(100, 100); } TEST_F(KyVpnConnectOperationTest, getVpnConfig) { ASSERT_EQ(100, 100); } TEST_F(KyVpnConnectOperationTest, activateVpnConnection) { ASSERT_EQ(100, 100); } TEST_F(KyVpnConnectOperationTest, deactivateVpnConnection) { ASSERT_EQ(100, 100); } TEST_F(KyVpnConnectOperationTest, deleteVpnConnect) { ASSERT_EQ(100, 100); } TEST_F(KyVpnConnectOperationTest, getHmacAuthMethod) { ASSERT_EQ(100, 100); } TEST_F(KyVpnConnectOperationTest, getAuthMethod) { ASSERT_EQ(100, 100); } TEST_F(KyVpnConnectOperationTest, getConnectionSetting) { ASSERT_EQ(100, 100); } TEST_F(KyVpnConnectOperationTest, setConnectionSetting) { ASSERT_EQ(100, 100); } TEST_F(KyVpnConnectOperationTest, getUsrPasswdAndPolicy) { ASSERT_EQ(100, 100); } TEST_F(KyVpnConnectOperationTest, setUsrPasswdAndPolicy) { ASSERT_EQ(100, 100); } kylin-nm/tests/unit_test_alltest/unit_test_kylinutil.cpp0000664000175000017500000000466715167651420023020 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "stubext.h" #include "../../src/backend/dbus-interface/kylinutil.h" using namespace stub_ext; class KylinUtilInterfaceTest : public testing::Test { protected: static void SetUpTestSuite() { // m_pNetworkModeConfigDBus = new QDBusInterface("org.freedesktop.NetworkManager", // connectPath, // "org.freedesktop.NetworkManager.Settings.Connection", // QDBusConnection::systemBus()); } static void TearDownTestSuite() { // if (m_pNetworkModeConfigDBus) { // delete m_pNetworkModeConfigDBus; // m_pNetworkModeConfigDBus = nullptr; // } } static QDBusInterface* m_pNetworkModeConfigDBus; }; QDBusInterface *KylinUtilInterfaceTest::m_pNetworkModeConfigDBus = nullptr; TEST_F(KylinUtilInterfaceTest, getConnectTypeByDbus) { ASSERT_EQ(100, 100); } TEST_F(KylinUtilInterfaceTest, getSsidFromByteArray) { ASSERT_EQ(100, 100); } TEST_F(KylinUtilInterfaceTest, setWiredEnabledByGDbus) { ASSERT_EQ(100, 100); } TEST_F(KylinUtilInterfaceTest, setDeviceManagedByGDbus) { ASSERT_EQ(100, 100); } TEST_F(KylinUtilInterfaceTest, getConnectivityCheckSpareUriByGDbus) { ASSERT_EQ(100, 100); } TEST_F(KylinUtilInterfaceTest, setConnectivityCheckSpareUriByGDbus) { ASSERT_EQ(100, 100); } TEST_F(KylinUtilInterfaceTest, getWiredEnabledByGDbus) { ASSERT_EQ(100, 100); } kylin-nm/tests/kt-test-utils/0000775000175000017500000000000015167651420015140 5ustar fengfengkylin-nm/tests/kt-test-utils/cpp-stub/0000775000175000017500000000000015167651420016675 5ustar fengfengkylin-nm/tests/kt-test-utils/cpp-stub/addr_pri.h0000664000175000017500000002436415167651420020643 0ustar fengfeng#ifndef __ADDR_PRI_H__ #define __ADDR_PRI_H__ #include #include //base on C++11 /********************************************************** access private function **********************************************************/ namespace std { template using enable_if_t = typename enable_if::type; template using remove_reference_t = typename remove_reference::type; } // std // Unnamed namespace is used to avoid duplicate symbols if the macros are used namespace { namespace private_access_detail { // @tparam TagType, used to declare different "get" funciton overloads for // different members/statics template struct private_access { // Normal lookup cannot find in-class defined (inline) friend functions. friend PtrType get(TagType) { return PtrValue; } }; } // namespace private_access_detail } // namespace // Used macro naming conventions: // The "namespace" of this macro library is PRIVATE_ACCESS, i.e. all // macro here has this prefix. // All implementation macro, which are not meant to be used directly have the // PRIVATE_ACCESS_DETAIL prefix. // Some macros have the ABCD_IMPL form, which means they contain the // implementation details for the specific ABCD macro. #define PRIVATE_ACCESS_DETAIL_CONCATENATE_IMPL(x, y) x##y #define PRIVATE_ACCESS_DETAIL_CONCATENATE(x, y) \ PRIVATE_ACCESS_DETAIL_CONCATENATE_IMPL(x, y) // @param PtrTypeKind E.g if we have "class A", then it can be "A::*" in case of // members, or it can be "*" in case of statics. #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, \ PtrTypeKind) \ namespace { \ namespace private_access_detail { \ /* Tag type, used to declare different get funcitons for different \ * members \ */ \ struct Tag {}; \ /* Explicit instantiation */ \ template struct private_access; \ /* We can build the PtrType only with two aliases */ \ /* E.g. using PtrType = int(int) *; would be illformed */ \ using PRIVATE_ACCESS_DETAIL_CONCATENATE(Alias_, Tag) = Type; \ using PRIVATE_ACCESS_DETAIL_CONCATENATE(PtrType_, Tag) = \ PRIVATE_ACCESS_DETAIL_CONCATENATE(Alias_, Tag) PtrTypeKind; \ /* Declare the friend function, now it is visible in namespace scope. \ * Note, \ * we could declare it inside the Tag type too, in that case ADL would \ * find \ * the declaration. By choosing to declare it here, the Tag type remains \ * a \ * simple tag type, it has no other responsibilities. */ \ PRIVATE_ACCESS_DETAIL_CONCATENATE(PtrType_, Tag) get(Tag); \ } \ } #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_FIELD(Tag, Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, Class::*) \ namespace { \ namespace access_private_field { \ Type &Class##Name(Class &&t) { return t.*get(private_access_detail::Tag{}); } \ Type &Class##Name(Class &t) { return t.*get(private_access_detail::Tag{}); } \ /* The following usings are here to avoid duplicate const qualifier \ * warnings \ */ \ using PRIVATE_ACCESS_DETAIL_CONCATENATE(X, Tag) = Type; \ using PRIVATE_ACCESS_DETAIL_CONCATENATE(Y, Tag) = \ const PRIVATE_ACCESS_DETAIL_CONCATENATE(X, Tag); \ PRIVATE_ACCESS_DETAIL_CONCATENATE(Y, Tag) & Class##Name(const Class &t) {\ return t.*get(private_access_detail::Tag{}); \ } \ } \ } #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_FUN(Tag, Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, Class::*) \ namespace { \ namespace call_private_fun { \ /* We do perfect forwarding, but we want to restrict the overload set \ * only for objects which have the type Class. */ \ template , \ Class>::value> * = nullptr, \ typename... Args> \ auto Class##Name(Obj &&o, Args &&... args) -> decltype( \ (std::forward(o).* \ get(private_access_detail::Tag{}))(std::forward(args)...)) { \ return (std::forward(o).*get(private_access_detail::Tag{}))( \ std::forward(args)...); \ } \ } \ namespace get_private_fun { \ auto Class##Name() -> decltype( \ get(private_access_detail::Tag{})) { \ return (get(private_access_detail::Tag{})); \ } \ } \ } #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_STATIC_FIELD(Tag, Class, Type, \ Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, *) \ namespace { \ namespace access_private_static_field { \ namespace Class { \ Type &Class##Name() { return *get(private_access_detail::Tag{}); } \ } \ } \ } #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_STATIC_FUN(Tag, Class, Type, \ Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, *) \ namespace { \ namespace call_private_static_fun { \ namespace Class { \ template \ auto Class##Name(Args &&... args) -> decltype( \ get(private_access_detail::Tag{})(std::forward(args)...)) { \ return get(private_access_detail::Tag{})( \ std::forward(args)...); \ } \ } \ } \ namespace get_private_static_fun { \ namespace Class { \ auto Class##Name() -> decltype(get(private_access_detail::Tag{})) { \ return get(private_access_detail::Tag{}); \ } \ } \ } \ } #define PRIVATE_ACCESS_DETAIL_UNIQUE_TAG \ PRIVATE_ACCESS_DETAIL_CONCATENATE(PrivateAccessTag, __COUNTER__) #define ACCESS_PRIVATE_FIELD(Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_FIELD(PRIVATE_ACCESS_DETAIL_UNIQUE_TAG, \ Class, Type, Name) #define ACCESS_PRIVATE_FUN(Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_FUN(PRIVATE_ACCESS_DETAIL_UNIQUE_TAG, \ Class, Type, Name) #define ACCESS_PRIVATE_STATIC_FIELD(Class, Type, Name) \ Type Class::Name; \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_STATIC_FIELD( \ PRIVATE_ACCESS_DETAIL_UNIQUE_TAG, Class, Type, Name) #define ACCESS_PRIVATE_STATIC_FUN(Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_STATIC_FUN( \ PRIVATE_ACCESS_DETAIL_UNIQUE_TAG, Class, Type, Name) #endif kylin-nm/tests/kt-test-utils/cpp-stub/addr_any.h0000664000175000017500000002113415167651420020630 0ustar fengfeng#ifndef __ADDR_ANY_H__ #define __ADDR_ANY_H__ //linux #include #include //c #include #include #include //c++ #include #include //project #include "elfio.hpp" class AddrAny { public: AddrAny() { m_init = get_exe_pathname(m_fullname); m_baseaddr = 0; } AddrAny(std::string libname) { m_init = get_lib_pathname_and_baseaddr(libname, m_fullname, m_baseaddr); } int get_local_func_addr_symtab(std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_SYMTAB, STB_LOCAL, func_name_regex_str, result); } int get_global_func_addr_symtab(std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_SYMTAB, STB_GLOBAL, func_name_regex_str, result); } int get_weak_func_addr_symtab(std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_SYMTAB, STB_WEAK, func_name_regex_str, result); } int get_global_func_addr_dynsym( std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_DYNSYM, STB_GLOBAL, func_name_regex_str, result); } int get_weak_func_addr_dynsym(std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_DYNSYM, STB_WEAK, func_name_regex_str, result); } private: bool demangle(std::string& s, std::string& name) { int status; char* pname = abi::__cxa_demangle(s.c_str(), 0, 0, &status); if (status != 0) { switch(status) { case -1: name = "memory allocation error"; break; case -2: name = "invalid name given"; break; case -3: name = "internal error: __cxa_demangle: invalid argument"; break; default: name = "unknown error occured"; break; } return false; } name = pname; free(pname); return true; } bool get_exe_pathname( std::string& name) { char line[512]; FILE *fp; uintptr_t base_addr; char perm[5]; unsigned long offset; int pathname_pos; char *pathname; size_t pathname_len; int match = 0; if(NULL == (fp = fopen("/proc/self/maps", "r"))) { return false; } while(fgets(line, sizeof(line), fp)) { if(sscanf(line, "%" PRIxPTR "-%*lx %4s %lx %*x:%*x %*d%n", &base_addr, perm, &offset, &pathname_pos) != 3) continue; if(0 != offset) continue; //get pathname while(isspace(line[pathname_pos]) && pathname_pos < (int)(sizeof(line) - 1)) pathname_pos += 1; if(pathname_pos >= (int)(sizeof(line) - 1)) continue; pathname = line + pathname_pos; pathname_len = strlen(pathname); if(0 == pathname_len) continue; if(pathname[pathname_len - 1] == '\n') { pathname[pathname_len - 1] = '\0'; pathname_len -= 1; } if(0 == pathname_len) continue; if('[' == pathname[0]) continue; name = pathname; match = 1; break; } fclose(fp); if(0 == match) { return false; } else { return true; } } bool get_lib_pathname_and_baseaddr(std::string pathname_regex_str, std::string& name, unsigned long& addr) { char line[512]; FILE *fp; uintptr_t base_addr; char perm[5]; unsigned long offset; int pathname_pos; char *pathname; size_t pathname_len; int match; regex_t pathname_regex; regcomp(&pathname_regex, pathname_regex_str.c_str(), 0); if(NULL == (fp = fopen("/proc/self/maps", "r"))) { return false; } while(fgets(line, sizeof(line), fp)) { if(sscanf(line, "%" PRIxPTR "-%*lx %4s %lx %*x:%*x %*d%n", &base_addr, perm, &offset, &pathname_pos) != 3) continue; //check permission if(perm[0] != 'r') continue; if(perm[3] != 'p') continue; //do not touch the shared memory //check offset // //We are trying to find ELF header in memory. //It can only be found at the beginning of a mapped memory regions //whose offset is 0. if(0 != offset) continue; //get pathname while(isspace(line[pathname_pos]) && pathname_pos < (int)(sizeof(line) - 1)) pathname_pos += 1; if(pathname_pos >= (int)(sizeof(line) - 1)) continue; pathname = line + pathname_pos; pathname_len = strlen(pathname); if(0 == pathname_len) continue; if(pathname[pathname_len - 1] == '\n') { pathname[pathname_len - 1] = '\0'; pathname_len -= 1; } if(0 == pathname_len) continue; if('[' == pathname[0]) continue; //check pathname //if we need to hook this elf? match = 0; if(0 == regexec(&pathname_regex, pathname, 0, NULL, 0)) { match = 1; name = pathname; addr = (unsigned long)base_addr; break; } if(0 == match) continue; } fclose(fp); if(0 == match) { return false; } else { return true; } } int get_func_addr(unsigned int ttype, unsigned int stype, std::string& func_name_regex_str, std::map& result) { // Create an elfio reader ELFIO::elfio reader; int count = 0; regex_t pathname_regex; if(!m_init) { return -1; } regcomp(&pathname_regex, func_name_regex_str.c_str(), 0); // Load ELF data if(!reader.load(m_fullname.c_str())) { return -1; } ELFIO::Elf_Half sec_num = reader.sections.size(); for(int i = 0; i < sec_num; ++i) { ELFIO::section* psec = reader.sections[i]; // Check section type if(psec->get_type() == ttype) { const ELFIO::symbol_section_accessor symbols( reader, psec ); for ( unsigned int j = 0; j < symbols.get_symbols_num(); ++j ) { std::string name; std::string name_mangle; ELFIO::Elf64_Addr value; ELFIO::Elf_Xword size; unsigned char bind; unsigned char type; ELFIO::Elf_Half section_index; unsigned char other; // Read symbol properties symbols.get_symbol( j, name, value, size, bind, type, section_index, other ); if(type == STT_FUNC && bind == stype) { bool ret = demangle(name,name_mangle); if(ret == true) { if (0 == regexec(&pathname_regex, name_mangle.c_str(), 0, NULL, 0)) { result.insert ( std::pair(name_mangle,(void*)(value + m_baseaddr))); count++; } } else { if (0 == regexec(&pathname_regex, name.c_str(), 0, NULL, 0)) { result.insert ( std::pair(name,(void*)(value + m_baseaddr))); count++; } } } } break; } } return count; } private: bool m_init; std::string m_name; std::string m_fullname; unsigned long m_baseaddr; }; #endif kylin-nm/tests/kt-test-utils/cpp-stub/elfio.hpp0000664000175000017500000045310415167651420020513 0ustar fengfeng /*** Start of inlined file: elfio_dump.hpp ***/ #ifndef ELFIO_DUMP_HPP #define ELFIO_DUMP_HPP #include #include #include #include #include /*** Start of inlined file: elfio.hpp ***/ #ifndef ELFIO_HPP #define ELFIO_HPP #ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable : 4996 ) #pragma warning( disable : 4355 ) #pragma warning( disable : 4244 ) #endif #include #include #include #include #include #include #include #include /*** Start of inlined file: elf_types.hpp ***/ #ifndef ELFTYPES_H #define ELFTYPES_H #ifndef ELFIO_NO_OWN_TYPES #if !defined( ELFIO_NO_CSTDINT ) && !defined( ELFIO_NO_INTTYPES ) #include #else typedef unsigned char uint8_t; typedef signed char int8_t; typedef unsigned short uint16_t; typedef signed short int16_t; #ifdef _MSC_VER typedef unsigned __int32 uint32_t; typedef signed __int32 int32_t; typedef unsigned __int64 uint64_t; typedef signed __int64 int64_t; #else typedef unsigned int uint32_t; typedef signed int int32_t; typedef unsigned long long uint64_t; typedef signed long long int64_t; #endif // _MSC_VER #endif // ELFIO_NO_CSTDINT #endif // ELFIO_NO_OWN_TYPES namespace ELFIO { // Attention! Platform depended definitions. typedef uint16_t Elf_Half; typedef uint32_t Elf_Word; typedef int32_t Elf_Sword; typedef uint64_t Elf_Xword; typedef int64_t Elf_Sxword; typedef uint32_t Elf32_Addr; typedef uint32_t Elf32_Off; typedef uint64_t Elf64_Addr; typedef uint64_t Elf64_Off; #define Elf32_Half Elf_Half #define Elf64_Half Elf_Half #define Elf32_Word Elf_Word #define Elf64_Word Elf_Word #define Elf32_Sword Elf_Sword #define Elf64_Sword Elf_Sword /////////////////////// // ELF Header Constants // File type #define ET_NONE 0 #define ET_REL 1 #define ET_EXEC 2 #define ET_DYN 3 #define ET_CORE 4 #define ET_LOOS 0xFE00 #define ET_HIOS 0xFEFF #define ET_LOPROC 0xFF00 #define ET_HIPROC 0xFFFF #define EM_NONE 0 // No machine #define EM_M32 1 // AT&T WE 32100 #define EM_SPARC 2 // SUN SPARC #define EM_386 3 // Intel 80386 #define EM_68K 4 // Motorola m68k family #define EM_88K 5 // Motorola m88k family #define EM_486 6 // Intel 80486// Reserved for future use #define EM_860 7 // Intel 80860 #define EM_MIPS 8 // MIPS R3000 (officially, big-endian only) #define EM_S370 9 // IBM System/370 #define EM_MIPS_RS3_LE \ 10 // MIPS R3000 little-endian (Oct 4 1999 Draft) Deprecated #define EM_res011 11 // Reserved #define EM_res012 12 // Reserved #define EM_res013 13 // Reserved #define EM_res014 14 // Reserved #define EM_PARISC 15 // HPPA #define EM_res016 16 // Reserved #define EM_VPP550 17 // Fujitsu VPP500 #define EM_SPARC32PLUS 18 // Sun's "v8plus" #define EM_960 19 // Intel 80960 #define EM_PPC 20 // PowerPC #define EM_PPC64 21 // 64-bit PowerPC #define EM_S390 22 // IBM S/390 #define EM_SPU 23 // Sony/Toshiba/IBM SPU #define EM_res024 24 // Reserved #define EM_res025 25 // Reserved #define EM_res026 26 // Reserved #define EM_res027 27 // Reserved #define EM_res028 28 // Reserved #define EM_res029 29 // Reserved #define EM_res030 30 // Reserved #define EM_res031 31 // Reserved #define EM_res032 32 // Reserved #define EM_res033 33 // Reserved #define EM_res034 34 // Reserved #define EM_res035 35 // Reserved #define EM_V800 36 // NEC V800 series #define EM_FR20 37 // Fujitsu FR20 #define EM_RH32 38 // TRW RH32 #define EM_MCORE 39 // Motorola M*Core // May also be taken by Fujitsu MMA #define EM_RCE 39 // Old name for MCore #define EM_ARM 40 // ARM #define EM_OLD_ALPHA 41 // Digital Alpha #define EM_SH 42 // Renesas (formerly Hitachi) / SuperH SH #define EM_SPARCV9 43 // SPARC v9 64-bit #define EM_TRICORE 44 // Siemens Tricore embedded processor #define EM_ARC 45 // ARC Cores #define EM_H8_300 46 // Renesas (formerly Hitachi) H8/300 #define EM_H8_300H 47 // Renesas (formerly Hitachi) H8/300H #define EM_H8S 48 // Renesas (formerly Hitachi) H8S #define EM_H8_500 49 // Renesas (formerly Hitachi) H8/500 #define EM_IA_64 50 // Intel IA-64 Processor #define EM_MIPS_X 51 // Stanford MIPS-X #define EM_COLDFIRE 52 // Motorola Coldfire #define EM_68HC12 53 // Motorola M68HC12 #define EM_MMA 54 // Fujitsu Multimedia Accelerator #define EM_PCP 55 // Siemens PCP #define EM_NCPU 56 // Sony nCPU embedded RISC processor #define EM_NDR1 57 // Denso NDR1 microprocesspr #define EM_STARCORE 58 // Motorola Star*Core processor #define EM_ME16 59 // Toyota ME16 processor #define EM_ST100 60 // STMicroelectronics ST100 processor #define EM_TINYJ 61 // Advanced Logic Corp. TinyJ embedded processor #define EM_X86_64 62 // Advanced Micro Devices X86-64 processor #define EM_PDSP 63 // Sony DSP Processor #define EM_PDP10 64 // Digital Equipment Corp. PDP-10 #define EM_PDP11 65 // Digital Equipment Corp. PDP-11 #define EM_FX66 66 // Siemens FX66 microcontroller #define EM_ST9PLUS 67 // STMicroelectronics ST9+ 8/16 bit microcontroller #define EM_ST7 68 // STMicroelectronics ST7 8-bit microcontroller #define EM_68HC16 69 // Motorola MC68HC16 Microcontroller #define EM_68HC11 70 // Motorola MC68HC11 Microcontroller #define EM_68HC08 71 // Motorola MC68HC08 Microcontroller #define EM_68HC05 72 // Motorola MC68HC05 Microcontroller #define EM_SVX 73 // Silicon Graphics SVx #define EM_ST19 74 // STMicroelectronics ST19 8-bit cpu #define EM_VAX 75 // Digital VAX #define EM_CRIS 76 // Axis Communications 32-bit embedded processor #define EM_JAVELIN 77 // Infineon Technologies 32-bit embedded cpu #define EM_FIREPATH 78 // Element 14 64-bit DSP processor #define EM_ZSP 79 // LSI Logic's 16-bit DSP processor #define EM_MMIX 80 // Donald Knuth's educational 64-bit processor #define EM_HUANY 81 // Harvard's machine-independent format #define EM_PRISM 82 // SiTera Prism #define EM_AVR 83 // Atmel AVR 8-bit microcontroller #define EM_FR30 84 // Fujitsu FR30 #define EM_D10V 85 // Mitsubishi D10V #define EM_D30V 86 // Mitsubishi D30V #define EM_V850 87 // NEC v850 #define EM_M32R 88 // Renesas M32R (formerly Mitsubishi M32R) #define EM_MN10300 89 // Matsushita MN10300 #define EM_MN10200 90 // Matsushita MN10200 #define EM_PJ 91 // picoJava #define EM_OPENRISC 92 // OpenRISC 32-bit embedded processor #define EM_ARC_A5 93 // ARC Cores Tangent-A5 #define EM_XTENSA 94 // Tensilica Xtensa Architecture #define EM_VIDEOCORE 95 // Alphamosaic VideoCore processor #define EM_TMM_GPP 96 // Thompson Multimedia General Purpose Processor #define EM_NS32K 97 // National Semiconductor 32000 series #define EM_TPC 98 // Tenor Network TPC processor #define EM_SNP1K 99 // Trebia SNP 1000 processor #define EM_ST200 100 // STMicroelectronics ST200 microcontroller #define EM_IP2K 101 // Ubicom IP2022 micro controller #define EM_MAX 102 // MAX Processor #define EM_CR 103 // National Semiconductor CompactRISC #define EM_F2MC16 104 // Fujitsu F2MC16 #define EM_MSP430 105 // TI msp430 micro controller #define EM_BLACKFIN 106 // ADI Blackfin #define EM_SE_C33 107 // S1C33 Family of Seiko Epson processors #define EM_SEP 108 // Sharp embedded microprocessor #define EM_ARCA 109 // Arca RISC Microprocessor #define EM_UNICORE \ 110 // Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University #define EM_EXCESS 111 // eXcess: 16/32/64-bit configurable embedded CPU #define EM_DXP 112 // Icera Semiconductor Inc. Deep Execution Processor #define EM_ALTERA_NIOS2 113 // Altera Nios II soft-core processor #define EM_CRX 114 // National Semiconductor CRX #define EM_XGATE 115 // Motorola XGATE embedded processor #define EM_C166 116 // Infineon C16x/XC16x processor #define EM_M16C 117 // Renesas M16C series microprocessors #define EM_DSPIC30F \ 118 // Microchip Technology dsPIC30F Digital Signal Controller #define EM_CE 119 // Freescale Communication Engine RISC core #define EM_M32C 120 // Renesas M32C series microprocessors #define EM_res121 121 // Reserved #define EM_res122 122 // Reserved #define EM_res123 123 // Reserved #define EM_res124 124 // Reserved #define EM_res125 125 // Reserved #define EM_res126 126 // Reserved #define EM_res127 127 // Reserved #define EM_res128 128 // Reserved #define EM_res129 129 // Reserved #define EM_res130 130 // Reserved #define EM_TSK3000 131 // Altium TSK3000 core #define EM_RS08 132 // Freescale RS08 embedded processor #define EM_res133 133 // Reserved #define EM_ECOG2 134 // Cyan Technology eCOG2 microprocessor #define EM_SCORE 135 // Sunplus Score #define EM_SCORE7 135 // Sunplus S+core7 RISC processor #define EM_DSP24 136 // New Japan Radio (NJR) 24-bit DSP Processor #define EM_VIDEOCORE3 137 // Broadcom VideoCore III processor #define EM_LATTICEMICO32 138 // RISC processor for Lattice FPGA architecture #define EM_SE_C17 139 // Seiko Epson C17 family #define EM_TI_C6000 140 // Texas Instruments TMS320C6000 DSP family #define EM_TI_C2000 141 // Texas Instruments TMS320C2000 DSP family #define EM_TI_C5500 142 // Texas Instruments TMS320C55x DSP family #define EM_res143 143 // Reserved #define EM_res144 144 // Reserved #define EM_res145 145 // Reserved #define EM_res146 146 // Reserved #define EM_res147 147 // Reserved #define EM_res148 148 // Reserved #define EM_res149 149 // Reserved #define EM_res150 150 // Reserved #define EM_res151 151 // Reserved #define EM_res152 152 // Reserved #define EM_res153 153 // Reserved #define EM_res154 154 // Reserved #define EM_res155 155 // Reserved #define EM_res156 156 // Reserved #define EM_res157 157 // Reserved #define EM_res158 158 // Reserved #define EM_res159 159 // Reserved #define EM_MMDSP_PLUS 160 // STMicroelectronics 64bit VLIW Data Signal Processor #define EM_CYPRESS_M8C 161 // Cypress M8C microprocessor #define EM_R32C 162 // Renesas R32C series microprocessors #define EM_TRIMEDIA 163 // NXP Semiconductors TriMedia architecture family #define EM_QDSP6 164 // QUALCOMM DSP6 Processor #define EM_8051 165 // Intel 8051 and variants #define EM_STXP7X 166 // STMicroelectronics STxP7x family #define EM_NDS32 \ 167 // Andes Technology compact code size embedded RISC processor family #define EM_ECOG1 168 // Cyan Technology eCOG1X family #define EM_ECOG1X 168 // Cyan Technology eCOG1X family #define EM_MAXQ30 169 // Dallas Semiconductor MAXQ30 Core Micro-controllers #define EM_XIMO16 170 // New Japan Radio (NJR) 16-bit DSP Processor #define EM_MANIK 171 // M2000 Reconfigurable RISC Microprocessor #define EM_CRAYNV2 172 // Cray Inc. NV2 vector architecture #define EM_RX 173 // Renesas RX family #define EM_METAG 174 // Imagination Technologies META processor architecture #define EM_MCST_ELBRUS 175 // MCST Elbrus general purpose hardware architecture #define EM_ECOG16 176 // Cyan Technology eCOG16 family #define EM_CR16 177 // National Semiconductor CompactRISC 16-bit processor #define EM_ETPU 178 // Freescale Extended Time Processing Unit #define EM_SLE9X 179 // Infineon Technologies SLE9X core #define EM_L1OM 180 // Intel L1OM #define EM_INTEL181 181 // Reserved by Intel #define EM_INTEL182 182 // Reserved by Intel #define EM_res183 183 // Reserved by ARM #define EM_res184 184 // Reserved by ARM #define EM_AVR32 185 // Atmel Corporation 32-bit microprocessor family #define EM_STM8 186 // STMicroeletronics STM8 8-bit microcontroller #define EM_TILE64 187 // Tilera TILE64 multicore architecture family #define EM_TILEPRO 188 // Tilera TILEPro multicore architecture family #define EM_MICROBLAZE 189 // Xilinx MicroBlaze 32-bit RISC soft processor core #define EM_CUDA 190 // NVIDIA CUDA architecture #define EM_TILEGX 191 // Tilera TILE-Gx multicore architecture family #define EM_CLOUDSHIELD 192 // CloudShield architecture family #define EM_COREA_1ST 193 // KIPO-KAIST Core-A 1st generation processor family #define EM_COREA_2ND 194 // KIPO-KAIST Core-A 2nd generation processor family #define EM_ARC_COMPACT2 195 // Synopsys ARCompact V2 #define EM_OPEN8 196 // Open8 8-bit RISC soft processor core #define EM_RL78 197 // Renesas RL78 family #define EM_VIDEOCORE5 198 // Broadcom VideoCore V processor #define EM_78KOR 199 // Renesas 78KOR family #define EM_56800EX 200 // Freescale 56800EX Digital Signal Controller (DSC) #define EM_BA1 201 // Beyond BA1 CPU architecture #define EM_BA2 202 // Beyond BA2 CPU architecture #define EM_XCORE 203 // XMOS xCORE processor family #define EM_MCHP_PIC 204 // Microchip 8-bit PIC(r) family #define EM_INTEL205 205 // Reserved by Intel #define EM_INTEL206 206 // Reserved by Intel #define EM_INTEL207 207 // Reserved by Intel #define EM_INTEL208 208 // Reserved by Intel #define EM_INTEL209 209 // Reserved by Intel #define EM_KM32 210 // KM211 KM32 32-bit processor #define EM_KMX32 211 // KM211 KMX32 32-bit processor #define EM_KMX16 212 // KM211 KMX16 16-bit processor #define EM_KMX8 213 // KM211 KMX8 8-bit processor #define EM_KVARC 214 // KM211 KVARC processor #define EM_CDP 215 // Paneve CDP architecture family #define EM_COGE 216 // Cognitive Smart Memory Processor #define EM_COOL 217 // iCelero CoolEngine #define EM_NORC 218 // Nanoradio Optimized RISC #define EM_CSR_KALIMBA 219 // CSR Kalimba architecture family #define EM_Z80 220 // Zilog Z80 #define EM_VISIUM 221 // Controls and Data Services VISIUMcore processor #define EM_FT32 222 // FTDI Chip FT32 high performance 32-bit RISC architecture #define EM_MOXIE 223 // Moxie processor family #define EM_AMDGPU 224 // AMD GPU architecture #define EM_RISCV 243 // RISC-V #define EM_LANAI 244 // Lanai processor #define EM_CEVA 245 // CEVA Processor Architecture Family #define EM_CEVA_X2 246 // CEVA X2 Processor Family #define EM_BPF 247 // Linux BPF – in-kernel virtual machine #define EM_GRAPHCORE_IPU 248 // Graphcore Intelligent Processing Unit #define EM_IMG1 249 // Imagination Technologies #define EM_NFP 250 // Netronome Flow Processor (P) #define EM_CSKY 252 // C-SKY processor family // File version #define EV_NONE 0 #define EV_CURRENT 1 // Identification index #define EI_MAG0 0 #define EI_MAG1 1 #define EI_MAG2 2 #define EI_MAG3 3 #define EI_CLASS 4 #define EI_DATA 5 #define EI_VERSION 6 #define EI_OSABI 7 #define EI_ABIVERSION 8 #define EI_PAD 9 #define EI_NIDENT 16 // Magic number #define ELFMAG0 0x7F #define ELFMAG1 'E' #define ELFMAG2 'L' #define ELFMAG3 'F' // File class #define ELFCLASSNONE 0 #define ELFCLASS32 1 #define ELFCLASS64 2 // Encoding #define ELFDATANONE 0 #define ELFDATA2LSB 1 #define ELFDATA2MSB 2 // OS extensions #define ELFOSABI_NONE 0 // No extensions or unspecified #define ELFOSABI_HPUX 1 // Hewlett-Packard HP-UX #define ELFOSABI_NETBSD 2 // NetBSD #define ELFOSABI_LINUX 3 // Linux #define ELFOSABI_SOLARIS 6 // Sun Solaris #define ELFOSABI_AIX 7 // AIX #define ELFOSABI_IRIX 8 // IRIX #define ELFOSABI_FREEBSD 9 // FreeBSD #define ELFOSABI_TRU64 10 // Compaq TRU64 UNIX #define ELFOSABI_MODESTO 11 // Novell Modesto #define ELFOSABI_OPENBSD 12 // Open BSD #define ELFOSABI_OPENVMS 13 // Open VMS #define ELFOSABI_NSK 14 // Hewlett-Packard Non-Stop Kernel #define ELFOSABI_AROS 15 // Amiga Research OS #define ELFOSABI_FENIXOS 16 // The FenixOS highly scalable multi-core OS // 64-255 Architecture-specific value range #define ELFOSABI_AMDGPU_HSA \ 64 // AMDGPU OS for HSA compatible compute // kernels. #define ELFOSABI_AMDGPU_PAL \ 65 // AMDGPU OS for AMD PAL compatible graphics // shaders and compute kernels. #define ELFOSABI_AMDGPU_MESA3D \ 66 // AMDGPU OS for Mesa3D compatible graphics // shaders and compute kernels. // AMDGPU specific e_flags #define EF_AMDGPU_MACH 0x0ff // AMDGPU processor selection mask. #define EF_AMDGPU_XNACK \ 0x100 // Indicates if the XNACK target feature is // enabled for all code contained in the ELF. // AMDGPU processors #define EF_AMDGPU_MACH_NONE 0x000 // Unspecified processor. #define EF_AMDGPU_MACH_R600_R600 0x001 #define EF_AMDGPU_MACH_R600_R630 0x002 #define EF_AMDGPU_MACH_R600_RS880 0x003 #define EF_AMDGPU_MACH_R600_RV670 0x004 #define EF_AMDGPU_MACH_R600_RV710 0x005 #define EF_AMDGPU_MACH_R600_RV730 0x006 #define EF_AMDGPU_MACH_R600_RV770 0x007 #define EF_AMDGPU_MACH_R600_CEDAR 0x008 #define EF_AMDGPU_MACH_R600_CYPRESS 0x009 #define EF_AMDGPU_MACH_R600_JUNIPER 0x00a #define EF_AMDGPU_MACH_R600_REDWOOD 0x00b #define EF_AMDGPU_MACH_R600_SUMO 0x00c #define EF_AMDGPU_MACH_R600_BARTS 0x00d #define EF_AMDGPU_MACH_R600_CAICOS 0x00e #define EF_AMDGPU_MACH_R600_CAYMAN 0x00f #define EF_AMDGPU_MACH_R600_TURKS 0x010 #define EF_AMDGPU_MACH_R600_RESERVED_FIRST 0x011 #define EF_AMDGPU_MACH_R600_RESERVED_LAST 0x01f #define EF_AMDGPU_MACH_R600_FIRST EF_AMDGPU_MACH_R600_R600 #define EF_AMDGPU_MACH_R600_LAST EF_AMDGPU_MACH_R600_TURKS #define EF_AMDGPU_MACH_AMDGCN_GFX600 0x020 #define EF_AMDGPU_MACH_AMDGCN_GFX601 0x021 #define EF_AMDGPU_MACH_AMDGCN_GFX700 0x022 #define EF_AMDGPU_MACH_AMDGCN_GFX701 0x023 #define EF_AMDGPU_MACH_AMDGCN_GFX702 0x024 #define EF_AMDGPU_MACH_AMDGCN_GFX703 0x025 #define EF_AMDGPU_MACH_AMDGCN_GFX704 0x026 #define EF_AMDGPU_MACH_AMDGCN_GFX801 0x028 #define EF_AMDGPU_MACH_AMDGCN_GFX802 0x029 #define EF_AMDGPU_MACH_AMDGCN_GFX803 0x02a #define EF_AMDGPU_MACH_AMDGCN_GFX810 0x02b #define EF_AMDGPU_MACH_AMDGCN_GFX900 0x02c #define EF_AMDGPU_MACH_AMDGCN_GFX902 0x02d #define EF_AMDGPU_MACH_AMDGCN_GFX904 0x02e #define EF_AMDGPU_MACH_AMDGCN_GFX906 0x02f #define EF_AMDGPU_MACH_AMDGCN_RESERVED0 0x027 #define EF_AMDGPU_MACH_AMDGCN_RESERVED1 0x030 #define EF_AMDGPU_MACH_AMDGCN_FIRST EF_AMDGPU_MACH_AMDGCN_GFX600 #define EF_AMDGPU_MACH_AMDGCN_LAST EF_AMDGPU_MACH_AMDGCN_GFX906 ///////////////////// // Sections constants // Section indexes #define SHN_UNDEF 0 #define SHN_LORESERVE 0xFF00 #define SHN_LOPROC 0xFF00 #define SHN_HIPROC 0xFF1F #define SHN_LOOS 0xFF20 #define SHN_HIOS 0xFF3F #define SHN_ABS 0xFFF1 #define SHN_COMMON 0xFFF2 #define SHN_XINDEX 0xFFFF #define SHN_HIRESERVE 0xFFFF // Section types #define SHT_NULL 0 #define SHT_PROGBITS 1 #define SHT_SYMTAB 2 #define SHT_STRTAB 3 #define SHT_RELA 4 #define SHT_HASH 5 #define SHT_DYNAMIC 6 #define SHT_NOTE 7 #define SHT_NOBITS 8 #define SHT_REL 9 #define SHT_SHLIB 10 #define SHT_DYNSYM 11 #define SHT_INIT_ARRAY 14 #define SHT_FINI_ARRAY 15 #define SHT_PREINIT_ARRAY 16 #define SHT_GROUP 17 #define SHT_SYMTAB_SHNDX 18 #define SHT_LOOS 0x60000000 #define SHT_HIOS 0x6fffffff #define SHT_LOPROC 0x70000000 #define SHT_HIPROC 0x7FFFFFFF #define SHT_LOUSER 0x80000000 #define SHT_HIUSER 0xFFFFFFFF // Section attribute flags #define SHF_WRITE 0x1 #define SHF_ALLOC 0x2 #define SHF_EXECINSTR 0x4 #define SHF_MERGE 0x10 #define SHF_STRINGS 0x20 #define SHF_INFO_LINK 0x40 #define SHF_LINK_ORDER 0x80 #define SHF_OS_NONCONFORMING 0x100 #define SHF_GROUP 0x200 #define SHF_TLS 0x400 #define SHF_MASKOS 0x0ff00000 #define SHF_MASKPROC 0xF0000000 // Section group flags #define GRP_COMDAT 0x1 #define GRP_MASKOS 0x0ff00000 #define GRP_MASKPROC 0xf0000000 // Symbol binding #define STB_LOCAL 0 #define STB_GLOBAL 1 #define STB_WEAK 2 #define STB_LOOS 10 #define STB_HIOS 12 #define STB_MULTIDEF 13 #define STB_LOPROC 13 #define STB_HIPROC 15 // Note types #define NT_AMDGPU_METADATA 1 #define NT_AMD_AMDGPU_HSA_METADATA 10 #define NT_AMD_AMDGPU_ISA 11 #define NT_AMD_AMDGPU_PAL_METADATA 12 // Symbol types #define STT_NOTYPE 0 #define STT_OBJECT 1 #define STT_FUNC 2 #define STT_SECTION 3 #define STT_FILE 4 #define STT_COMMON 5 #define STT_TLS 6 #define STT_LOOS 10 #define STT_AMDGPU_HSA_KERNEL 10 #define STT_HIOS 12 #define STT_LOPROC 13 #define STT_HIPROC 15 // Symbol visibility #define STV_DEFAULT 0 #define STV_INTERNAL 1 #define STV_HIDDEN 2 #define STV_PROTECTED 3 // Undefined name #define STN_UNDEF 0 // Relocation types #define R_386_NONE 0 #define R_X86_64_NONE 0 #define R_AMDGPU_NONE 0 #define R_386_32 1 #define R_X86_64_64 1 #define R_AMDGPU_ABS32_LO 1 #define R_386_PC32 2 #define R_X86_64_PC32 2 #define R_AMDGPU_ABS32_HI 2 #define R_386_GOT32 3 #define R_X86_64_GOT32 3 #define R_AMDGPU_ABS64 3 #define R_386_PLT32 4 #define R_X86_64_PLT32 4 #define R_AMDGPU_REL32 4 #define R_386_COPY 5 #define R_X86_64_COPY 5 #define R_AMDGPU_REL64 5 #define R_386_GLOB_DAT 6 #define R_X86_64_GLOB_DAT 6 #define R_AMDGPU_ABS32 6 #define R_386_JMP_SLOT 7 #define R_X86_64_JUMP_SLOT 7 #define R_AMDGPU_GOTPCREL 7 #define R_386_RELATIVE 8 #define R_X86_64_RELATIVE 8 #define R_AMDGPU_GOTPCREL32_LO 8 #define R_386_GOTOFF 9 #define R_X86_64_GOTPCREL 9 #define R_AMDGPU_GOTPCREL32_HI 9 #define R_386_GOTPC 10 #define R_X86_64_32 10 #define R_AMDGPU_REL32_LO 10 #define R_386_32PLT 11 #define R_X86_64_32S 11 #define R_AMDGPU_REL32_HI 11 #define R_X86_64_16 12 #define R_X86_64_PC16 13 #define R_AMDGPU_RELATIVE64 13 #define R_386_TLS_TPOFF 14 #define R_X86_64_8 14 #define R_386_TLS_IE 15 #define R_X86_64_PC8 15 #define R_386_TLS_GOTIE 16 #define R_X86_64_DTPMOD64 16 #define R_386_TLS_LE 17 #define R_X86_64_DTPOFF64 17 #define R_386_TLS_GD 18 #define R_X86_64_TPOFF64 18 #define R_386_TLS_LDM 19 #define R_X86_64_TLSGD 19 #define R_386_16 20 #define R_X86_64_TLSLD 20 #define R_386_PC16 21 #define R_X86_64_DTPOFF32 21 #define R_386_8 22 #define R_X86_64_GOTTPOFF 22 #define R_386_PC8 23 #define R_X86_64_TPOFF32 23 #define R_386_TLS_GD_32 24 #define R_X86_64_PC64 24 #define R_386_TLS_GD_PUSH 25 #define R_X86_64_GOTOFF64 25 #define R_386_TLS_GD_CALL 26 #define R_X86_64_GOTPC32 26 #define R_386_TLS_GD_POP 27 #define R_X86_64_GOT64 27 #define R_386_TLS_LDM_32 28 #define R_X86_64_GOTPCREL64 28 #define R_386_TLS_LDM_PUSH 29 #define R_X86_64_GOTPC64 29 #define R_386_TLS_LDM_CALL 30 #define R_X86_64_GOTPLT64 30 #define R_386_TLS_LDM_POP 31 #define R_X86_64_PLTOFF64 31 #define R_386_TLS_LDO_32 32 #define R_386_TLS_IE_32 33 #define R_386_TLS_LE_32 34 #define R_X86_64_GOTPC32_TLSDESC 34 #define R_386_TLS_DTPMOD32 35 #define R_X86_64_TLSDESC_CALL 35 #define R_386_TLS_DTPOFF32 36 #define R_X86_64_TLSDESC 36 #define R_386_TLS_TPOFF32 37 #define R_X86_64_IRELATIVE 37 #define R_386_SIZE32 38 #define R_386_TLS_GOTDESC 39 #define R_386_TLS_DESC_CALL 40 #define R_386_TLS_DESC 41 #define R_386_IRELATIVE 42 #define R_386_GOT32X 43 #define R_X86_64_GNU_VTINHERIT 250 #define R_X86_64_GNU_VTENTRY 251 // Segment types #define PT_NULL 0 #define PT_LOAD 1 #define PT_DYNAMIC 2 #define PT_INTERP 3 #define PT_NOTE 4 #define PT_SHLIB 5 #define PT_PHDR 6 #define PT_TLS 7 #define PT_LOOS 0x60000000 #define PT_HIOS 0x6fffffff #define PT_LOPROC 0x70000000 #define PT_HIPROC 0x7FFFFFFF // Segment flags #define PF_X 1 // Execute #define PF_W 2 // Write #define PF_R 4 // Read #define PF_MASKOS 0x0ff00000 // Unspecified #define PF_MASKPROC 0xf0000000 // Unspecified // Dynamic Array Tags #define DT_NULL 0 #define DT_NEEDED 1 #define DT_PLTRELSZ 2 #define DT_PLTGOT 3 #define DT_HASH 4 #define DT_STRTAB 5 #define DT_SYMTAB 6 #define DT_RELA 7 #define DT_RELASZ 8 #define DT_RELAENT 9 #define DT_STRSZ 10 #define DT_SYMENT 11 #define DT_INIT 12 #define DT_FINI 13 #define DT_SONAME 14 #define DT_RPATH 15 #define DT_SYMBOLIC 16 #define DT_REL 17 #define DT_RELSZ 18 #define DT_RELENT 19 #define DT_PLTREL 20 #define DT_DEBUG 21 #define DT_TEXTREL 22 #define DT_JMPREL 23 #define DT_BIND_NOW 24 #define DT_INIT_ARRAY 25 #define DT_FINI_ARRAY 26 #define DT_INIT_ARRAYSZ 27 #define DT_FINI_ARRAYSZ 28 #define DT_RUNPATH 29 #define DT_FLAGS 30 #define DT_ENCODING 32 #define DT_PREINIT_ARRAY 32 #define DT_PREINIT_ARRAYSZ 33 #define DT_MAXPOSTAGS 34 #define DT_LOOS 0x6000000D #define DT_HIOS 0x6ffff000 #define DT_LOPROC 0x70000000 #define DT_HIPROC 0x7FFFFFFF // DT_FLAGS values #define DF_ORIGIN 0x1 #define DF_SYMBOLIC 0x2 #define DF_TEXTREL 0x4 #define DF_BIND_NOW 0x8 #define DF_STATIC_TLS 0x10 // ELF file header struct Elf32_Ehdr { unsigned char e_ident[EI_NIDENT]; Elf_Half e_type; Elf_Half e_machine; Elf_Word e_version; Elf32_Addr e_entry; Elf32_Off e_phoff; Elf32_Off e_shoff; Elf_Word e_flags; Elf_Half e_ehsize; Elf_Half e_phentsize; Elf_Half e_phnum; Elf_Half e_shentsize; Elf_Half e_shnum; Elf_Half e_shstrndx; }; struct Elf64_Ehdr { unsigned char e_ident[EI_NIDENT]; Elf_Half e_type; Elf_Half e_machine; Elf_Word e_version; Elf64_Addr e_entry; Elf64_Off e_phoff; Elf64_Off e_shoff; Elf_Word e_flags; Elf_Half e_ehsize; Elf_Half e_phentsize; Elf_Half e_phnum; Elf_Half e_shentsize; Elf_Half e_shnum; Elf_Half e_shstrndx; }; // Section header struct Elf32_Shdr { Elf_Word sh_name; Elf_Word sh_type; Elf_Word sh_flags; Elf32_Addr sh_addr; Elf32_Off sh_offset; Elf_Word sh_size; Elf_Word sh_link; Elf_Word sh_info; Elf_Word sh_addralign; Elf_Word sh_entsize; }; struct Elf64_Shdr { Elf_Word sh_name; Elf_Word sh_type; Elf_Xword sh_flags; Elf64_Addr sh_addr; Elf64_Off sh_offset; Elf_Xword sh_size; Elf_Word sh_link; Elf_Word sh_info; Elf_Xword sh_addralign; Elf_Xword sh_entsize; }; // Segment header struct Elf32_Phdr { Elf_Word p_type; Elf32_Off p_offset; Elf32_Addr p_vaddr; Elf32_Addr p_paddr; Elf_Word p_filesz; Elf_Word p_memsz; Elf_Word p_flags; Elf_Word p_align; }; struct Elf64_Phdr { Elf_Word p_type; Elf_Word p_flags; Elf64_Off p_offset; Elf64_Addr p_vaddr; Elf64_Addr p_paddr; Elf_Xword p_filesz; Elf_Xword p_memsz; Elf_Xword p_align; }; // Symbol table entry struct Elf32_Sym { Elf_Word st_name; Elf32_Addr st_value; Elf_Word st_size; unsigned char st_info; unsigned char st_other; Elf_Half st_shndx; }; struct Elf64_Sym { Elf_Word st_name; unsigned char st_info; unsigned char st_other; Elf_Half st_shndx; Elf64_Addr st_value; Elf_Xword st_size; }; #define ELF_ST_BIND( i ) ( ( i ) >> 4 ) #define ELF_ST_TYPE( i ) ( (i)&0xf ) #define ELF_ST_INFO( b, t ) ( ( ( b ) << 4 ) + ( (t)&0xf ) ) #define ELF_ST_VISIBILITY( o ) ( (o)&0x3 ) // Relocation entries struct Elf32_Rel { Elf32_Addr r_offset; Elf_Word r_info; }; struct Elf32_Rela { Elf32_Addr r_offset; Elf_Word r_info; Elf_Sword r_addend; }; struct Elf64_Rel { Elf64_Addr r_offset; Elf_Xword r_info; }; struct Elf64_Rela { Elf64_Addr r_offset; Elf_Xword r_info; Elf_Sxword r_addend; }; #define ELF32_R_SYM( i ) ( ( i ) >> 8 ) #define ELF32_R_TYPE( i ) ( (unsigned char)( i ) ) #define ELF32_R_INFO( s, t ) ( ( ( s ) << 8 ) + (unsigned char)( t ) ) #define ELF64_R_SYM( i ) ( ( i ) >> 32 ) #define ELF64_R_TYPE( i ) ( (i)&0xffffffffL ) #define ELF64_R_INFO( s, t ) \ ( ( ( ( int64_t )( s ) ) << 32 ) + ( (t)&0xffffffffL ) ) // Dynamic structure struct Elf32_Dyn { Elf_Sword d_tag; union { Elf_Word d_val; Elf32_Addr d_ptr; } d_un; }; struct Elf64_Dyn { Elf_Sxword d_tag; union { Elf_Xword d_val; Elf64_Addr d_ptr; } d_un; }; } // namespace ELFIO #endif // ELFTYPES_H /*** End of inlined file: elf_types.hpp ***/ /*** Start of inlined file: elfio_version.hpp ***/ #define ELFIO_VERSION "3.8" /*** End of inlined file: elfio_version.hpp ***/ /*** Start of inlined file: elfio_utils.hpp ***/ #ifndef ELFIO_UTILS_HPP #define ELFIO_UTILS_HPP #define ELFIO_GET_ACCESS( TYPE, NAME, FIELD ) \ TYPE get_##NAME() const { return ( *convertor )( FIELD ); } #define ELFIO_SET_ACCESS( TYPE, NAME, FIELD ) \ void set_##NAME( TYPE value ) \ { \ FIELD = value; \ FIELD = ( *convertor )( FIELD ); \ } #define ELFIO_GET_SET_ACCESS( TYPE, NAME, FIELD ) \ TYPE get_##NAME() const { return ( *convertor )( FIELD ); } \ void set_##NAME( TYPE value ) \ { \ FIELD = value; \ FIELD = ( *convertor )( FIELD ); \ } #define ELFIO_GET_ACCESS_DECL( TYPE, NAME ) virtual TYPE get_##NAME() const = 0 #define ELFIO_SET_ACCESS_DECL( TYPE, NAME ) \ virtual void set_##NAME( TYPE value ) = 0 #define ELFIO_GET_SET_ACCESS_DECL( TYPE, NAME ) \ virtual TYPE get_##NAME() const = 0; \ virtual void set_##NAME( TYPE value ) = 0 namespace ELFIO { //------------------------------------------------------------------------------ class endianess_convertor { public: //------------------------------------------------------------------------------ endianess_convertor() { need_conversion = false; } //------------------------------------------------------------------------------ void setup( unsigned char elf_file_encoding ) { need_conversion = ( elf_file_encoding != get_host_encoding() ); } //------------------------------------------------------------------------------ uint64_t operator()( uint64_t value ) const { if ( !need_conversion ) { return value; } value = ( ( value & 0x00000000000000FFull ) << 56 ) | ( ( value & 0x000000000000FF00ull ) << 40 ) | ( ( value & 0x0000000000FF0000ull ) << 24 ) | ( ( value & 0x00000000FF000000ull ) << 8 ) | ( ( value & 0x000000FF00000000ull ) >> 8 ) | ( ( value & 0x0000FF0000000000ull ) >> 24 ) | ( ( value & 0x00FF000000000000ull ) >> 40 ) | ( ( value & 0xFF00000000000000ull ) >> 56 ); return value; } //------------------------------------------------------------------------------ int64_t operator()( int64_t value ) const { if ( !need_conversion ) { return value; } return ( int64_t )( *this )( (uint64_t)value ); } //------------------------------------------------------------------------------ uint32_t operator()( uint32_t value ) const { if ( !need_conversion ) { return value; } value = ( ( value & 0x000000FF ) << 24 ) | ( ( value & 0x0000FF00 ) << 8 ) | ( ( value & 0x00FF0000 ) >> 8 ) | ( ( value & 0xFF000000 ) >> 24 ); return value; } //------------------------------------------------------------------------------ int32_t operator()( int32_t value ) const { if ( !need_conversion ) { return value; } return ( int32_t )( *this )( (uint32_t)value ); } //------------------------------------------------------------------------------ uint16_t operator()( uint16_t value ) const { if ( !need_conversion ) { return value; } value = ( ( value & 0x00FF ) << 8 ) | ( ( value & 0xFF00 ) >> 8 ); return value; } //------------------------------------------------------------------------------ int16_t operator()( int16_t value ) const { if ( !need_conversion ) { return value; } return ( int16_t )( *this )( (uint16_t)value ); } //------------------------------------------------------------------------------ int8_t operator()( int8_t value ) const { return value; } //------------------------------------------------------------------------------ uint8_t operator()( uint8_t value ) const { return value; } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ unsigned char get_host_encoding() const { static const int tmp = 1; if ( 1 == *(const char*)&tmp ) { return ELFDATA2LSB; } else { return ELFDATA2MSB; } } //------------------------------------------------------------------------------ private: bool need_conversion; }; //------------------------------------------------------------------------------ inline uint32_t elf_hash( const unsigned char* name ) { uint32_t h = 0, g; while ( *name ) { h = ( h << 4 ) + *name++; g = h & 0xf0000000; if ( g != 0 ) h ^= g >> 24; h &= ~g; } return h; } } // namespace ELFIO #endif // ELFIO_UTILS_HPP /*** End of inlined file: elfio_utils.hpp ***/ /*** Start of inlined file: elfio_header.hpp ***/ #ifndef ELF_HEADER_HPP #define ELF_HEADER_HPP #include namespace ELFIO { class elf_header { public: virtual ~elf_header(){}; virtual bool load( std::istream& stream ) = 0; virtual bool save( std::ostream& stream ) const = 0; // ELF header functions ELFIO_GET_ACCESS_DECL( unsigned char, class ); ELFIO_GET_ACCESS_DECL( unsigned char, elf_version ); ELFIO_GET_ACCESS_DECL( unsigned char, encoding ); ELFIO_GET_ACCESS_DECL( Elf_Half, header_size ); ELFIO_GET_ACCESS_DECL( Elf_Half, section_entry_size ); ELFIO_GET_ACCESS_DECL( Elf_Half, segment_entry_size ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, version ); ELFIO_GET_SET_ACCESS_DECL( unsigned char, os_abi ); ELFIO_GET_SET_ACCESS_DECL( unsigned char, abi_version ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, type ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, machine ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, flags ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, entry ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, sections_num ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Off, sections_offset ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, segments_num ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Off, segments_offset ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, section_name_str_index ); }; template struct elf_header_impl_types; template <> struct elf_header_impl_types { typedef Elf32_Phdr Phdr_type; typedef Elf32_Shdr Shdr_type; static const unsigned char file_class = ELFCLASS32; }; template <> struct elf_header_impl_types { typedef Elf64_Phdr Phdr_type; typedef Elf64_Shdr Shdr_type; static const unsigned char file_class = ELFCLASS64; }; template class elf_header_impl : public elf_header { public: //------------------------------------------------------------------------------ elf_header_impl( endianess_convertor* convertor_, unsigned char encoding ) { convertor = convertor_; std::fill_n( reinterpret_cast( &header ), sizeof( header ), '\0' ); header.e_ident[EI_MAG0] = ELFMAG0; header.e_ident[EI_MAG1] = ELFMAG1; header.e_ident[EI_MAG2] = ELFMAG2; header.e_ident[EI_MAG3] = ELFMAG3; header.e_ident[EI_CLASS] = elf_header_impl_types::file_class; header.e_ident[EI_DATA] = encoding; header.e_ident[EI_VERSION] = EV_CURRENT; header.e_version = ( *convertor )( (Elf_Word)EV_CURRENT ); header.e_ehsize = ( sizeof( header ) ); header.e_ehsize = ( *convertor )( header.e_ehsize ); header.e_shstrndx = ( *convertor )( (Elf_Half)1 ); header.e_phentsize = sizeof( typename elf_header_impl_types::Phdr_type ); header.e_shentsize = sizeof( typename elf_header_impl_types::Shdr_type ); header.e_phentsize = ( *convertor )( header.e_phentsize ); header.e_shentsize = ( *convertor )( header.e_shentsize ); } //------------------------------------------------------------------------------ bool load( std::istream& stream ) { stream.seekg( 0 ); stream.read( reinterpret_cast( &header ), sizeof( header ) ); return ( stream.gcount() == sizeof( header ) ); } //------------------------------------------------------------------------------ bool save( std::ostream& stream ) const { stream.seekp( 0 ); stream.write( reinterpret_cast( &header ), sizeof( header ) ); return stream.good(); } //------------------------------------------------------------------------------ // ELF header functions ELFIO_GET_ACCESS( unsigned char, class, header.e_ident[EI_CLASS] ); ELFIO_GET_ACCESS( unsigned char, elf_version, header.e_ident[EI_VERSION] ); ELFIO_GET_ACCESS( unsigned char, encoding, header.e_ident[EI_DATA] ); ELFIO_GET_ACCESS( Elf_Half, header_size, header.e_ehsize ); ELFIO_GET_ACCESS( Elf_Half, section_entry_size, header.e_shentsize ); ELFIO_GET_ACCESS( Elf_Half, segment_entry_size, header.e_phentsize ); ELFIO_GET_SET_ACCESS( Elf_Word, version, header.e_version ); ELFIO_GET_SET_ACCESS( unsigned char, os_abi, header.e_ident[EI_OSABI] ); ELFIO_GET_SET_ACCESS( unsigned char, abi_version, header.e_ident[EI_ABIVERSION] ); ELFIO_GET_SET_ACCESS( Elf_Half, type, header.e_type ); ELFIO_GET_SET_ACCESS( Elf_Half, machine, header.e_machine ); ELFIO_GET_SET_ACCESS( Elf_Word, flags, header.e_flags ); ELFIO_GET_SET_ACCESS( Elf_Half, section_name_str_index, header.e_shstrndx ); ELFIO_GET_SET_ACCESS( Elf64_Addr, entry, header.e_entry ); ELFIO_GET_SET_ACCESS( Elf_Half, sections_num, header.e_shnum ); ELFIO_GET_SET_ACCESS( Elf64_Off, sections_offset, header.e_shoff ); ELFIO_GET_SET_ACCESS( Elf_Half, segments_num, header.e_phnum ); ELFIO_GET_SET_ACCESS( Elf64_Off, segments_offset, header.e_phoff ); private: T header; endianess_convertor* convertor; }; } // namespace ELFIO #endif // ELF_HEADER_HPP /*** End of inlined file: elfio_header.hpp ***/ /*** Start of inlined file: elfio_section.hpp ***/ #ifndef ELFIO_SECTION_HPP #define ELFIO_SECTION_HPP #include #include #include namespace ELFIO { class section { friend class elfio; public: virtual ~section(){}; ELFIO_GET_ACCESS_DECL( Elf_Half, index ); ELFIO_GET_SET_ACCESS_DECL( std::string, name ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, type ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, flags ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, info ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, link ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, addr_align ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, entry_size ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, address ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, size ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, name_string_offset ); ELFIO_GET_ACCESS_DECL( Elf64_Off, offset ); virtual const char* get_data() const = 0; virtual void set_data( const char* pData, Elf_Word size ) = 0; virtual void set_data( const std::string& data ) = 0; virtual void append_data( const char* pData, Elf_Word size ) = 0; virtual void append_data( const std::string& data ) = 0; virtual size_t get_stream_size() const = 0; virtual void set_stream_size( size_t value ) = 0; protected: ELFIO_SET_ACCESS_DECL( Elf64_Off, offset ); ELFIO_SET_ACCESS_DECL( Elf_Half, index ); virtual void load( std::istream& stream, std::streampos header_offset ) = 0; virtual void save( std::ostream& stream, std::streampos header_offset, std::streampos data_offset ) = 0; virtual bool is_address_initialized() const = 0; }; template class section_impl : public section { public: //------------------------------------------------------------------------------ section_impl( const endianess_convertor* convertor_ ) : convertor( convertor_ ) { std::fill_n( reinterpret_cast( &header ), sizeof( header ), '\0' ); is_address_set = false; data = 0; data_size = 0; index = 0; stream_size = 0; } //------------------------------------------------------------------------------ ~section_impl() { delete[] data; } //------------------------------------------------------------------------------ // Section info functions ELFIO_GET_SET_ACCESS( Elf_Word, type, header.sh_type ); ELFIO_GET_SET_ACCESS( Elf_Xword, flags, header.sh_flags ); ELFIO_GET_SET_ACCESS( Elf_Xword, size, header.sh_size ); ELFIO_GET_SET_ACCESS( Elf_Word, link, header.sh_link ); ELFIO_GET_SET_ACCESS( Elf_Word, info, header.sh_info ); ELFIO_GET_SET_ACCESS( Elf_Xword, addr_align, header.sh_addralign ); ELFIO_GET_SET_ACCESS( Elf_Xword, entry_size, header.sh_entsize ); ELFIO_GET_SET_ACCESS( Elf_Word, name_string_offset, header.sh_name ); ELFIO_GET_ACCESS( Elf64_Addr, address, header.sh_addr ); //------------------------------------------------------------------------------ Elf_Half get_index() const { return index; } //------------------------------------------------------------------------------ std::string get_name() const { return name; } //------------------------------------------------------------------------------ void set_name( std::string name_ ) { name = name_; } //------------------------------------------------------------------------------ void set_address( Elf64_Addr value ) { header.sh_addr = value; header.sh_addr = ( *convertor )( header.sh_addr ); is_address_set = true; } //------------------------------------------------------------------------------ bool is_address_initialized() const { return is_address_set; } //------------------------------------------------------------------------------ const char* get_data() const { return data; } //------------------------------------------------------------------------------ void set_data( const char* raw_data, Elf_Word size ) { if ( get_type() != SHT_NOBITS ) { delete[] data; data = new ( std::nothrow ) char[size]; if ( 0 != data && 0 != raw_data ) { data_size = size; std::copy( raw_data, raw_data + size, data ); } else { data_size = 0; } } set_size( data_size ); } //------------------------------------------------------------------------------ void set_data( const std::string& str_data ) { return set_data( str_data.c_str(), (Elf_Word)str_data.size() ); } //------------------------------------------------------------------------------ void append_data( const char* raw_data, Elf_Word size ) { if ( get_type() != SHT_NOBITS ) { if ( get_size() + size < data_size ) { std::copy( raw_data, raw_data + size, data + get_size() ); } else { data_size = 2 * ( data_size + size ); char* new_data = new ( std::nothrow ) char[data_size]; if ( 0 != new_data ) { std::copy( data, data + get_size(), new_data ); std::copy( raw_data, raw_data + size, new_data + get_size() ); delete[] data; data = new_data; } else { size = 0; } } set_size( get_size() + size ); } } //------------------------------------------------------------------------------ void append_data( const std::string& str_data ) { return append_data( str_data.c_str(), (Elf_Word)str_data.size() ); } //------------------------------------------------------------------------------ protected: //------------------------------------------------------------------------------ ELFIO_GET_SET_ACCESS( Elf64_Off, offset, header.sh_offset ); //------------------------------------------------------------------------------ void set_index( Elf_Half value ) { index = value; } //------------------------------------------------------------------------------ void load( std::istream& stream, std::streampos header_offset ) { std::fill_n( reinterpret_cast( &header ), sizeof( header ), '\0' ); stream.seekg( 0, stream.end ); set_stream_size( stream.tellg() ); stream.seekg( header_offset ); stream.read( reinterpret_cast( &header ), sizeof( header ) ); Elf_Xword size = get_size(); if ( 0 == data && SHT_NULL != get_type() && SHT_NOBITS != get_type() && size < get_stream_size() ) { data = new ( std::nothrow ) char[size + 1]; if ( ( 0 != size ) && ( 0 != data ) ) { stream.seekg( ( *convertor )( header.sh_offset ) ); stream.read( data, size ); data[size] = 0; // Ensure data is ended with 0 to avoid oob read data_size = size; } else { data_size = 0; } } } //------------------------------------------------------------------------------ void save( std::ostream& stream, std::streampos header_offset, std::streampos data_offset ) { if ( 0 != get_index() ) { header.sh_offset = data_offset; header.sh_offset = ( *convertor )( header.sh_offset ); } save_header( stream, header_offset ); if ( get_type() != SHT_NOBITS && get_type() != SHT_NULL && get_size() != 0 && data != 0 ) { save_data( stream, data_offset ); } } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ void save_header( std::ostream& stream, std::streampos header_offset ) const { stream.seekp( header_offset ); stream.write( reinterpret_cast( &header ), sizeof( header ) ); } //------------------------------------------------------------------------------ void save_data( std::ostream& stream, std::streampos data_offset ) const { stream.seekp( data_offset ); stream.write( get_data(), get_size() ); } //------------------------------------------------------------------------------ size_t get_stream_size() const { return stream_size; } //------------------------------------------------------------------------------ void set_stream_size( size_t value ) { stream_size = value; } //------------------------------------------------------------------------------ private: T header; Elf_Half index; std::string name; char* data; Elf_Word data_size; const endianess_convertor* convertor; bool is_address_set; size_t stream_size; }; } // namespace ELFIO #endif // ELFIO_SECTION_HPP /*** End of inlined file: elfio_section.hpp ***/ /*** Start of inlined file: elfio_segment.hpp ***/ #ifndef ELFIO_SEGMENT_HPP #define ELFIO_SEGMENT_HPP #include #include #include namespace ELFIO { class segment { friend class elfio; public: virtual ~segment(){}; ELFIO_GET_ACCESS_DECL( Elf_Half, index ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, type ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, flags ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, align ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, virtual_address ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, physical_address ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, file_size ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, memory_size ); ELFIO_GET_ACCESS_DECL( Elf64_Off, offset ); virtual const char* get_data() const = 0; virtual Elf_Half add_section_index( Elf_Half index, Elf_Xword addr_align ) = 0; virtual Elf_Half get_sections_num() const = 0; virtual Elf_Half get_section_index_at( Elf_Half num ) const = 0; virtual bool is_offset_initialized() const = 0; protected: ELFIO_SET_ACCESS_DECL( Elf64_Off, offset ); ELFIO_SET_ACCESS_DECL( Elf_Half, index ); virtual const std::vector& get_sections() const = 0; virtual void load( std::istream& stream, std::streampos header_offset ) = 0; virtual void save( std::ostream& stream, std::streampos header_offset, std::streampos data_offset ) = 0; }; //------------------------------------------------------------------------------ template class segment_impl : public segment { public: //------------------------------------------------------------------------------ segment_impl( endianess_convertor* convertor_ ) : stream_size( 0 ), index( 0 ), data( 0 ), convertor( convertor_ ) { is_offset_set = false; std::fill_n( reinterpret_cast( &ph ), sizeof( ph ), '\0' ); } //------------------------------------------------------------------------------ virtual ~segment_impl() { delete[] data; } //------------------------------------------------------------------------------ // Section info functions ELFIO_GET_SET_ACCESS( Elf_Word, type, ph.p_type ); ELFIO_GET_SET_ACCESS( Elf_Word, flags, ph.p_flags ); ELFIO_GET_SET_ACCESS( Elf_Xword, align, ph.p_align ); ELFIO_GET_SET_ACCESS( Elf64_Addr, virtual_address, ph.p_vaddr ); ELFIO_GET_SET_ACCESS( Elf64_Addr, physical_address, ph.p_paddr ); ELFIO_GET_SET_ACCESS( Elf_Xword, file_size, ph.p_filesz ); ELFIO_GET_SET_ACCESS( Elf_Xword, memory_size, ph.p_memsz ); ELFIO_GET_ACCESS( Elf64_Off, offset, ph.p_offset ); size_t stream_size; //------------------------------------------------------------------------------ size_t get_stream_size() const { return stream_size; } //------------------------------------------------------------------------------ void set_stream_size( size_t value ) { stream_size = value; } //------------------------------------------------------------------------------ Elf_Half get_index() const { return index; } //------------------------------------------------------------------------------ const char* get_data() const { return data; } //------------------------------------------------------------------------------ Elf_Half add_section_index( Elf_Half sec_index, Elf_Xword addr_align ) { sections.push_back( sec_index ); if ( addr_align > get_align() ) { set_align( addr_align ); } return (Elf_Half)sections.size(); } //------------------------------------------------------------------------------ Elf_Half get_sections_num() const { return (Elf_Half)sections.size(); } //------------------------------------------------------------------------------ Elf_Half get_section_index_at( Elf_Half num ) const { if ( num < sections.size() ) { return sections[num]; } return Elf_Half( -1 ); } //------------------------------------------------------------------------------ protected: //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void set_offset( Elf64_Off value ) { ph.p_offset = value; ph.p_offset = ( *convertor )( ph.p_offset ); is_offset_set = true; } //------------------------------------------------------------------------------ bool is_offset_initialized() const { return is_offset_set; } //------------------------------------------------------------------------------ const std::vector& get_sections() const { return sections; } //------------------------------------------------------------------------------ void set_index( Elf_Half value ) { index = value; } //------------------------------------------------------------------------------ void load( std::istream& stream, std::streampos header_offset ) { stream.seekg( 0, stream.end ); set_stream_size( stream.tellg() ); stream.seekg( header_offset ); stream.read( reinterpret_cast( &ph ), sizeof( ph ) ); is_offset_set = true; if ( PT_NULL != get_type() && 0 != get_file_size() ) { stream.seekg( ( *convertor )( ph.p_offset ) ); Elf_Xword size = get_file_size(); if ( size > get_stream_size() ) { data = 0; } else { data = new (std::nothrow) char[size + 1]; if ( 0 != data ) { stream.read( data, size ); data[size] = 0; } } } } //------------------------------------------------------------------------------ void save( std::ostream& stream, std::streampos header_offset, std::streampos data_offset ) { ph.p_offset = data_offset; ph.p_offset = ( *convertor )( ph.p_offset ); stream.seekp( header_offset ); stream.write( reinterpret_cast( &ph ), sizeof( ph ) ); } //------------------------------------------------------------------------------ private: T ph; Elf_Half index; char* data; std::vector sections; endianess_convertor* convertor; bool is_offset_set; }; } // namespace ELFIO #endif // ELFIO_SEGMENT_HPP /*** End of inlined file: elfio_segment.hpp ***/ /*** Start of inlined file: elfio_strings.hpp ***/ #ifndef ELFIO_STRINGS_HPP #define ELFIO_STRINGS_HPP #include #include #include namespace ELFIO { //------------------------------------------------------------------------------ template class string_section_accessor_template { public: //------------------------------------------------------------------------------ string_section_accessor_template( S* section_ ) : string_section( section_ ) { } //------------------------------------------------------------------------------ const char* get_string( Elf_Word index ) const { if ( string_section ) { if ( index < string_section->get_size() ) { const char* data = string_section->get_data(); if ( 0 != data ) { return data + index; } } } return 0; } //------------------------------------------------------------------------------ Elf_Word add_string( const char* str ) { Elf_Word current_position = 0; if ( string_section ) { // Strings are addeded to the end of the current section data current_position = (Elf_Word)string_section->get_size(); if ( current_position == 0 ) { char empty_string = '\0'; string_section->append_data( &empty_string, 1 ); current_position++; } string_section->append_data( str, (Elf_Word)std::strlen( str ) + 1 ); } return current_position; } //------------------------------------------------------------------------------ Elf_Word add_string( const std::string& str ) { return add_string( str.c_str() ); } //------------------------------------------------------------------------------ private: S* string_section; }; using string_section_accessor = string_section_accessor_template
; using const_string_section_accessor = string_section_accessor_template; } // namespace ELFIO #endif // ELFIO_STRINGS_HPP /*** End of inlined file: elfio_strings.hpp ***/ #define ELFIO_HEADER_ACCESS_GET( TYPE, FNAME ) \ TYPE get_##FNAME() const { return header ? ( header->get_##FNAME() ) : 0; } #define ELFIO_HEADER_ACCESS_GET_SET( TYPE, FNAME ) \ TYPE get_##FNAME() const \ { \ return header ? ( header->get_##FNAME() ) : 0; \ } \ void set_##FNAME( TYPE val ) \ { \ if ( header ) { \ header->set_##FNAME( val ); \ } \ } namespace ELFIO { //------------------------------------------------------------------------------ class elfio { public: //------------------------------------------------------------------------------ elfio() : sections( this ), segments( this ) { header = 0; current_file_pos = 0; create( ELFCLASS32, ELFDATA2LSB ); } //------------------------------------------------------------------------------ ~elfio() { clean(); } //------------------------------------------------------------------------------ void create( unsigned char file_class, unsigned char encoding ) { clean(); convertor.setup( encoding ); header = create_header( file_class, encoding ); create_mandatory_sections(); } //------------------------------------------------------------------------------ bool load( const std::string& file_name ) { std::ifstream stream; stream.open( file_name.c_str(), std::ios::in | std::ios::binary ); if ( !stream ) { return false; } return load( stream ); } //------------------------------------------------------------------------------ bool load( std::istream& stream ) { clean(); unsigned char e_ident[EI_NIDENT]; // Read ELF file signature stream.read( reinterpret_cast( &e_ident ), sizeof( e_ident ) ); // Is it ELF file? if ( stream.gcount() != sizeof( e_ident ) || e_ident[EI_MAG0] != ELFMAG0 || e_ident[EI_MAG1] != ELFMAG1 || e_ident[EI_MAG2] != ELFMAG2 || e_ident[EI_MAG3] != ELFMAG3 ) { return false; } if ( ( e_ident[EI_CLASS] != ELFCLASS64 ) && ( e_ident[EI_CLASS] != ELFCLASS32 ) ) { return false; } convertor.setup( e_ident[EI_DATA] ); header = create_header( e_ident[EI_CLASS], e_ident[EI_DATA] ); if ( 0 == header ) { return false; } if ( !header->load( stream ) ) { return false; } load_sections( stream ); bool is_still_good = load_segments( stream ); return is_still_good; } //------------------------------------------------------------------------------ bool save( const std::string& file_name ) { std::ofstream stream; stream.open( file_name.c_str(), std::ios::out | std::ios::binary ); if ( !stream ) { return false; } return save( stream ); } //------------------------------------------------------------------------------ bool save( std::ostream& stream ) { if ( !stream || !header ) { return false; } bool is_still_good = true; // Define layout specific header fields // The position of the segment table is fixed after the header. // The position of the section table is variable and needs to be fixed // before saving. header->set_segments_num( segments.size() ); header->set_segments_offset( segments.size() ? header->get_header_size() : 0 ); header->set_sections_num( sections.size() ); header->set_sections_offset( 0 ); // Layout the first section right after the segment table current_file_pos = header->get_header_size() + header->get_segment_entry_size() * (Elf_Xword)header->get_segments_num(); calc_segment_alignment(); is_still_good = layout_segments_and_their_sections(); is_still_good = is_still_good && layout_sections_without_segments(); is_still_good = is_still_good && layout_section_table(); is_still_good = is_still_good && save_header( stream ); is_still_good = is_still_good && save_sections( stream ); is_still_good = is_still_good && save_segments( stream ); return is_still_good; } //------------------------------------------------------------------------------ // ELF header access functions ELFIO_HEADER_ACCESS_GET( unsigned char, class ); ELFIO_HEADER_ACCESS_GET( unsigned char, elf_version ); ELFIO_HEADER_ACCESS_GET( unsigned char, encoding ); ELFIO_HEADER_ACCESS_GET( Elf_Word, version ); ELFIO_HEADER_ACCESS_GET( Elf_Half, header_size ); ELFIO_HEADER_ACCESS_GET( Elf_Half, section_entry_size ); ELFIO_HEADER_ACCESS_GET( Elf_Half, segment_entry_size ); ELFIO_HEADER_ACCESS_GET_SET( unsigned char, os_abi ); ELFIO_HEADER_ACCESS_GET_SET( unsigned char, abi_version ); ELFIO_HEADER_ACCESS_GET_SET( Elf_Half, type ); ELFIO_HEADER_ACCESS_GET_SET( Elf_Half, machine ); ELFIO_HEADER_ACCESS_GET_SET( Elf_Word, flags ); ELFIO_HEADER_ACCESS_GET_SET( Elf64_Addr, entry ); ELFIO_HEADER_ACCESS_GET_SET( Elf64_Off, sections_offset ); ELFIO_HEADER_ACCESS_GET_SET( Elf64_Off, segments_offset ); ELFIO_HEADER_ACCESS_GET_SET( Elf_Half, section_name_str_index ); //------------------------------------------------------------------------------ const endianess_convertor& get_convertor() const { return convertor; } //------------------------------------------------------------------------------ Elf_Xword get_default_entry_size( Elf_Word section_type ) const { switch ( section_type ) { case SHT_RELA: if ( header->get_class() == ELFCLASS64 ) { return sizeof( Elf64_Rela ); } else { return sizeof( Elf32_Rela ); } case SHT_REL: if ( header->get_class() == ELFCLASS64 ) { return sizeof( Elf64_Rel ); } else { return sizeof( Elf32_Rel ); } case SHT_SYMTAB: if ( header->get_class() == ELFCLASS64 ) { return sizeof( Elf64_Sym ); } else { return sizeof( Elf32_Sym ); } case SHT_DYNAMIC: if ( header->get_class() == ELFCLASS64 ) { return sizeof( Elf64_Dyn ); } else { return sizeof( Elf32_Dyn ); } default: return 0; } } //------------------------------------------------------------------------------ private: bool is_offset_in_section( Elf64_Off offset, const section* sec ) const { return ( offset >= sec->get_offset() ) && ( offset < ( sec->get_offset() + sec->get_size() ) ); } //------------------------------------------------------------------------------ public: //! returns an empty string if no problems are detected, //! or a string containing an error message if problems are found std::string validate() const { // check for overlapping sections in the file for ( int i = 0; i < sections.size(); ++i ) { for ( int j = i + 1; j < sections.size(); ++j ) { const section* a = sections[i]; const section* b = sections[j]; if ( !( a->get_type() & SHT_NOBITS ) && !( b->get_type() & SHT_NOBITS ) && ( a->get_size() > 0 ) && ( b->get_size() > 0 ) && ( a->get_offset() > 0 ) && ( b->get_offset() > 0 ) ) { if ( is_offset_in_section( a->get_offset(), b ) || is_offset_in_section( a->get_offset() + a->get_size() - 1, b ) || is_offset_in_section( b->get_offset(), a ) || is_offset_in_section( b->get_offset() + b->get_size() - 1, a ) ) { return "Sections " + a->get_name() + " and " + b->get_name() + " overlap in file"; } } } } // more checks to be added here... return ""; } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ void clean() { delete header; header = 0; std::vector::const_iterator it; for ( it = sections_.begin(); it != sections_.end(); ++it ) { delete *it; } sections_.clear(); std::vector::const_iterator it1; for ( it1 = segments_.begin(); it1 != segments_.end(); ++it1 ) { delete *it1; } segments_.clear(); } //------------------------------------------------------------------------------ elf_header* create_header( unsigned char file_class, unsigned char encoding ) { elf_header* new_header = 0; if ( file_class == ELFCLASS64 ) { new_header = new elf_header_impl( &convertor, encoding ); } else if ( file_class == ELFCLASS32 ) { new_header = new elf_header_impl( &convertor, encoding ); } else { return 0; } return new_header; } //------------------------------------------------------------------------------ section* create_section() { section* new_section; unsigned char file_class = get_class(); if ( file_class == ELFCLASS64 ) { new_section = new section_impl( &convertor ); } else if ( file_class == ELFCLASS32 ) { new_section = new section_impl( &convertor ); } else { return 0; } new_section->set_index( (Elf_Half)sections_.size() ); sections_.push_back( new_section ); return new_section; } //------------------------------------------------------------------------------ segment* create_segment() { segment* new_segment; unsigned char file_class = header->get_class(); if ( file_class == ELFCLASS64 ) { new_segment = new segment_impl( &convertor ); } else if ( file_class == ELFCLASS32 ) { new_segment = new segment_impl( &convertor ); } else { return 0; } new_segment->set_index( (Elf_Half)segments_.size() ); segments_.push_back( new_segment ); return new_segment; } //------------------------------------------------------------------------------ void create_mandatory_sections() { // Create null section without calling to 'add_section' as no string // section containing section names exists yet section* sec0 = create_section(); sec0->set_index( 0 ); sec0->set_name( "" ); sec0->set_name_string_offset( 0 ); set_section_name_str_index( 1 ); section* shstrtab = sections.add( ".shstrtab" ); shstrtab->set_type( SHT_STRTAB ); shstrtab->set_addr_align( 1 ); } //------------------------------------------------------------------------------ Elf_Half load_sections( std::istream& stream ) { Elf_Half entry_size = header->get_section_entry_size(); Elf_Half num = header->get_sections_num(); Elf64_Off offset = header->get_sections_offset(); for ( Elf_Half i = 0; i < num; ++i ) { section* sec = create_section(); sec->load( stream, (std::streamoff)offset + (std::streampos)i * entry_size ); sec->set_index( i ); // To mark that the section is not permitted to reassign address // during layout calculation sec->set_address( sec->get_address() ); } Elf_Half shstrndx = get_section_name_str_index(); if ( SHN_UNDEF != shstrndx ) { string_section_accessor str_reader( sections[shstrndx] ); for ( Elf_Half i = 0; i < num; ++i ) { Elf_Word section_offset = sections[i]->get_name_string_offset(); const char* p = str_reader.get_string( section_offset ); if ( p != 0 ) { sections[i]->set_name( p ); } } } return num; } //------------------------------------------------------------------------------ //! Checks whether the addresses of the section entirely fall within the given segment. //! It doesn't matter if the addresses are memory addresses, or file offsets, //! they just need to be in the same address space bool is_sect_in_seg( Elf64_Off sect_begin, Elf_Xword sect_size, Elf64_Off seg_begin, Elf64_Off seg_end ) { return ( seg_begin <= sect_begin ) && ( sect_begin + sect_size <= seg_end ) && ( sect_begin < seg_end ); // this is important criteria when sect_size == 0 // Example: seg_begin=10, seg_end=12 (-> covering the bytes 10 and 11) // sect_begin=12, sect_size=0 -> shall return false! } //------------------------------------------------------------------------------ bool load_segments( std::istream& stream ) { Elf_Half entry_size = header->get_segment_entry_size(); Elf_Half num = header->get_segments_num(); Elf64_Off offset = header->get_segments_offset(); for ( Elf_Half i = 0; i < num; ++i ) { segment* seg; unsigned char file_class = header->get_class(); if ( file_class == ELFCLASS64 ) { seg = new segment_impl( &convertor ); } else if ( file_class == ELFCLASS32 ) { seg = new segment_impl( &convertor ); } else { return false; } seg->load( stream, (std::streamoff)offset + (std::streampos)i * entry_size ); seg->set_index( i ); // Add sections to the segments (similar to readelfs algorithm) Elf64_Off segBaseOffset = seg->get_offset(); Elf64_Off segEndOffset = segBaseOffset + seg->get_file_size(); Elf64_Off segVBaseAddr = seg->get_virtual_address(); Elf64_Off segVEndAddr = segVBaseAddr + seg->get_memory_size(); for ( Elf_Half j = 0; j < sections.size(); ++j ) { const section* psec = sections[j]; // SHF_ALLOC sections are matched based on the virtual address // otherwise the file offset is matched if ( ( psec->get_flags() & SHF_ALLOC ) ? is_sect_in_seg( psec->get_address(), psec->get_size(), segVBaseAddr, segVEndAddr ) : is_sect_in_seg( psec->get_offset(), psec->get_size(), segBaseOffset, segEndOffset ) ) { // Alignment of segment shall not be updated, to preserve original value // It will be re-calculated on saving. seg->add_section_index( psec->get_index(), 0 ); } } // Add section into the segments' container segments_.push_back( seg ); } return true; } //------------------------------------------------------------------------------ bool save_header( std::ostream& stream ) { return header->save( stream ); } //------------------------------------------------------------------------------ bool save_sections( std::ostream& stream ) { for ( unsigned int i = 0; i < sections_.size(); ++i ) { section* sec = sections_.at( i ); std::streampos headerPosition = (std::streamoff)header->get_sections_offset() + (std::streampos)header->get_section_entry_size() * sec->get_index(); sec->save( stream, headerPosition, sec->get_offset() ); } return true; } //------------------------------------------------------------------------------ bool save_segments( std::ostream& stream ) { for ( unsigned int i = 0; i < segments_.size(); ++i ) { segment* seg = segments_.at( i ); std::streampos headerPosition = header->get_segments_offset() + (std::streampos)header->get_segment_entry_size() * seg->get_index(); seg->save( stream, headerPosition, seg->get_offset() ); } return true; } //------------------------------------------------------------------------------ bool is_section_without_segment( unsigned int section_index ) { bool found = false; for ( unsigned int j = 0; !found && ( j < segments.size() ); ++j ) { for ( unsigned int k = 0; !found && ( k < segments[j]->get_sections_num() ); ++k ) { found = segments[j]->get_section_index_at( k ) == section_index; } } return !found; } //------------------------------------------------------------------------------ bool is_subsequence_of( segment* seg1, segment* seg2 ) { // Return 'true' if sections of seg1 are a subset of sections in seg2 const std::vector& sections1 = seg1->get_sections(); const std::vector& sections2 = seg2->get_sections(); bool found = false; if ( sections1.size() < sections2.size() ) { found = std::includes( sections2.begin(), sections2.end(), sections1.begin(), sections1.end() ); } return found; } //------------------------------------------------------------------------------ std::vector get_ordered_segments() { std::vector res; std::deque worklist; res.reserve( segments.size() ); std::copy( segments_.begin(), segments_.end(), std::back_inserter( worklist ) ); // Bring the segments which start at address 0 to the front size_t nextSlot = 0; for ( size_t i = 0; i < worklist.size(); ++i ) { if ( i != nextSlot && worklist[i]->is_offset_initialized() && worklist[i]->get_offset() == 0 ) { if ( worklist[nextSlot]->get_offset() == 0 ) { ++nextSlot; } std::swap( worklist[i], worklist[nextSlot] ); ++nextSlot; } } while ( !worklist.empty() ) { segment* seg = worklist.front(); worklist.pop_front(); size_t i = 0; for ( ; i < worklist.size(); ++i ) { if ( is_subsequence_of( seg, worklist[i] ) ) { break; } } if ( i < worklist.size() ) worklist.push_back( seg ); else res.push_back( seg ); } return res; } //------------------------------------------------------------------------------ bool layout_sections_without_segments() { for ( unsigned int i = 0; i < sections_.size(); ++i ) { if ( is_section_without_segment( i ) ) { section* sec = sections_[i]; Elf_Xword section_align = sec->get_addr_align(); if ( section_align > 1 && current_file_pos % section_align != 0 ) { current_file_pos += section_align - current_file_pos % section_align; } if ( 0 != sec->get_index() ) sec->set_offset( current_file_pos ); if ( SHT_NOBITS != sec->get_type() && SHT_NULL != sec->get_type() ) { current_file_pos += sec->get_size(); } } } return true; } //------------------------------------------------------------------------------ void calc_segment_alignment() { for ( std::vector::iterator s = segments_.begin(); s != segments_.end(); ++s ) { segment* seg = *s; for ( int i = 0; i < seg->get_sections_num(); ++i ) { section* sect = sections_[seg->get_section_index_at( i )]; if ( sect->get_addr_align() > seg->get_align() ) { seg->set_align( sect->get_addr_align() ); } } } } //------------------------------------------------------------------------------ bool layout_segments_and_their_sections() { std::vector worklist; std::vector section_generated( sections.size(), false ); // Get segments in a order in where segments which contain a // sub sequence of other segments are located at the end worklist = get_ordered_segments(); for ( unsigned int i = 0; i < worklist.size(); ++i ) { Elf_Xword segment_memory = 0; Elf_Xword segment_filesize = 0; Elf_Xword seg_start_pos = current_file_pos; segment* seg = worklist[i]; // Special case: PHDR segment // This segment contains the program headers but no sections if ( seg->get_type() == PT_PHDR && seg->get_sections_num() == 0 ) { seg_start_pos = header->get_segments_offset(); segment_memory = segment_filesize = header->get_segment_entry_size() * (Elf_Xword)header->get_segments_num(); } // Special case: else if ( seg->is_offset_initialized() && seg->get_offset() == 0 ) { seg_start_pos = 0; if ( seg->get_sections_num() ) { segment_memory = segment_filesize = current_file_pos; } } // New segments with not generated sections // have to be aligned else if ( seg->get_sections_num() && !section_generated[seg->get_section_index_at( 0 )] ) { Elf_Xword align = seg->get_align() > 0 ? seg->get_align() : 1; Elf64_Off cur_page_alignment = current_file_pos % align; Elf64_Off req_page_alignment = seg->get_virtual_address() % align; Elf64_Off error = req_page_alignment - cur_page_alignment; current_file_pos += ( seg->get_align() + error ) % align; seg_start_pos = current_file_pos; } else if ( seg->get_sections_num() ) { seg_start_pos = sections[seg->get_section_index_at( 0 )]->get_offset(); } // Write segment's data for ( unsigned int j = 0; j < seg->get_sections_num(); ++j ) { Elf_Half index = seg->get_section_index_at( j ); section* sec = sections[index]; // The NULL section is always generated if ( SHT_NULL == sec->get_type() ) { section_generated[index] = true; continue; } Elf_Xword secAlign = 0; // Fix up the alignment if ( !section_generated[index] && sec->is_address_initialized() && SHT_NOBITS != sec->get_type() && SHT_NULL != sec->get_type() && 0 != sec->get_size() ) { // Align the sections based on the virtual addresses // when possible (this is what matters for execution) Elf64_Off req_offset = sec->get_address() - seg->get_virtual_address(); Elf64_Off cur_offset = current_file_pos - seg_start_pos; if ( req_offset < cur_offset ) { // something has gone awfully wrong, abort! // secAlign would turn out negative, seeking backwards and overwriting previous data return false; } secAlign = req_offset - cur_offset; } else if ( !section_generated[index] && !sec->is_address_initialized() ) { // If no address has been specified then only the section // alignment constraint has to be matched Elf_Xword align = sec->get_addr_align(); if ( align == 0 ) { align = 1; } Elf64_Off error = current_file_pos % align; secAlign = ( align - error ) % align; } else if ( section_generated[index] ) { // Alignment for already generated sections secAlign = sec->get_offset() - seg_start_pos - segment_filesize; } // Determine the segment file and memory sizes // Special case .tbss section (NOBITS) in non TLS segment if ( ( sec->get_flags() & SHF_ALLOC ) && !( ( sec->get_flags() & SHF_TLS ) && ( seg->get_type() != PT_TLS ) && ( SHT_NOBITS == sec->get_type() ) ) ) segment_memory += sec->get_size() + secAlign; if ( SHT_NOBITS != sec->get_type() ) segment_filesize += sec->get_size() + secAlign; // Nothing to be done when generating nested segments if ( section_generated[index] ) { continue; } current_file_pos += secAlign; // Set the section addresses when missing if ( !sec->is_address_initialized() ) sec->set_address( seg->get_virtual_address() + current_file_pos - seg_start_pos ); if ( 0 != sec->get_index() ) sec->set_offset( current_file_pos ); if ( SHT_NOBITS != sec->get_type() ) current_file_pos += sec->get_size(); section_generated[index] = true; } seg->set_file_size( segment_filesize ); // If we already have a memory size from loading an elf file (value > 0), // it must not shrink! // Memory size may be bigger than file size and it is the loader's job to do something // with the surplus bytes in memory, like initializing them with a defined value. if ( seg->get_memory_size() < segment_memory ) { seg->set_memory_size( segment_memory ); } seg->set_offset( seg_start_pos ); } return true; } //------------------------------------------------------------------------------ bool layout_section_table() { // Simply place the section table at the end for now Elf64_Off alignmentError = current_file_pos % 4; current_file_pos += ( 4 - alignmentError ) % 4; header->set_sections_offset( current_file_pos ); return true; } //------------------------------------------------------------------------------ public: friend class Sections; class Sections { public: //------------------------------------------------------------------------------ Sections( elfio* parent_ ) : parent( parent_ ) {} //------------------------------------------------------------------------------ Elf_Half size() const { return (Elf_Half)parent->sections_.size(); } //------------------------------------------------------------------------------ section* operator[]( unsigned int index ) const { section* sec = 0; if ( index < parent->sections_.size() ) { sec = parent->sections_[index]; } return sec; } //------------------------------------------------------------------------------ section* operator[]( const std::string& name ) const { section* sec = 0; std::vector::const_iterator it; for ( it = parent->sections_.begin(); it != parent->sections_.end(); ++it ) { if ( ( *it )->get_name() == name ) { sec = *it; break; } } return sec; } //------------------------------------------------------------------------------ section* add( const std::string& name ) { section* new_section = parent->create_section(); new_section->set_name( name ); Elf_Half str_index = parent->get_section_name_str_index(); section* string_table( parent->sections_[str_index] ); string_section_accessor str_writer( string_table ); Elf_Word pos = str_writer.add_string( name ); new_section->set_name_string_offset( pos ); return new_section; } //------------------------------------------------------------------------------ std::vector::iterator begin() { return parent->sections_.begin(); } //------------------------------------------------------------------------------ std::vector::iterator end() { return parent->sections_.end(); } //------------------------------------------------------------------------------ std::vector::const_iterator begin() const { return parent->sections_.cbegin(); } //------------------------------------------------------------------------------ std::vector::const_iterator end() const { return parent->sections_.cend(); } //------------------------------------------------------------------------------ private: elfio* parent; } sections; //------------------------------------------------------------------------------ public: friend class Segments; class Segments { public: //------------------------------------------------------------------------------ Segments( elfio* parent_ ) : parent( parent_ ) {} //------------------------------------------------------------------------------ Elf_Half size() const { return (Elf_Half)parent->segments_.size(); } //------------------------------------------------------------------------------ segment* operator[]( unsigned int index ) const { return parent->segments_[index]; } //------------------------------------------------------------------------------ segment* add() { return parent->create_segment(); } //------------------------------------------------------------------------------ std::vector::iterator begin() { return parent->segments_.begin(); } //------------------------------------------------------------------------------ std::vector::iterator end() { return parent->segments_.end(); } //------------------------------------------------------------------------------ std::vector::const_iterator begin() const { return parent->segments_.cbegin(); } //------------------------------------------------------------------------------ std::vector::const_iterator end() const { return parent->segments_.cend(); } //------------------------------------------------------------------------------ private: elfio* parent; } segments; //------------------------------------------------------------------------------ private: elf_header* header; std::vector sections_; std::vector segments_; endianess_convertor convertor; Elf_Xword current_file_pos; }; } // namespace ELFIO /*** Start of inlined file: elfio_symbols.hpp ***/ #ifndef ELFIO_SYMBOLS_HPP #define ELFIO_SYMBOLS_HPP namespace ELFIO { //------------------------------------------------------------------------------ template class symbol_section_accessor_template { public: //------------------------------------------------------------------------------ symbol_section_accessor_template( const elfio& elf_file_, S* symbol_section_ ) : elf_file( elf_file_ ), symbol_section( symbol_section_ ) { find_hash_section(); } //------------------------------------------------------------------------------ Elf_Xword get_symbols_num() const { Elf_Xword nRet = 0; if ( 0 != symbol_section->get_entry_size() ) { nRet = symbol_section->get_size() / symbol_section->get_entry_size(); } return nRet; } //------------------------------------------------------------------------------ bool get_symbol( Elf_Xword index, std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( elf_file.get_class() == ELFCLASS32 ) { ret = generic_get_symbol( index, name, value, size, bind, type, section_index, other ); } else { ret = generic_get_symbol( index, name, value, size, bind, type, section_index, other ); } return ret; } //------------------------------------------------------------------------------ bool get_symbol( const std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( 0 != get_hash_table_index() ) { Elf_Word nbucket = *(const Elf_Word*)hash_section->get_data(); Elf_Word nchain = *(const Elf_Word*)( hash_section->get_data() + sizeof( Elf_Word ) ); Elf_Word val = elf_hash( (const unsigned char*)name.c_str() ); Elf_Word y = *(const Elf_Word*)( hash_section->get_data() + ( 2 + val % nbucket ) * sizeof( Elf_Word ) ); std::string str; get_symbol( y, str, value, size, bind, type, section_index, other ); while ( str != name && STN_UNDEF != y && y < nchain ) { y = *(const Elf_Word*)( hash_section->get_data() + ( 2 + nbucket + y ) * sizeof( Elf_Word ) ); get_symbol( y, str, value, size, bind, type, section_index, other ); } if ( str == name ) { ret = true; } } else { for ( Elf_Xword i = 0; i < get_symbols_num() && !ret; i++ ) { std::string symbol_name; if ( get_symbol( i, symbol_name, value, size, bind, type, section_index, other ) ) { if ( symbol_name == name ) { ret = true; } } } } return ret; } //------------------------------------------------------------------------------ bool get_symbol( const Elf64_Addr& value, std::string& name, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { const endianess_convertor& convertor = elf_file.get_convertor(); Elf_Xword idx = 0; bool match = false; Elf64_Addr v = 0; if ( elf_file.get_class() == ELFCLASS32 ) { match = generic_search_symbols( [&]( const Elf32_Sym* sym ) { return convertor( sym->st_value ) == value; }, idx ); } else { match = generic_search_symbols( [&]( const Elf64_Sym* sym ) { return convertor( sym->st_value ) == value; }, idx ); } if ( match ) { return get_symbol( idx, name, v, size, bind, type, section_index, other ); } return false; } //------------------------------------------------------------------------------ Elf_Word add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { Elf_Word nRet; if ( symbol_section->get_size() == 0 ) { if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_add_symbol( 0, 0, 0, 0, 0, 0 ); } else { nRet = generic_add_symbol( 0, 0, 0, 0, 0, 0 ); } } if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_add_symbol( name, value, size, info, other, shndx ); } else { nRet = generic_add_symbol( name, value, size, info, other, shndx ); } return nRet; } //------------------------------------------------------------------------------ Elf_Word add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, unsigned char other, Elf_Half shndx ) { return add_symbol( name, value, size, ELF_ST_INFO( bind, type ), other, shndx ); } //------------------------------------------------------------------------------ Elf_Word add_symbol( string_section_accessor& pStrWriter, const char* str, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { Elf_Word index = pStrWriter.add_string( str ); return add_symbol( index, value, size, info, other, shndx ); } //------------------------------------------------------------------------------ Elf_Word add_symbol( string_section_accessor& pStrWriter, const char* str, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, unsigned char other, Elf_Half shndx ) { return add_symbol( pStrWriter, str, value, size, ELF_ST_INFO( bind, type ), other, shndx ); } //------------------------------------------------------------------------------ Elf_Xword arrange_local_symbols( std::function func = nullptr ) { int nRet = 0; if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_arrange_local_symbols( func ); } else { nRet = generic_arrange_local_symbols( func ); } return nRet; } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ void find_hash_section() { hash_section = 0; hash_section_index = 0; Elf_Half nSecNo = elf_file.sections.size(); for ( Elf_Half i = 0; i < nSecNo && 0 == hash_section_index; ++i ) { const section* sec = elf_file.sections[i]; if ( sec->get_link() == symbol_section->get_index() ) { hash_section = sec; hash_section_index = i; } } } //------------------------------------------------------------------------------ Elf_Half get_string_table_index() const { return (Elf_Half)symbol_section->get_link(); } //------------------------------------------------------------------------------ Elf_Half get_hash_table_index() const { return hash_section_index; } //------------------------------------------------------------------------------ template const T* generic_get_symbol_ptr( Elf_Xword index ) const { if ( 0 != symbol_section->get_data() && index < get_symbols_num() ) { const T* pSym = reinterpret_cast( symbol_section->get_data() + index * symbol_section->get_entry_size() ); return pSym; } return nullptr; } //------------------------------------------------------------------------------ template bool generic_search_symbols( std::function match, Elf_Xword& idx ) const { for ( Elf_Xword i = 0; i < get_symbols_num(); i++ ) { const T* symPtr = generic_get_symbol_ptr( i ); if ( symPtr == nullptr ) return false; if ( match( symPtr ) ) { idx = i; return true; } } return false; } //------------------------------------------------------------------------------ template bool generic_get_symbol( Elf_Xword index, std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( 0 != symbol_section->get_data() && index < get_symbols_num() ) { const T* pSym = reinterpret_cast( symbol_section->get_data() + index * symbol_section->get_entry_size() ); const endianess_convertor& convertor = elf_file.get_convertor(); section* string_section = elf_file.sections[get_string_table_index()]; string_section_accessor str_reader( string_section ); const char* pStr = str_reader.get_string( convertor( pSym->st_name ) ); if ( 0 != pStr ) { name = pStr; } value = convertor( pSym->st_value ); size = convertor( pSym->st_size ); bind = ELF_ST_BIND( pSym->st_info ); type = ELF_ST_TYPE( pSym->st_info ); section_index = convertor( pSym->st_shndx ); other = pSym->st_other; ret = true; } return ret; } //------------------------------------------------------------------------------ template Elf_Word generic_add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; entry.st_name = convertor( name ); entry.st_value = value; entry.st_value = convertor( entry.st_value ); entry.st_size = size; entry.st_size = convertor( entry.st_size ); entry.st_info = convertor( info ); entry.st_other = convertor( other ); entry.st_shndx = convertor( shndx ); symbol_section->append_data( reinterpret_cast( &entry ), sizeof( entry ) ); Elf_Word nRet = symbol_section->get_size() / sizeof( entry ) - 1; return nRet; } //------------------------------------------------------------------------------ template Elf_Xword generic_arrange_local_symbols( std::function func ) { const endianess_convertor& convertor = elf_file.get_convertor(); const Elf_Xword size = symbol_section->get_entry_size(); Elf_Xword first_not_local = 1; // Skip the first entry. It is always NOTYPE Elf_Xword current = 0; Elf_Xword count = get_symbols_num(); while ( true ) { T* p1 = nullptr; T* p2 = nullptr; while ( first_not_local < count ) { p1 = const_cast( generic_get_symbol_ptr( first_not_local ) ); if ( ELF_ST_BIND( convertor( p1->st_info ) ) != STB_LOCAL ) break; ++first_not_local; } current = first_not_local + 1; while ( current < count ) { p2 = const_cast( generic_get_symbol_ptr( current ) ); if ( ELF_ST_BIND( convertor( p2->st_info ) ) == STB_LOCAL ) break; ++current; } if ( first_not_local < count && current < count ) { if ( func ) func( first_not_local, current ); // Swap the symbols T tmp; std::copy( p1, p1 + 1, &tmp ); std::copy( p2, p2 + 1, p1 ); std::copy( &tmp, &tmp + 1, p2 ); } else { // Update 'info' field of the section symbol_section->set_info( first_not_local ); break; } } // Elf_Word nRet = symbol_section->get_size() / sizeof(entry) - 1; return first_not_local; } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* symbol_section; Elf_Half hash_section_index; const section* hash_section; }; using symbol_section_accessor = symbol_section_accessor_template
; using const_symbol_section_accessor = symbol_section_accessor_template; } // namespace ELFIO #endif // ELFIO_SYMBOLS_HPP /*** End of inlined file: elfio_symbols.hpp ***/ /*** Start of inlined file: elfio_note.hpp ***/ #ifndef ELFIO_NOTE_HPP #define ELFIO_NOTE_HPP namespace ELFIO { //------------------------------------------------------------------------------ // There are discrepancies in documentations. SCO documentation // (http://www.sco.com/developers/gabi/latest/ch5.pheader.html#note_section) // requires 8 byte entries alignment for 64-bit ELF file, // but Oracle's definition uses the same structure // for 32-bit and 64-bit formats. // (https://docs.oracle.com/cd/E23824_01/html/819-0690/chapter6-18048.html) // // It looks like EM_X86_64 Linux implementation is similar to Oracle's // definition. Therefore, the same alignment works for both formats //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ template class note_section_accessor_template { public: //------------------------------------------------------------------------------ note_section_accessor_template( const elfio& elf_file_, S* section_ ) : elf_file( elf_file_ ), note_section( section_ ) { process_section(); } //------------------------------------------------------------------------------ Elf_Word get_notes_num() const { return (Elf_Word)note_start_positions.size(); } //------------------------------------------------------------------------------ bool get_note( Elf_Word index, Elf_Word& type, std::string& name, void*& desc, Elf_Word& descSize ) const { if ( index >= note_section->get_size() ) { return false; } const char* pData = note_section->get_data() + note_start_positions[index]; int align = sizeof( Elf_Word ); const endianess_convertor& convertor = elf_file.get_convertor(); type = convertor( *(const Elf_Word*)( pData + 2 * align ) ); Elf_Word namesz = convertor( *(const Elf_Word*)( pData ) ); descSize = convertor( *(const Elf_Word*)( pData + sizeof( namesz ) ) ); Elf_Xword max_name_size = note_section->get_size() - note_start_positions[index]; if ( namesz < 1 || namesz > max_name_size || (Elf_Xword)namesz + descSize > max_name_size ) { return false; } name.assign( pData + 3 * align, namesz - 1 ); if ( 0 == descSize ) { desc = 0; } else { desc = const_cast( pData + 3 * align + ( ( namesz + align - 1 ) / align ) * align ); } return true; } //------------------------------------------------------------------------------ void add_note( Elf_Word type, const std::string& name, const void* desc, Elf_Word descSize ) { const endianess_convertor& convertor = elf_file.get_convertor(); int align = sizeof( Elf_Word ); Elf_Word nameLen = (Elf_Word)name.size() + 1; Elf_Word nameLenConv = convertor( nameLen ); std::string buffer( reinterpret_cast( &nameLenConv ), align ); Elf_Word descSizeConv = convertor( descSize ); buffer.append( reinterpret_cast( &descSizeConv ), align ); type = convertor( type ); buffer.append( reinterpret_cast( &type ), align ); buffer.append( name ); buffer.append( 1, '\x00' ); const char pad[] = { '\0', '\0', '\0', '\0' }; if ( nameLen % align != 0 ) { buffer.append( pad, align - nameLen % align ); } if ( desc != 0 && descSize != 0 ) { buffer.append( reinterpret_cast( desc ), descSize ); if ( descSize % align != 0 ) { buffer.append( pad, align - descSize % align ); } } note_start_positions.push_back( note_section->get_size() ); note_section->append_data( buffer ); } private: //------------------------------------------------------------------------------ void process_section() { const endianess_convertor& convertor = elf_file.get_convertor(); const char* data = note_section->get_data(); Elf_Xword size = note_section->get_size(); Elf_Xword current = 0; note_start_positions.clear(); // Is it empty? if ( 0 == data || 0 == size ) { return; } Elf_Word align = sizeof( Elf_Word ); while ( current + (Elf_Xword)3 * align <= size ) { note_start_positions.push_back( current ); Elf_Word namesz = convertor( *(const Elf_Word*)( data + current ) ); Elf_Word descsz = convertor( *(const Elf_Word*)( data + current + sizeof( namesz ) ) ); current += (Elf_Xword)3 * sizeof( Elf_Word ) + ( ( namesz + align - 1 ) / align ) * (Elf_Xword)align + ( ( descsz + align - 1 ) / align ) * (Elf_Xword)align; } } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* note_section; std::vector note_start_positions; }; using note_section_accessor = note_section_accessor_template
; using const_note_section_accessor = note_section_accessor_template; } // namespace ELFIO #endif // ELFIO_NOTE_HPP /*** End of inlined file: elfio_note.hpp ***/ /*** Start of inlined file: elfio_relocation.hpp ***/ #ifndef ELFIO_RELOCATION_HPP #define ELFIO_RELOCATION_HPP namespace ELFIO { template struct get_sym_and_type; template <> struct get_sym_and_type { static int get_r_sym( Elf_Xword info ) { return ELF32_R_SYM( (Elf_Word)info ); } static int get_r_type( Elf_Xword info ) { return ELF32_R_TYPE( (Elf_Word)info ); } }; template <> struct get_sym_and_type { static int get_r_sym( Elf_Xword info ) { return ELF32_R_SYM( (Elf_Word)info ); } static int get_r_type( Elf_Xword info ) { return ELF32_R_TYPE( (Elf_Word)info ); } }; template <> struct get_sym_and_type { static int get_r_sym( Elf_Xword info ) { return ELF64_R_SYM( info ); } static int get_r_type( Elf_Xword info ) { return ELF64_R_TYPE( info ); } }; template <> struct get_sym_and_type { static int get_r_sym( Elf_Xword info ) { return ELF64_R_SYM( info ); } static int get_r_type( Elf_Xword info ) { return ELF64_R_TYPE( info ); } }; //------------------------------------------------------------------------------ template class relocation_section_accessor_template { public: //------------------------------------------------------------------------------ relocation_section_accessor_template( const elfio& elf_file_, S* section_ ) : elf_file( elf_file_ ), relocation_section( section_ ) { } //------------------------------------------------------------------------------ Elf_Xword get_entries_num() const { Elf_Xword nRet = 0; if ( 0 != relocation_section->get_entry_size() ) { nRet = relocation_section->get_size() / relocation_section->get_entry_size(); } return nRet; } //------------------------------------------------------------------------------ bool get_entry( Elf_Xword index, Elf64_Addr& offset, Elf_Word& symbol, Elf_Word& type, Elf_Sxword& addend ) const { if ( index >= get_entries_num() ) { // Is index valid return false; } if ( elf_file.get_class() == ELFCLASS32 ) { if ( SHT_REL == relocation_section->get_type() ) { generic_get_entry_rel( index, offset, symbol, type, addend ); } else if ( SHT_RELA == relocation_section->get_type() ) { generic_get_entry_rela( index, offset, symbol, type, addend ); } } else { if ( SHT_REL == relocation_section->get_type() ) { generic_get_entry_rel( index, offset, symbol, type, addend ); } else if ( SHT_RELA == relocation_section->get_type() ) { generic_get_entry_rela( index, offset, symbol, type, addend ); } } return true; } //------------------------------------------------------------------------------ bool get_entry( Elf_Xword index, Elf64_Addr& offset, Elf64_Addr& symbolValue, std::string& symbolName, Elf_Word& type, Elf_Sxword& addend, Elf_Sxword& calcValue ) const { // Do regular job Elf_Word symbol; bool ret = get_entry( index, offset, symbol, type, addend ); // Find the symbol Elf_Xword size; unsigned char bind; unsigned char symbolType; Elf_Half section; unsigned char other; symbol_section_accessor symbols( elf_file, elf_file.sections[get_symbol_table_index()] ); ret = ret && symbols.get_symbol( symbol, symbolName, symbolValue, size, bind, symbolType, section, other ); if ( ret ) { // Was it successful? switch ( type ) { case R_386_NONE: // none calcValue = 0; break; case R_386_32: // S + A calcValue = symbolValue + addend; break; case R_386_PC32: // S + A - P calcValue = symbolValue + addend - offset; break; case R_386_GOT32: // G + A - P calcValue = 0; break; case R_386_PLT32: // L + A - P calcValue = 0; break; case R_386_COPY: // none calcValue = 0; break; case R_386_GLOB_DAT: // S case R_386_JMP_SLOT: // S calcValue = symbolValue; break; case R_386_RELATIVE: // B + A calcValue = addend; break; case R_386_GOTOFF: // S + A - GOT calcValue = 0; break; case R_386_GOTPC: // GOT + A - P calcValue = 0; break; default: // Not recognized symbol! calcValue = 0; break; } } return ret; } //------------------------------------------------------------------------------ bool set_entry( Elf_Xword index, Elf64_Addr offset, Elf_Word symbol, Elf_Word type, Elf_Sxword addend ) { if ( index >= get_entries_num() ) { // Is index valid return false; } if ( elf_file.get_class() == ELFCLASS32 ) { if ( SHT_REL == relocation_section->get_type() ) { generic_set_entry_rel( index, offset, symbol, type, addend ); } else if ( SHT_RELA == relocation_section->get_type() ) { generic_set_entry_rela( index, offset, symbol, type, addend ); } } else { if ( SHT_REL == relocation_section->get_type() ) { generic_set_entry_rel( index, offset, symbol, type, addend ); } else if ( SHT_RELA == relocation_section->get_type() ) { generic_set_entry_rela( index, offset, symbol, type, addend ); } } return true; } //------------------------------------------------------------------------------ void add_entry( Elf64_Addr offset, Elf_Xword info ) { if ( elf_file.get_class() == ELFCLASS32 ) { generic_add_entry( offset, info ); } else { generic_add_entry( offset, info ); } } //------------------------------------------------------------------------------ void add_entry( Elf64_Addr offset, Elf_Word symbol, unsigned char type ) { Elf_Xword info; if ( elf_file.get_class() == ELFCLASS32 ) { info = ELF32_R_INFO( (Elf_Xword)symbol, type ); } else { info = ELF64_R_INFO( (Elf_Xword)symbol, type ); } add_entry( offset, info ); } //------------------------------------------------------------------------------ void add_entry( Elf64_Addr offset, Elf_Xword info, Elf_Sxword addend ) { if ( elf_file.get_class() == ELFCLASS32 ) { generic_add_entry( offset, info, addend ); } else { generic_add_entry( offset, info, addend ); } } //------------------------------------------------------------------------------ void add_entry( Elf64_Addr offset, Elf_Word symbol, unsigned char type, Elf_Sxword addend ) { Elf_Xword info; if ( elf_file.get_class() == ELFCLASS32 ) { info = ELF32_R_INFO( (Elf_Xword)symbol, type ); } else { info = ELF64_R_INFO( (Elf_Xword)symbol, type ); } add_entry( offset, info, addend ); } //------------------------------------------------------------------------------ void add_entry( string_section_accessor str_writer, const char* str, symbol_section_accessor sym_writer, Elf64_Addr value, Elf_Word size, unsigned char sym_info, unsigned char other, Elf_Half shndx, Elf64_Addr offset, unsigned char type ) { Elf_Word str_index = str_writer.add_string( str ); Elf_Word sym_index = sym_writer.add_symbol( str_index, value, size, sym_info, other, shndx ); add_entry( offset, sym_index, type ); } //------------------------------------------------------------------------------ void swap_symbols( Elf_Xword first, Elf_Xword second ) { Elf64_Addr offset; Elf_Word symbol; Elf_Word rtype; Elf_Sxword addend; for ( Elf_Word i = 0; i < get_entries_num(); i++ ) { get_entry( i, offset, symbol, rtype, addend ); if ( symbol == first ) { set_entry( i, offset, (Elf_Word)second, rtype, addend ); } if ( symbol == second ) { set_entry( i, offset, (Elf_Word)first, rtype, addend ); } } } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ Elf_Half get_symbol_table_index() const { return (Elf_Half)relocation_section->get_link(); } //------------------------------------------------------------------------------ template void generic_get_entry_rel( Elf_Xword index, Elf64_Addr& offset, Elf_Word& symbol, Elf_Word& type, Elf_Sxword& addend ) const { const endianess_convertor& convertor = elf_file.get_convertor(); const T* pEntry = reinterpret_cast( relocation_section->get_data() + index * relocation_section->get_entry_size() ); offset = convertor( pEntry->r_offset ); Elf_Xword tmp = convertor( pEntry->r_info ); symbol = get_sym_and_type::get_r_sym( tmp ); type = get_sym_and_type::get_r_type( tmp ); addend = 0; } //------------------------------------------------------------------------------ template void generic_get_entry_rela( Elf_Xword index, Elf64_Addr& offset, Elf_Word& symbol, Elf_Word& type, Elf_Sxword& addend ) const { const endianess_convertor& convertor = elf_file.get_convertor(); const T* pEntry = reinterpret_cast( relocation_section->get_data() + index * relocation_section->get_entry_size() ); offset = convertor( pEntry->r_offset ); Elf_Xword tmp = convertor( pEntry->r_info ); symbol = get_sym_and_type::get_r_sym( tmp ); type = get_sym_and_type::get_r_type( tmp ); addend = convertor( pEntry->r_addend ); } //------------------------------------------------------------------------------ template void generic_set_entry_rel( Elf_Xword index, Elf64_Addr offset, Elf_Word symbol, Elf_Word type, Elf_Sxword ) { const endianess_convertor& convertor = elf_file.get_convertor(); T* pEntry = const_cast( reinterpret_cast( relocation_section->get_data() + index * relocation_section->get_entry_size() ) ); if ( elf_file.get_class() == ELFCLASS32 ) { pEntry->r_info = ELF32_R_INFO( (Elf_Xword)symbol, type ); } else { pEntry->r_info = ELF64_R_INFO( (Elf_Xword)symbol, type ); } pEntry->r_offset = offset; pEntry->r_offset = convertor( pEntry->r_offset ); pEntry->r_info = convertor( pEntry->r_info ); } //------------------------------------------------------------------------------ template void generic_set_entry_rela( Elf_Xword index, Elf64_Addr offset, Elf_Word symbol, Elf_Word type, Elf_Sxword addend ) { const endianess_convertor& convertor = elf_file.get_convertor(); T* pEntry = const_cast( reinterpret_cast( relocation_section->get_data() + index * relocation_section->get_entry_size() ) ); if ( elf_file.get_class() == ELFCLASS32 ) { pEntry->r_info = ELF32_R_INFO( (Elf_Xword)symbol, type ); } else { pEntry->r_info = ELF64_R_INFO( (Elf_Xword)symbol, type ); } pEntry->r_offset = offset; pEntry->r_addend = addend; pEntry->r_offset = convertor( pEntry->r_offset ); pEntry->r_info = convertor( pEntry->r_info ); pEntry->r_addend = convertor( pEntry->r_addend ); } //------------------------------------------------------------------------------ template void generic_add_entry( Elf64_Addr offset, Elf_Xword info ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; entry.r_offset = offset; entry.r_info = info; entry.r_offset = convertor( entry.r_offset ); entry.r_info = convertor( entry.r_info ); relocation_section->append_data( reinterpret_cast( &entry ), sizeof( entry ) ); } //------------------------------------------------------------------------------ template void generic_add_entry( Elf64_Addr offset, Elf_Xword info, Elf_Sxword addend ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; entry.r_offset = offset; entry.r_info = info; entry.r_addend = addend; entry.r_offset = convertor( entry.r_offset ); entry.r_info = convertor( entry.r_info ); entry.r_addend = convertor( entry.r_addend ); relocation_section->append_data( reinterpret_cast( &entry ), sizeof( entry ) ); } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* relocation_section; }; using relocation_section_accessor = relocation_section_accessor_template
; using const_relocation_section_accessor = relocation_section_accessor_template; } // namespace ELFIO #endif // ELFIO_RELOCATION_HPP /*** End of inlined file: elfio_relocation.hpp ***/ /*** Start of inlined file: elfio_dynamic.hpp ***/ #ifndef ELFIO_DYNAMIC_HPP #define ELFIO_DYNAMIC_HPP namespace ELFIO { //------------------------------------------------------------------------------ template class dynamic_section_accessor_template { public: //------------------------------------------------------------------------------ dynamic_section_accessor_template( const elfio& elf_file_, S* section_ ) : elf_file( elf_file_ ), dynamic_section( section_ ) { } //------------------------------------------------------------------------------ Elf_Xword get_entries_num() const { Elf_Xword nRet = 0; if ( 0 != dynamic_section->get_entry_size() ) { nRet = dynamic_section->get_size() / dynamic_section->get_entry_size(); } return nRet; } //------------------------------------------------------------------------------ bool get_entry( Elf_Xword index, Elf_Xword& tag, Elf_Xword& value, std::string& str ) const { if ( index >= get_entries_num() ) { // Is index valid return false; } if ( elf_file.get_class() == ELFCLASS32 ) { generic_get_entry_dyn( index, tag, value ); } else { generic_get_entry_dyn( index, tag, value ); } // If the tag may have a string table reference, prepare the string if ( tag == DT_NEEDED || tag == DT_SONAME || tag == DT_RPATH || tag == DT_RUNPATH ) { string_section_accessor strsec = elf_file.sections[get_string_table_index()]; const char* result = strsec.get_string( value ); if ( 0 == result ) { str.clear(); return false; } str = result; } else { str.clear(); } return true; } //------------------------------------------------------------------------------ void add_entry( Elf_Xword tag, Elf_Xword value ) { if ( elf_file.get_class() == ELFCLASS32 ) { generic_add_entry( tag, value ); } else { generic_add_entry( tag, value ); } } //------------------------------------------------------------------------------ void add_entry( Elf_Xword tag, const std::string& str ) { string_section_accessor strsec = elf_file.sections[get_string_table_index()]; Elf_Xword value = strsec.add_string( str ); add_entry( tag, value ); } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ Elf_Half get_string_table_index() const { return (Elf_Half)dynamic_section->get_link(); } //------------------------------------------------------------------------------ template void generic_get_entry_dyn( Elf_Xword index, Elf_Xword& tag, Elf_Xword& value ) const { const endianess_convertor& convertor = elf_file.get_convertor(); // Check unusual case when dynamic section has no data if ( dynamic_section->get_data() == 0 || ( index + 1 ) * dynamic_section->get_entry_size() > dynamic_section->get_size() ) { tag = DT_NULL; value = 0; return; } const T* pEntry = reinterpret_cast( dynamic_section->get_data() + index * dynamic_section->get_entry_size() ); tag = convertor( pEntry->d_tag ); switch ( tag ) { case DT_NULL: case DT_SYMBOLIC: case DT_TEXTREL: case DT_BIND_NOW: value = 0; break; case DT_NEEDED: case DT_PLTRELSZ: case DT_RELASZ: case DT_RELAENT: case DT_STRSZ: case DT_SYMENT: case DT_SONAME: case DT_RPATH: case DT_RELSZ: case DT_RELENT: case DT_PLTREL: case DT_INIT_ARRAYSZ: case DT_FINI_ARRAYSZ: case DT_RUNPATH: case DT_FLAGS: case DT_PREINIT_ARRAYSZ: value = convertor( pEntry->d_un.d_val ); break; case DT_PLTGOT: case DT_HASH: case DT_STRTAB: case DT_SYMTAB: case DT_RELA: case DT_INIT: case DT_FINI: case DT_REL: case DT_DEBUG: case DT_JMPREL: case DT_INIT_ARRAY: case DT_FINI_ARRAY: case DT_PREINIT_ARRAY: default: value = convertor( pEntry->d_un.d_ptr ); break; } } //------------------------------------------------------------------------------ template void generic_add_entry( Elf_Xword tag, Elf_Xword value ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; switch ( tag ) { case DT_NULL: case DT_SYMBOLIC: case DT_TEXTREL: case DT_BIND_NOW: value = 0; case DT_NEEDED: case DT_PLTRELSZ: case DT_RELASZ: case DT_RELAENT: case DT_STRSZ: case DT_SYMENT: case DT_SONAME: case DT_RPATH: case DT_RELSZ: case DT_RELENT: case DT_PLTREL: case DT_INIT_ARRAYSZ: case DT_FINI_ARRAYSZ: case DT_RUNPATH: case DT_FLAGS: case DT_PREINIT_ARRAYSZ: entry.d_un.d_val = convertor( value ); break; case DT_PLTGOT: case DT_HASH: case DT_STRTAB: case DT_SYMTAB: case DT_RELA: case DT_INIT: case DT_FINI: case DT_REL: case DT_DEBUG: case DT_JMPREL: case DT_INIT_ARRAY: case DT_FINI_ARRAY: case DT_PREINIT_ARRAY: default: entry.d_un.d_ptr = convertor( value ); break; } entry.d_tag = convertor( tag ); dynamic_section->append_data( reinterpret_cast( &entry ), sizeof( entry ) ); } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* dynamic_section; }; using dynamic_section_accessor = dynamic_section_accessor_template
; using const_dynamic_section_accessor = dynamic_section_accessor_template; } // namespace ELFIO #endif // ELFIO_DYNAMIC_HPP /*** End of inlined file: elfio_dynamic.hpp ***/ /*** Start of inlined file: elfio_modinfo.hpp ***/ #ifndef ELFIO_MODINFO_HPP #define ELFIO_MODINFO_HPP #include #include namespace ELFIO { //------------------------------------------------------------------------------ template class modinfo_section_accessor_template { public: //------------------------------------------------------------------------------ modinfo_section_accessor_template( S* section_ ) : modinfo_section( section_ ) { process_section(); } //------------------------------------------------------------------------------ Elf_Word get_attribute_num() const { return (Elf_Word)content.size(); } //------------------------------------------------------------------------------ bool get_attribute( Elf_Word no, std::string& field, std::string& value ) const { if ( no < content.size() ) { field = content[no].first; value = content[no].second; return true; } return false; } //------------------------------------------------------------------------------ bool get_attribute( std::string field_name, std::string& value ) const { for ( auto i = content.begin(); i != content.end(); i++ ) { if ( field_name == i->first ) { value = i->second; return true; } } return false; } //------------------------------------------------------------------------------ Elf_Word add_attribute( std::string field, std::string value ) { Elf_Word current_position = 0; if ( modinfo_section ) { // Strings are addeded to the end of the current section data current_position = (Elf_Word)modinfo_section->get_size(); std::string attribute = field + "=" + value; modinfo_section->append_data( attribute + '\0' ); content.push_back( std::pair( field, value ) ); } return current_position; } //------------------------------------------------------------------------------ private: void process_section() { const char* pdata = modinfo_section->get_data(); if ( pdata ) { ELFIO::Elf_Xword i = 0; while ( i < modinfo_section->get_size() ) { while ( i < modinfo_section->get_size() && !pdata[i] ) i++; if ( i < modinfo_section->get_size() ) { std::string info = pdata + i; size_t loc = info.find( '=' ); std::pair attribute( info.substr( 0, loc ), info.substr( loc + 1 ) ); content.push_back( attribute ); i += info.length(); } } } } //------------------------------------------------------------------------------ private: S* modinfo_section; std::vector> content; }; using modinfo_section_accessor = modinfo_section_accessor_template
; using const_modinfo_section_accessor = modinfo_section_accessor_template; } // namespace ELFIO #endif // ELFIO_MODINFO_HPP /*** End of inlined file: elfio_modinfo.hpp ***/ #ifdef _MSC_VER #pragma warning( pop ) #endif #endif // ELFIO_HPP /*** End of inlined file: elfio.hpp ***/ namespace ELFIO { static struct class_table_t { const char key; const char* str; } class_table[] = { { ELFCLASS32, "ELF32" }, { ELFCLASS64, "ELF64" }, }; static struct endian_table_t { const char key; const char* str; } endian_table[] = { { ELFDATANONE, "None" }, { ELFDATA2LSB, "Little endian" }, { ELFDATA2MSB, "Big endian" }, }; static struct version_table_t { const Elf64_Word key; const char* str; } version_table[] = { { EV_NONE, "None" }, { EV_CURRENT, "Current" }, }; static struct type_table_t { const Elf32_Half key; const char* str; } type_table[] = { { ET_NONE, "No file type" }, { ET_REL, "Relocatable file" }, { ET_EXEC, "Executable file" }, { ET_DYN, "Shared object file" }, { ET_CORE, "Core file" }, }; static struct machine_table_t { const Elf64_Half key; const char* str; } machine_table[] = { { EM_NONE, "No machine" }, { EM_M32, "AT&T WE 32100" }, { EM_SPARC, "SUN SPARC" }, { EM_386, "Intel 80386" }, { EM_68K, "Motorola m68k family" }, { EM_88K, "Motorola m88k family" }, { EM_486, "Intel 80486// Reserved for future use" }, { EM_860, "Intel 80860" }, { EM_MIPS, "MIPS R3000 (officially, big-endian only)" }, { EM_S370, "IBM System/370" }, { EM_MIPS_RS3_LE, "MIPS R3000 little-endian (Oct 4 1999 Draft) Deprecated" }, { EM_res011, "Reserved" }, { EM_res012, "Reserved" }, { EM_res013, "Reserved" }, { EM_res014, "Reserved" }, { EM_PARISC, "HPPA" }, { EM_res016, "Reserved" }, { EM_VPP550, "Fujitsu VPP500" }, { EM_SPARC32PLUS, "Sun's v8plus" }, { EM_960, "Intel 80960" }, { EM_PPC, "PowerPC" }, { EM_PPC64, "64-bit PowerPC" }, { EM_S390, "IBM S/390" }, { EM_SPU, "Sony/Toshiba/IBM SPU" }, { EM_res024, "Reserved" }, { EM_res025, "Reserved" }, { EM_res026, "Reserved" }, { EM_res027, "Reserved" }, { EM_res028, "Reserved" }, { EM_res029, "Reserved" }, { EM_res030, "Reserved" }, { EM_res031, "Reserved" }, { EM_res032, "Reserved" }, { EM_res033, "Reserved" }, { EM_res034, "Reserved" }, { EM_res035, "Reserved" }, { EM_V800, "NEC V800 series" }, { EM_FR20, "Fujitsu FR20" }, { EM_RH32, "TRW RH32" }, { EM_MCORE, "Motorola M*Core // May also be taken by Fujitsu MMA" }, { EM_RCE, "Old name for MCore" }, { EM_ARM, "ARM" }, { EM_OLD_ALPHA, "Digital Alpha" }, { EM_SH, "Renesas (formerly Hitachi) / SuperH SH" }, { EM_SPARCV9, "SPARC v9 64-bit" }, { EM_TRICORE, "Siemens Tricore embedded processor" }, { EM_ARC, "ARC Cores" }, { EM_H8_300, "Renesas (formerly Hitachi) H8/300" }, { EM_H8_300H, "Renesas (formerly Hitachi) H8/300H" }, { EM_H8S, "Renesas (formerly Hitachi) H8S" }, { EM_H8_500, "Renesas (formerly Hitachi) H8/500" }, { EM_IA_64, "Intel IA-64 Processor" }, { EM_MIPS_X, "Stanford MIPS-X" }, { EM_COLDFIRE, "Motorola Coldfire" }, { EM_68HC12, "Motorola M68HC12" }, { EM_MMA, "Fujitsu Multimedia Accelerator" }, { EM_PCP, "Siemens PCP" }, { EM_NCPU, "Sony nCPU embedded RISC processor" }, { EM_NDR1, "Denso NDR1 microprocesspr" }, { EM_STARCORE, "Motorola Star*Core processor" }, { EM_ME16, "Toyota ME16 processor" }, { EM_ST100, "STMicroelectronics ST100 processor" }, { EM_TINYJ, "Advanced Logic Corp. TinyJ embedded processor" }, { EM_X86_64, "Advanced Micro Devices X86-64 processor" }, { EM_PDSP, "Sony DSP Processor" }, { EM_PDP10, "Digital Equipment Corp. PDP-10" }, { EM_PDP11, "Digital Equipment Corp. PDP-11" }, { EM_FX66, "Siemens FX66 microcontroller" }, { EM_ST9PLUS, "STMicroelectronics ST9+ 8/16 bit microcontroller" }, { EM_ST7, "STMicroelectronics ST7 8-bit microcontroller" }, { EM_68HC16, "Motorola MC68HC16 Microcontroller" }, { EM_68HC11, "Motorola MC68HC11 Microcontroller" }, { EM_68HC08, "Motorola MC68HC08 Microcontroller" }, { EM_68HC05, "Motorola MC68HC05 Microcontroller" }, { EM_SVX, "Silicon Graphics SVx" }, { EM_ST19, "STMicroelectronics ST19 8-bit cpu" }, { EM_VAX, "Digital VAX" }, { EM_CRIS, "Axis Communications 32-bit embedded processor" }, { EM_JAVELIN, "Infineon Technologies 32-bit embedded cpu" }, { EM_FIREPATH, "Element 14 64-bit DSP processor" }, { EM_ZSP, "LSI Logic's 16-bit DSP processor" }, { EM_MMIX, "Donald Knuth's educational 64-bit processor" }, { EM_HUANY, "Harvard's machine-independent format" }, { EM_PRISM, "SiTera Prism" }, { EM_AVR, "Atmel AVR 8-bit microcontroller" }, { EM_FR30, "Fujitsu FR30" }, { EM_D10V, "Mitsubishi D10V" }, { EM_D30V, "Mitsubishi D30V" }, { EM_V850, "NEC v850" }, { EM_M32R, "Renesas M32R (formerly Mitsubishi M32R)" }, { EM_MN10300, "Matsushita MN10300" }, { EM_MN10200, "Matsushita MN10200" }, { EM_PJ, "picoJava" }, { EM_OPENRISC, "OpenRISC 32-bit embedded processor" }, { EM_ARC_A5, "ARC Cores Tangent-A5" }, { EM_XTENSA, "Tensilica Xtensa Architecture" }, { EM_VIDEOCORE, "Alphamosaic VideoCore processor" }, { EM_TMM_GPP, "Thompson Multimedia General Purpose Processor" }, { EM_NS32K, "National Semiconductor 32000 series" }, { EM_TPC, "Tenor Network TPC processor" }, { EM_SNP1K, "Trebia SNP 1000 processor" }, { EM_ST200, "STMicroelectronics ST200 microcontroller" }, { EM_IP2K, "Ubicom IP2022 micro controller" }, { EM_MAX, "MAX Processor" }, { EM_CR, "National Semiconductor CompactRISC" }, { EM_F2MC16, "Fujitsu F2MC16" }, { EM_MSP430, "TI msp430 micro controller" }, { EM_BLACKFIN, "ADI Blackfin" }, { EM_SE_C33, "S1C33 Family of Seiko Epson processors" }, { EM_SEP, "Sharp embedded microprocessor" }, { EM_ARCA, "Arca RISC Microprocessor" }, { EM_UNICORE, "Microprocessor series from PKU-Unity Ltd. and MPRC of " "Peking University" }, { EM_EXCESS, "eXcess: 16/32/64-bit configurable embedded CPU" }, { EM_DXP, "Icera Semiconductor Inc. Deep Execution Processor" }, { EM_ALTERA_NIOS2, "Altera Nios II soft-core processor" }, { EM_CRX, "National Semiconductor CRX" }, { EM_XGATE, "Motorola XGATE embedded processor" }, { EM_C166, "Infineon C16x/XC16x processor" }, { EM_M16C, "Renesas M16C series microprocessors" }, { EM_DSPIC30F, "Microchip Technology dsPIC30F Digital Signal Controller" }, { EM_CE, "Freescale Communication Engine RISC core" }, { EM_M32C, "Renesas M32C series microprocessors" }, { EM_res121, "Reserved" }, { EM_res122, "Reserved" }, { EM_res123, "Reserved" }, { EM_res124, "Reserved" }, { EM_res125, "Reserved" }, { EM_res126, "Reserved" }, { EM_res127, "Reserved" }, { EM_res128, "Reserved" }, { EM_res129, "Reserved" }, { EM_res130, "Reserved" }, { EM_TSK3000, "Altium TSK3000 core" }, { EM_RS08, "Freescale RS08 embedded processor" }, { EM_res133, "Reserved" }, { EM_ECOG2, "Cyan Technology eCOG2 microprocessor" }, { EM_SCORE, "Sunplus Score" }, { EM_SCORE7, "Sunplus S+core7 RISC processor" }, { EM_DSP24, "New Japan Radio (NJR) 24-bit DSP Processor" }, { EM_VIDEOCORE3, "Broadcom VideoCore III processor" }, { EM_LATTICEMICO32, "RISC processor for Lattice FPGA architecture" }, { EM_SE_C17, "Seiko Epson C17 family" }, { EM_TI_C6000, "Texas Instruments TMS320C6000 DSP family" }, { EM_TI_C2000, "Texas Instruments TMS320C2000 DSP family" }, { EM_TI_C5500, "Texas Instruments TMS320C55x DSP family" }, { EM_res143, "Reserved" }, { EM_res144, "Reserved" }, { EM_res145, "Reserved" }, { EM_res146, "Reserved" }, { EM_res147, "Reserved" }, { EM_res148, "Reserved" }, { EM_res149, "Reserved" }, { EM_res150, "Reserved" }, { EM_res151, "Reserved" }, { EM_res152, "Reserved" }, { EM_res153, "Reserved" }, { EM_res154, "Reserved" }, { EM_res155, "Reserved" }, { EM_res156, "Reserved" }, { EM_res157, "Reserved" }, { EM_res158, "Reserved" }, { EM_res159, "Reserved" }, { EM_MMDSP_PLUS, "STMicroelectronics 64bit VLIW Data Signal Processor" }, { EM_CYPRESS_M8C, "Cypress M8C microprocessor" }, { EM_R32C, "Renesas R32C series microprocessors" }, { EM_TRIMEDIA, "NXP Semiconductors TriMedia architecture family" }, { EM_QDSP6, "QUALCOMM DSP6 Processor" }, { EM_8051, "Intel 8051 and variants" }, { EM_STXP7X, "STMicroelectronics STxP7x family" }, { EM_NDS32, "Andes Technology compact code size embedded RISC processor family" }, { EM_ECOG1, "Cyan Technology eCOG1X family" }, { EM_ECOG1X, "Cyan Technology eCOG1X family" }, { EM_MAXQ30, "Dallas Semiconductor MAXQ30 Core Micro-controllers" }, { EM_XIMO16, "New Japan Radio (NJR) 16-bit DSP Processor" }, { EM_MANIK, "M2000 Reconfigurable RISC Microprocessor" }, { EM_CRAYNV2, "Cray Inc. NV2 vector architecture" }, { EM_RX, "Renesas RX family" }, { EM_METAG, "Imagination Technologies META processor architecture" }, { EM_MCST_ELBRUS, "MCST Elbrus general purpose hardware architecture" }, { EM_ECOG16, "Cyan Technology eCOG16 family" }, { EM_CR16, "National Semiconductor CompactRISC 16-bit processor" }, { EM_ETPU, "Freescale Extended Time Processing Unit" }, { EM_SLE9X, "Infineon Technologies SLE9X core" }, { EM_L1OM, "Intel L1OM" }, { EM_INTEL181, "Reserved by Intel" }, { EM_INTEL182, "Reserved by Intel" }, { EM_res183, "Reserved by ARM" }, { EM_res184, "Reserved by ARM" }, { EM_AVR32, "Atmel Corporation 32-bit microprocessor family" }, { EM_STM8, "STMicroeletronics STM8 8-bit microcontroller" }, { EM_TILE64, "Tilera TILE64 multicore architecture family" }, { EM_TILEPRO, "Tilera TILEPro multicore architecture family" }, { EM_MICROBLAZE, "Xilinx MicroBlaze 32-bit RISC soft processor core" }, { EM_CUDA, "NVIDIA CUDA architecture " }, }; static struct section_type_table_t { const Elf64_Half key; const char* str; } section_type_table[] = { { SHT_NULL, "NULL" }, { SHT_PROGBITS, "PROGBITS" }, { SHT_SYMTAB, "SYMTAB" }, { SHT_STRTAB, "STRTAB" }, { SHT_RELA, "RELA" }, { SHT_HASH, "HASH" }, { SHT_DYNAMIC, "DYNAMIC" }, { SHT_NOTE, "NOTE" }, { SHT_NOBITS, "NOBITS" }, { SHT_REL, "REL" }, { SHT_SHLIB, "SHLIB" }, { SHT_DYNSYM, "DYNSYM" }, { SHT_INIT_ARRAY, "INIT_ARRAY" }, { SHT_FINI_ARRAY, "FINI_ARRAY" }, { SHT_PREINIT_ARRAY, "PREINIT_ARRAY" }, { SHT_GROUP, "GROUP" }, { SHT_SYMTAB_SHNDX, "SYMTAB_SHNDX " }, }; static struct segment_type_table_t { const Elf_Word key; const char* str; } segment_type_table[] = { { PT_NULL, "NULL" }, { PT_LOAD, "LOAD" }, { PT_DYNAMIC, "DYNAMIC" }, { PT_INTERP, "INTERP" }, { PT_NOTE, "NOTE" }, { PT_SHLIB, "SHLIB" }, { PT_PHDR, "PHDR" }, { PT_TLS, "TLS" }, }; static struct segment_flag_table_t { const Elf_Word key; const char* str; } segment_flag_table[] = { { 0, "" }, { 1, "X" }, { 2, "W" }, { 3, "WX" }, { 4, "R" }, { 5, "RX" }, { 6, "RW" }, { 7, "RWX" }, }; static struct symbol_bind_t { const Elf_Word key; const char* str; } symbol_bind_table[] = { { STB_LOCAL, "LOCAL" }, { STB_GLOBAL, "GLOBAL" }, { STB_WEAK, "WEAK" }, { STB_LOOS, "LOOS" }, { STB_HIOS, "HIOS" }, { STB_MULTIDEF, "MULTIDEF" }, { STB_LOPROC, "LOPROC" }, { STB_HIPROC, "HIPROC" }, }; static struct symbol_type_t { const Elf_Word key; const char* str; } symbol_type_table[] = { { STT_NOTYPE, "NOTYPE" }, { STT_OBJECT, "OBJECT" }, { STT_FUNC, "FUNC" }, { STT_SECTION, "SECTION" }, { STT_FILE, "FILE" }, { STT_COMMON, "COMMON" }, { STT_TLS, "TLS" }, { STT_LOOS, "LOOS" }, { STT_HIOS, "HIOS" }, { STT_LOPROC, "LOPROC" }, { STT_HIPROC, "HIPROC" }, }; static struct dynamic_tag_t { const Elf_Word key; const char* str; } dynamic_tag_table[] = { { DT_NULL, "NULL" }, { DT_NEEDED, "NEEDED" }, { DT_PLTRELSZ, "PLTRELSZ" }, { DT_PLTGOT, "PLTGOT" }, { DT_HASH, "HASH" }, { DT_STRTAB, "STRTAB" }, { DT_SYMTAB, "SYMTAB" }, { DT_RELA, "RELA" }, { DT_RELASZ, "RELASZ" }, { DT_RELAENT, "RELAENT" }, { DT_STRSZ, "STRSZ" }, { DT_SYMENT, "SYMENT" }, { DT_INIT, "INIT" }, { DT_FINI, "FINI" }, { DT_SONAME, "SONAME" }, { DT_RPATH, "RPATH" }, { DT_SYMBOLIC, "SYMBOLIC" }, { DT_REL, "REL" }, { DT_RELSZ, "RELSZ" }, { DT_RELENT, "RELENT" }, { DT_PLTREL, "PLTREL" }, { DT_DEBUG, "DEBUG" }, { DT_TEXTREL, "TEXTREL" }, { DT_JMPREL, "JMPREL" }, { DT_BIND_NOW, "BIND_NOW" }, { DT_INIT_ARRAY, "INIT_ARRAY" }, { DT_FINI_ARRAY, "FINI_ARRAY" }, { DT_INIT_ARRAYSZ, "INIT_ARRAYSZ" }, { DT_FINI_ARRAYSZ, "FINI_ARRAYSZ" }, { DT_RUNPATH, "RUNPATH" }, { DT_FLAGS, "FLAGS" }, { DT_ENCODING, "ENCODING" }, { DT_PREINIT_ARRAY, "PREINIT_ARRAY" }, { DT_PREINIT_ARRAYSZ, "PREINIT_ARRAYSZ" }, { DT_MAXPOSTAGS, "MAXPOSTAGS" }, }; static const ELFIO::Elf_Xword MAX_DATA_ENTRIES = 64; //------------------------------------------------------------------------------ class dump { #define DUMP_DEC_FORMAT( width ) \ std::setw( width ) << std::setfill( ' ' ) << std::dec << std::right #define DUMP_HEX_FORMAT( width ) \ std::setw( width ) << std::setfill( '0' ) << std::hex << std::right #define DUMP_STR_FORMAT( width ) \ std::setw( width ) << std::setfill( ' ' ) << std::hex << std::left public: //------------------------------------------------------------------------------ static void header( std::ostream& out, const elfio& reader ) { if ( !reader.get_header_size() ) { return; } out << "ELF Header" << std::endl << std::endl << " Class: " << str_class( reader.get_class() ) << std::endl << " Encoding: " << str_endian( reader.get_encoding() ) << std::endl << " ELFVersion: " << str_version( reader.get_elf_version() ) << std::endl << " Type: " << str_type( reader.get_type() ) << std::endl << " Machine: " << str_machine( reader.get_machine() ) << std::endl << " Version: " << str_version( reader.get_version() ) << std::endl << " Entry: " << "0x" << std::hex << reader.get_entry() << std::endl << " Flags: " << "0x" << std::hex << reader.get_flags() << std::endl << std::endl; } //------------------------------------------------------------------------------ static void section_headers( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.sections.size(); if ( n == 0 ) { return; } out << "Section Headers:" << std::endl; if ( reader.get_class() == ELFCLASS32 ) { // Output for 32-bit out << "[ Nr ] Type Addr Size ES Flg Lk Inf " "Al Name" << std::endl; } else { // Output for 64-bit out << "[ Nr ] Type Addr Size " " ES Flg" << std::endl << " Lk Inf Al Name" << std::endl; } for ( Elf_Half i = 0; i < n; ++i ) { // For all sections section* sec = reader.sections[i]; section_header( out, i, sec, reader.get_class() ); } out << "Key to Flags: W (write), A (alloc), X (execute)\n\n" << std::endl; } //------------------------------------------------------------------------------ static void section_header( std::ostream& out, Elf_Half no, const section* sec, unsigned char elf_class ) { std::ios_base::fmtflags original_flags = out.flags(); if ( elf_class == ELFCLASS32 ) { // Output for 32-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 17 ) << str_section_type( sec->get_type() ) << " " << DUMP_HEX_FORMAT( 8 ) << sec->get_address() << " " << DUMP_HEX_FORMAT( 8 ) << sec->get_size() << " " << DUMP_HEX_FORMAT( 2 ) << sec->get_entry_size() << " " << DUMP_STR_FORMAT( 3 ) << section_flags( sec->get_flags() ) << " " << DUMP_HEX_FORMAT( 2 ) << sec->get_link() << " " << DUMP_HEX_FORMAT( 3 ) << sec->get_info() << " " << DUMP_HEX_FORMAT( 2 ) << sec->get_addr_align() << " " << DUMP_STR_FORMAT( 17 ) << sec->get_name() << " " << std::endl; } else { // Output for 64-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 17 ) << str_section_type( sec->get_type() ) << " " << DUMP_HEX_FORMAT( 16 ) << sec->get_address() << " " << DUMP_HEX_FORMAT( 16 ) << sec->get_size() << " " << DUMP_HEX_FORMAT( 4 ) << sec->get_entry_size() << " " << DUMP_STR_FORMAT( 3 ) << section_flags( sec->get_flags() ) << " " << std::endl << " " << DUMP_HEX_FORMAT( 4 ) << sec->get_link() << " " << DUMP_HEX_FORMAT( 4 ) << sec->get_info() << " " << DUMP_HEX_FORMAT( 4 ) << sec->get_addr_align() << " " << DUMP_STR_FORMAT( 17 ) << sec->get_name() << " " << std::endl; } out.flags( original_flags ); return; } //------------------------------------------------------------------------------ static void segment_headers( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.segments.size(); if ( n == 0 ) { return; } out << "Segment headers:" << std::endl; if ( reader.get_class() == ELFCLASS32 ) { // Output for 32-bit out << "[ Nr ] Type VirtAddr PhysAddr FileSize Mem.Size " "Flags Align" << std::endl; } else { // Output for 64-bit out << "[ Nr ] Type VirtAddr PhysAddr " "Flags" << std::endl << " FileSize Mem.Size " "Align" << std::endl; } for ( Elf_Half i = 0; i < n; ++i ) { segment* seg = reader.segments[i]; segment_header( out, i, seg, reader.get_class() ); } out << std::endl; } //------------------------------------------------------------------------------ static void segment_header( std::ostream& out, Elf_Half no, const segment* seg, unsigned int elf_class ) { std::ios_base::fmtflags original_flags = out.flags(); if ( elf_class == ELFCLASS32 ) { // Output for 32-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 14 ) << str_segment_type( seg->get_type() ) << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_virtual_address() << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_physical_address() << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_file_size() << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_memory_size() << " " << DUMP_STR_FORMAT( 8 ) << str_segment_flag( seg->get_flags() ) << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_align() << " " << std::endl; } else { // Output for 64-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 14 ) << str_segment_type( seg->get_type() ) << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_virtual_address() << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_physical_address() << " " << DUMP_STR_FORMAT( 16 ) << str_segment_flag( seg->get_flags() ) << " " << std::endl << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_file_size() << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_memory_size() << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_align() << " " << std::endl; } out.flags( original_flags ); } //------------------------------------------------------------------------------ static void symbol_tables( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.sections.size(); for ( Elf_Half i = 0; i < n; ++i ) { // For all sections section* sec = reader.sections[i]; if ( SHT_SYMTAB == sec->get_type() || SHT_DYNSYM == sec->get_type() ) { symbol_section_accessor symbols( reader, sec ); Elf_Xword sym_no = symbols.get_symbols_num(); if ( sym_no > 0 ) { out << "Symbol table (" << sec->get_name() << ")" << std::endl; if ( reader.get_class() == ELFCLASS32 ) { // Output for 32-bit out << "[ Nr ] Value Size Type Bind " "Sect Name" << std::endl; } else { // Output for 64-bit out << "[ Nr ] Value Size Type " " Bind Sect" << std::endl << " Name" << std::endl; } for ( Elf_Xword i = 0; i < sym_no; ++i ) { std::string name; Elf64_Addr value = 0; Elf_Xword size = 0; unsigned char bind = 0; unsigned char type = 0; Elf_Half section = 0; unsigned char other = 0; symbols.get_symbol( i, name, value, size, bind, type, section, other ); symbol_table( out, i, name, value, size, bind, type, section, reader.get_class() ); } out << std::endl; } } } } //------------------------------------------------------------------------------ static void symbol_table( std::ostream& out, Elf_Xword no, std::string& name, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, Elf_Half section, unsigned int elf_class ) { std::ios_base::fmtflags original_flags = out.flags(); if ( elf_class == ELFCLASS32 ) { // Output for 32-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_HEX_FORMAT( 8 ) << value << " " << DUMP_HEX_FORMAT( 8 ) << size << " " << DUMP_STR_FORMAT( 7 ) << str_symbol_type( type ) << " " << DUMP_STR_FORMAT( 8 ) << str_symbol_bind( bind ) << " " << DUMP_DEC_FORMAT( 5 ) << section << " " << DUMP_STR_FORMAT( 1 ) << name << " " << std::endl; } else { // Output for 64-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_HEX_FORMAT( 16 ) << value << " " << DUMP_HEX_FORMAT( 16 ) << size << " " << DUMP_STR_FORMAT( 7 ) << str_symbol_type( type ) << " " << DUMP_STR_FORMAT( 8 ) << str_symbol_bind( bind ) << " " << DUMP_DEC_FORMAT( 5 ) << section << " " << std::endl << " " << DUMP_STR_FORMAT( 1 ) << name << " " << std::endl; } out.flags( original_flags ); } //------------------------------------------------------------------------------ static void notes( std::ostream& out, const elfio& reader ) { Elf_Half no = reader.sections.size(); for ( Elf_Half i = 0; i < no; ++i ) { // For all sections section* sec = reader.sections[i]; if ( SHT_NOTE == sec->get_type() ) { // Look at notes note_section_accessor notes( reader, sec ); Elf_Word no_notes = notes.get_notes_num(); if ( no > 0 ) { out << "Note section (" << sec->get_name() << ")" << std::endl << " No Type Name" << std::endl; for ( Elf_Word j = 0; j < no_notes; ++j ) { // For all notes Elf_Word type; std::string name; void* desc; Elf_Word descsz; if ( notes.get_note( j, type, name, desc, descsz ) ) { // 'name' usually contains \0 at the end. Try to fix it name = name.c_str(); note( out, j, type, name ); } } out << std::endl; } } } } //------------------------------------------------------------------------------ static void modinfo( std::ostream& out, const elfio& reader ) { Elf_Half no = reader.sections.size(); for ( Elf_Half i = 0; i < no; ++i ) { // For all sections section* sec = reader.sections[i]; if ( ".modinfo" == sec->get_name() ) { // Look for the section out << "Section .modinfo" << std::endl; const_modinfo_section_accessor modinfo( sec ); for ( Elf_Word i = 0; i < modinfo.get_attribute_num(); i++ ) { std::string field; std::string value; if ( modinfo.get_attribute( i, field, value ) ) { out << " " << std::setw( 20 ) << field << std::setw( 0 ) << " = " << value << std::endl; } } out << std::endl; break; } } } //------------------------------------------------------------------------------ static void note( std::ostream& out, int no, Elf_Word type, const std::string& name ) { out << " [" << DUMP_DEC_FORMAT( 2 ) << no << "] " << DUMP_HEX_FORMAT( 8 ) << type << " " << DUMP_STR_FORMAT( 1 ) << name << std::endl; } //------------------------------------------------------------------------------ static void dynamic_tags( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.sections.size(); for ( Elf_Half i = 0; i < n; ++i ) { // For all sections section* sec = reader.sections[i]; if ( SHT_DYNAMIC == sec->get_type() ) { dynamic_section_accessor dynamic( reader, sec ); Elf_Xword dyn_no = dynamic.get_entries_num(); if ( dyn_no > 0 ) { out << "Dynamic section (" << sec->get_name() << ")" << std::endl; out << "[ Nr ] Tag Name/Value" << std::endl; for ( Elf_Xword i = 0; i < dyn_no; ++i ) { Elf_Xword tag = 0; Elf_Xword value = 0; std::string str; dynamic.get_entry( i, tag, value, str ); dynamic_tag( out, i, tag, value, str, reader.get_class() ); if ( DT_NULL == tag ) { break; } } out << std::endl; } } } } //------------------------------------------------------------------------------ static void dynamic_tag( std::ostream& out, Elf_Xword no, Elf_Xword tag, Elf_Xword value, std::string str, unsigned int /*elf_class*/ ) { out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 16 ) << str_dynamic_tag( tag ) << " "; if ( str.empty() ) { out << DUMP_HEX_FORMAT( 16 ) << value << " "; } else { out << DUMP_STR_FORMAT( 32 ) << str << " "; } out << std::endl; } //------------------------------------------------------------------------------ static void section_data( std::ostream& out, const section* sec ) { std::ios_base::fmtflags original_flags = out.flags(); out << sec->get_name() << std::endl; const char* pdata = sec->get_data(); if ( pdata ) { ELFIO::Elf_Xword i; for ( i = 0; i < std::min( sec->get_size(), MAX_DATA_ENTRIES ); ++i ) { if ( i % 16 == 0 ) { out << "[" << DUMP_HEX_FORMAT( 8 ) << i << "]"; } out << " " << DUMP_HEX_FORMAT( 2 ) << ( pdata[i] & 0x000000FF ); if ( i % 16 == 15 ) { out << std::endl; } } if ( i % 16 != 0 ) { out << std::endl; } out.flags( original_flags ); } return; } //------------------------------------------------------------------------------ static void section_datas( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.sections.size(); if ( n == 0 ) { return; } out << "Section Data:" << std::endl; for ( Elf_Half i = 1; i < n; ++i ) { // For all sections section* sec = reader.sections[i]; if ( sec->get_type() == SHT_NOBITS ) { continue; } section_data( out, sec ); } out << std::endl; } //------------------------------------------------------------------------------ static void segment_data( std::ostream& out, Elf_Half no, const segment* seg ) { std::ios_base::fmtflags original_flags = out.flags(); out << "Segment # " << no << std::endl; const char* pdata = seg->get_data(); if ( pdata ) { ELFIO::Elf_Xword i; for ( i = 0; i < std::min( seg->get_file_size(), MAX_DATA_ENTRIES ); ++i ) { if ( i % 16 == 0 ) { out << "[" << DUMP_HEX_FORMAT( 8 ) << i << "]"; } out << " " << DUMP_HEX_FORMAT( 2 ) << ( pdata[i] & 0x000000FF ); if ( i % 16 == 15 ) { out << std::endl; } } if ( i % 16 != 0 ) { out << std::endl; } out.flags( original_flags ); } return; } //------------------------------------------------------------------------------ static void segment_datas( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.segments.size(); if ( n == 0 ) { return; } out << "Segment Data:" << std::endl; for ( Elf_Half i = 0; i < n; ++i ) { // For all sections segment* seg = reader.segments[i]; segment_data( out, i, seg ); } out << std::endl; } private: //------------------------------------------------------------------------------ template std::string static find_value_in_table( const T& table, const K& key ) { std::string res = "?"; for ( unsigned int i = 0; i < sizeof( table ) / sizeof( table[0] ); ++i ) { if ( table[i].key == key ) { res = table[i].str; break; } } return res; } //------------------------------------------------------------------------------ template static std::string format_assoc( const T& table, const K& key ) { std::string str = find_value_in_table( table, key ); if ( str == "?" ) { std::ostringstream oss; oss << str << " (0x" << std::hex << key << ")"; str = oss.str(); } return str; } //------------------------------------------------------------------------------ template static std::string format_assoc( const T& table, const char key ) { return format_assoc( table, (const int)key ); } //------------------------------------------------------------------------------ static std::string section_flags( Elf_Xword flags ) { std::string ret = ""; if ( flags & SHF_WRITE ) { ret += "W"; } if ( flags & SHF_ALLOC ) { ret += "A"; } if ( flags & SHF_EXECINSTR ) { ret += "X"; } return ret; } //------------------------------------------------------------------------------ #define STR_FUNC_TABLE( name ) \ template static std::string str_##name( const T key ) \ { \ return format_assoc( name##_table, key ); \ } STR_FUNC_TABLE( class ) STR_FUNC_TABLE( endian ) STR_FUNC_TABLE( version ) STR_FUNC_TABLE( type ) STR_FUNC_TABLE( machine ) STR_FUNC_TABLE( section_type ) STR_FUNC_TABLE( segment_type ) STR_FUNC_TABLE( segment_flag ) STR_FUNC_TABLE( symbol_bind ) STR_FUNC_TABLE( symbol_type ) STR_FUNC_TABLE( dynamic_tag ) #undef STR_FUNC_TABLE #undef DUMP_DEC_FORMAT #undef DUMP_HEX_FORMAT #undef DUMP_STR_FORMAT }; // class dump }; // namespace ELFIO #endif // ELFIO_DUMP_HPP /*** End of inlined file: elfio_dump.hpp ***/ kylin-nm/tests/kt-test-utils/cpp-stub/stub.h0000664000175000017500000002340715167651420020031 0ustar fengfeng#ifndef __STUB_H__ #define __STUB_H__ #ifdef _WIN32 //windows #include #include #else //linux #include #include #include #endif //c #include #include //c++ #include #define ADDR(CLASS_NAME,MEMBER_NAME) (&CLASS_NAME::MEMBER_NAME) /********************************************************** replace function **********************************************************/ #ifdef _WIN32 #define CACHEFLUSH(addr, size) FlushInstructionCache(GetCurrentProcess(), addr, size) #else #define CACHEFLUSH(addr, size) __builtin___clear_cache(addr, addr + size) #endif #if defined(__aarch64__) || defined(_M_ARM64) #define CODESIZE 16U #define CODESIZE_MIN 16U #define CODESIZE_MAX CODESIZE // ldr x9, +8 // br x9 // addr #define REPLACE_FAR(t, fn, fn_stub)\ ((uint32_t*)fn)[0] = 0x58000040 | 9;\ ((uint32_t*)fn)[1] = 0xd61f0120 | (9 << 5);\ *(long long *)(fn + 8) = (long long )fn_stub;\ CACHEFLUSH((char *)fn, CODESIZE); #define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub) #elif defined(__arm__) || defined(_M_ARM) #define CODESIZE 8U #define CODESIZE_MIN 8U #define CODESIZE_MAX CODESIZE // ldr pc, [pc, #-4] #define REPLACE_FAR(t, fn, fn_stub)\ ((uint32_t*)fn)[0] = 0xe51ff004;\ ((uint32_t*)fn)[1] = (uint32_t)fn_stub;\ CACHEFLUSH((char *)fn, CODESIZE); #define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub) #elif defined(__mips64) #define CACHEFLUSH(addr, size) __builtin___clear_cache(addr, addr + size) #define CODESIZE 80U #define CODESIZE_MIN 80U #define CODESIZE_MAX CODESIZE //mips没有PC指针,所以需要手动入栈出栈 //120000ce0: 67bdffe0 daddiu sp, sp, -32 //入栈 //120000ce4: ffbf0018 sd ra, 24(sp) //120000ce8: ffbe0010 sd s8, 16(sp) //120000cec: ffbc0008 sd gp, 8(sp) //120000cf0: 03a0f025 move s8, sp //120000d2c: 03c0e825 move sp, s8 //出栈 //120000d30: dfbf0018 ld ra, 24(sp) //120000d34: dfbe0010 ld s8, 16(sp) //120000d38: dfbc0008 ld gp, 8(sp) //120000d3c: 67bd0020 daddiu sp, sp, 32 //120000d40: 03e00008 jr ra #define REPLACE_FAR(t, fn, fn_stub)\ ((uint32_t *)fn)[0] = 0x67bdffe0;\ ((uint32_t *)fn)[1] = 0xffbf0018;\ ((uint32_t *)fn)[2] = 0xffbe0010;\ ((uint32_t *)fn)[3] = 0xffbc0008;\ ((uint32_t *)fn)[4] = 0x03a0f025;\ *(uint16_t *)(fn + 20) = (long long)fn_stub >> 32;\ *(fn + 22) = 0x19;\ *(fn + 23) = 0x24;\ ((uint32_t *)fn)[6] = 0x0019cc38;\ *(uint16_t *)(fn + 28) = (long long)fn_stub >> 16;\ *(fn + 30) = 0x39;\ *(fn + 31) = 0x37;\ ((uint32_t *)fn)[8] = 0x0019cc38;\ *(uint16_t *)(fn + 36) = (long long)fn_stub;\ *(fn + 38) = 0x39;\ *(fn + 39) = 0x37;\ ((uint32_t *)fn)[10] = 0x0320f809;\ ((uint32_t *)fn)[11] = 0x00000000;\ ((uint32_t *)fn)[12] = 0x00000000;\ ((uint32_t *)fn)[13] = 0x03c0e825;\ ((uint32_t *)fn)[14] = 0xdfbf0018;\ ((uint32_t *)fn)[15] = 0xdfbe0010;\ ((uint32_t *)fn)[16] = 0xdfbc0008;\ ((uint32_t *)fn)[17] = 0x67bd0020;\ ((uint32_t *)fn)[18] = 0x03e00008;\ ((uint32_t *)fn)[19] = 0x00000000;\ CACHEFLUSH((char *)fn, CODESIZE); #define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub) #elif defined(__thumb__) || defined(_M_THUMB) #error "Thumb is not supported" #else //__i386__ _x86_64__ #define CODESIZE 13U #define CODESIZE_MIN 5U #define CODESIZE_MAX CODESIZE //13 byte(jmp m16:64) //movabs $0x102030405060708,%r11 //jmpq *%r11 static void REPLACE_FAR(void *t, char *fn, char *fn_stub) { *fn = 0x49; *(fn + 1) = 0xbb; *(long long *)(fn + 2) = (long long)fn_stub; *(fn + 10) = 0x41; *(fn + 11) = 0xff; *(fn + 12) = 0xe3; CACHEFLUSH((char *)fn, CODESIZE); } //5 byte(jmp rel32) #define REPLACE_NEAR(t, fn, fn_stub)\ *fn = 0xE9;\ *(int *)(fn + 1) = (int)(fn_stub - fn - CODESIZE_MIN);\ CACHEFLUSH((char *)fn, CODESIZE); #endif struct func_stub { char *fn; unsigned char code_buf[CODESIZE]; bool far_jmp; }; class Stub { public: Stub() { #ifdef _WIN32 SYSTEM_INFO sys_info; GetSystemInfo(&sys_info); m_pagesize = sys_info.dwPageSize; #else m_pagesize = sysconf(_SC_PAGE_SIZE); #endif if (m_pagesize < 0) { m_pagesize = 4096; } } ~Stub() { clear(); } virtual void clear() { std::map::iterator iter; struct func_stub *pstub; for(iter=m_result.begin(); iter != m_result.end(); iter++) { pstub = iter->second; #ifdef _WIN32 DWORD lpflOldProtect; if(0 != VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READWRITE, &lpflOldProtect)) #else if (0 == mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_WRITE | PROT_EXEC)) #endif { if(pstub->far_jmp) { std::memcpy(pstub->fn, pstub->code_buf, CODESIZE_MAX); } else { std::memcpy(pstub->fn, pstub->code_buf, CODESIZE_MIN); } #ifdef _WIN32 VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READ, &lpflOldProtect); #else CACHEFLUSH(pstub->fn,CODESIZE); mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_EXEC); #endif } iter->second = NULL; delete pstub; } m_result.clear(); return; } template bool set(T addr, S addr_stub) { char * fn; char * fn_stub; fn = addrof(addr); fn_stub = addrof(addr_stub); struct func_stub *pstub; std::map::iterator iter = m_result.find(fn); if (iter == m_result.end()) { pstub = new func_stub; //start pstub->fn = fn; if(distanceof(fn, fn_stub)) { pstub->far_jmp = true; std::memcpy(pstub->code_buf, fn, CODESIZE_MAX); } else { pstub->far_jmp = false; std::memcpy(pstub->code_buf, fn, CODESIZE_MIN); } } else { pstub = iter->second; pstub->far_jmp = distanceof(fn, fn_stub); } #ifdef _WIN32 DWORD lpflOldProtect; if(0 == VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READWRITE, &lpflOldProtect)) #else if (-1 == mprotect(pageof(pstub->fn), static_cast(m_pagesize * 2), PROT_READ | PROT_WRITE | PROT_EXEC)) #endif { throw("stub set memory protect to w+r+x faild"); return false; } if(pstub->far_jmp) { REPLACE_FAR(this, fn, fn_stub); } else { REPLACE_NEAR(this, fn, fn_stub); } #ifdef _WIN32 if(0 == VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READ, &lpflOldProtect)) #else if (-1 == mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_EXEC)) #endif { throw("stub set memory protect to r+x failed"); return false; } m_result.insert(std::pair(fn,pstub)); return true; } template bool reset(T addr) { char * fn; fn = addrof(addr); std::map::iterator iter = m_result.find(fn); if (iter == m_result.end()) { return true; } struct func_stub *pstub; pstub = iter->second; #ifdef _WIN32 DWORD lpflOldProtect; if(0 == VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READWRITE, &lpflOldProtect)) #else if (-1 == mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_WRITE | PROT_EXEC)) #endif { throw("stub reset memory protect to w+r+x faild"); return false; } if(pstub->far_jmp) { std::memcpy(pstub->fn, pstub->code_buf, CODESIZE_MAX); } else { std::memcpy(pstub->fn, pstub->code_buf, CODESIZE_MIN); } #ifdef _WIN32 if(0 == VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READ, &lpflOldProtect)) #else CACHEFLUSH(pstub->fn,CODESIZE); if (-1 == mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_EXEC)) #endif { throw("stub reset memory protect to r+x failed"); return false; } m_result.erase(iter); delete pstub; return true; } protected: char *pageof(char* addr) { #ifdef _WIN32 return (char *)((unsigned long long)addr & ~(m_pagesize - 1)); #else return (char *)((unsigned long)addr & ~(m_pagesize - 1)); #endif } template char* addrof(T addr) { union { T _s; char* _d; }ut; ut._s = addr; return ut._d; } bool distanceof(char* addr, char* addr_stub) { std::ptrdiff_t diff = addr_stub >= addr ? addr_stub - addr : addr - addr_stub; if((sizeof(addr) > 4) && (((diff >> 31) - 1) > 0)) { return true; } return false; } protected: #ifdef _WIN32 //LLP64 long long m_pagesize; #else //LP64 long m_pagesize; #endif std::map m_result; }; #endif kylin-nm/tests/kt-test-utils/cpp-stub-ext/0000775000175000017500000000000015167651420017473 5ustar fengfengkylin-nm/tests/kt-test-utils/cpp-stub-ext/stubext.h0000664000175000017500000000734115167651420021347 0ustar fengfeng #ifndef STUBEXT_H #define STUBEXT_H /* * Author: Zhang Yu * Maintainer: Zhang Yu * * MIT License * * Copyright (c) 2020 Zhang Yu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ //需修改Stub的私用成员函数和成员变量为保护类型 #include "stub.h" #include "stub-shadow.h" #ifdef DEBUG_STUB_INVOKE // use to make sure the stub function is invoked. # define __DBG_STUB_INVOKE__ printf("stub at %s:%d is invoked.\n", __FILE__, __LINE__); #else # define __DBG_STUB_INVOKE__ #endif #define VADDR(CLASS_NAME, MEMBER_NAME) (typename stub_ext::VFLocator::Func)(&CLASS_NAME::MEMBER_NAME) namespace stub_ext { class StubExt : public Stub { public: StubExt() : Stub() { } template bool set_lamda(T addr, Lamda lamda) { char *fn = addrof(addr); if (m_result.find(fn) != m_result.end()) reset(addr); Wrapper *wrapper = nullptr; auto addr_stub = depictShadow(&wrapper, addr, lamda); if (set(addr, addr_stub)) { m_wrappers.insert(std::make_pair(fn, wrapper)); return true; } else { freeWrapper(wrapper); } return false; } template void reset(T addr) { Stub::reset(addr); char *fn = addrof(addr); auto iter = m_wrappers.find(fn); if (iter != m_wrappers.end()) { freeWrapper(iter->second); m_wrappers.erase(iter); } } ~StubExt() { clear(); } void clear() override { Stub::clear(); for (auto iter = m_wrappers.begin(); iter != m_wrappers.end(); ++iter) { freeWrapper(iter->second); } m_wrappers.clear(); } template static void *get_ctor_addr(bool start = true) { // the start vairable must be true, or the compiler will optimize out. if (start) goto Start; Call_Constructor: // This line of code will not be executed. // The purpose of the code is to allow the compiler to generate the assembly code that calls the constructor. T(); Start: // The address of the line of code T() obtained by assembly char *p = (char *)&&Call_Constructor; // https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html // CALL rel32 void *ret = 0; char pos; char call = 0xe8; do { pos = *p; if (pos == call) { ret = p + 5 + (*(int *)(p + 1)); } } while (!ret && (++p)); return ret; } protected: std::map m_wrappers; }; } #endif // STUBEXT_H kylin-nm/tests/kt-test-utils/cpp-stub-ext/stub-shadow.cpp0000664000175000017500000000314715167651420022444 0ustar fengfeng/* * Author: Zhang Yu * Maintainer: Zhang Yu * * MIT License * * Copyright (c) 2020 Zhang Yu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "stub-shadow.h" namespace stub_ext { WrapperMap stub_wrappers; Wrapper::Wrapper() { } Wrapper::~Wrapper() { } void freeWrapper(Wrapper *wrapper) { if (!wrapper) return; for (auto iter = stub_wrappers.begin(); iter != stub_wrappers.end();) { if (iter->second == wrapper) iter = stub_wrappers.erase(iter); else ++iter; } delete wrapper; } } kylin-nm/tests/kt-test-utils/cpp-stub-ext/stub-shadow.h0000664000175000017500000001143415167651420022107 0ustar fengfeng #ifndef STUBSHADOW_H #define STUBSHADOW_H /* * Author: Zhang Yu * Maintainer: Zhang Yu * * MIT License * * Copyright (c) 2020 Zhang Yu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include namespace stub_ext { #define LAMDA_FUNCTION_TYPE decltype(&Lamda::operator()) class Wrapper { public: Wrapper(); virtual ~Wrapper(); }; typedef std::unordered_map WrapperMap; extern WrapperMap stub_wrappers; template class LamdaWrapper : public Wrapper { public: LamdaWrapper(Lamda func): Wrapper(),_func(func){} ~LamdaWrapper(){} Lamda _func; }; template struct VFLocator { }; template struct VFLocator { typedef Ret (*Func)(Obj*, Args...); }; template struct VFLocator { typedef Ret (*Func)(Obj*, Args...); }; template struct LamdaCaller { }; template struct LamdaCaller { template static Ret call(LamdaWrapper *wrapper, OrgArgs&&... args) { return wrapper->_func(std::forward(args)...); } }; template struct LamdaCaller { template static Ret call(LamdaWrapper *wrapper, OrgArgs&&... args) { return wrapper->_func(); } }; template struct FuncShadow { }; template struct FuncShadow { typedef Ret (*Shadow)(Args...); typedef Ret RetType; static Ret call(Args ...args) { Shadow shadow = &call; long id = (long)shadow; auto iter = stub_wrappers.find(id); assert(stub_wrappers.find(id) != stub_wrappers.end()); LamdaWrapper *wrapper = dynamic_cast *>(iter->second); return LamdaCaller::call(wrapper, args...); } }; template struct FuncShadow { typedef Ret (*Shadow)(Obj *,Args...); typedef Ret RetType; static Ret call(Obj *obj, Args ...args) { Shadow shadow = &call; long id = (long)shadow; auto iter = stub_wrappers.find(id); assert(stub_wrappers.find(id) != stub_wrappers.end()); LamdaWrapper *wrapper = dynamic_cast *>(iter->second); return LamdaCaller::call(wrapper, obj, args...); } }; template struct FuncShadow { typedef Ret (*Shadow)(Obj *,Args...); typedef Ret RetType; static Ret call(Obj *obj, Args ...args) { Shadow shadow = &call; long id = (long)shadow; auto iter = stub_wrappers.find(id); assert(stub_wrappers.find(id) != stub_wrappers.end()); LamdaWrapper *wrapper = dynamic_cast *>(iter->second); return LamdaCaller::call(wrapper, obj, args...); } }; template typename FuncShadow::Shadow depictShadow(Wrapper **wrapper, Func func, Lamda lamda) { *wrapper = new LamdaWrapper(lamda); typename FuncShadow::Shadow shadow = &FuncShadow::call; long id = (long)shadow; assert(stub_wrappers.find(id) == stub_wrappers.end()); stub_wrappers.insert(std::make_pair(id,*wrapper)); return shadow; } void freeWrapper(Wrapper *wrapper); } #endif // STUBSHADOW_H kylin-nm/tests/tests.pro0000664000175000017500000000066115167651420014276 0ustar fengfengTEMPLATE = subdirs SUBDIRS = unit_test_alltest \ # 打桩工具 # Define paths TEST_UTILS_PATH = $$PWD/kt-test-utils # Header files (if needed) HEADERS += $$files($$TEST_UTILS_PATH/cpp-stub/*.h $$TEST_UTILS_PATH/cpp-stub/*.hpp) \ $$files($$TEST_UTILS_PATH/cpp-stub-ext/*.h) # Gather source files SOURCES += $$files($$TEST_UTILS_PATH/cpp-stub/*.cpp) \ $$files($$TEST_UTILS_PATH/cpp-stub-ext/*.cpp) kylin-nm/tests/.scannerwork/0000775000175000017500000000000015167651420015021 5ustar fengfengkylin-nm/tests/.scannerwork/.sonar_lock0000664000175000017500000000000015167651420017142 0ustar fengfengkylin-nm/tests/.scannerwork/report-task.txt0000664000175000017500000000053715167651420020042 0ustar fengfengprojectKey=desktop_kylin-nm serverUrl=https://codescan.kylinos.cn serverVersion=10.8.1.101195 branch=yhkylin/v11-2503 dashboardUrl=https://codescan.kylinos.cn/dashboard?id=desktop_kylin-nm&branch=yhkylin%2Fv11-2503 ceTaskId=ab900b3b-96be-47b8-bdb4-5a6f7b62421a ceTaskUrl=https://codescan.kylinos.cn/api/ce/task?id=ab900b3b-96be-47b8-bdb4-5a6f7b62421a kylin-nm/tests/readme.txt0000664000175000017500000000072415167651420014410 0ustar fengfengsonar-scanner -Dsonar.projectKey=desktop_kylin-nm -Dsonar.sources=. -Dsonar.host.url=https://codescan.kylinos.cn -Dsonar.cfamily.gcov.reportsPath=/home/kylin/桌面/lx/kylin-nm/kylin-nm/tests -Dsonar.token=sqp_a0c0f7be62b18839d20f96321e7c6bdb888cb30d -Dsonar.branch.name=yhkylin/v11-2503 -Dsonar.coverage.exclusions="/home/kylin/桌面/lx/kylin-nm/kylin-nm/tests/*.h" -Dsonar.coverage.exclusions="/home/kylin/桌面/lx/kylin-nm/kylin-nm/tests/unit_test_alltest/moc_*" kylin-nm/tests/auto_test.sh0000775000175000017500000000303515167651420014756 0ustar fengfeng#!/bin/bash # 设置退出脚本当命令失败时 (非零退出状态) #set -e # 函数:运行单元测试 run_unit_tests() { local pattern="unit_test_*" # 遍历所有匹配模式的目录 for dir in $pattern; do if [ -d "$dir" ] && [ -x "$dir/$(basename "$dir")" ]; then echo "Running tests in $dir..." # 执行单元测试 (cd "$dir" && "./$(basename "$dir")") # 收集代码覆盖率数据 echo "Collecting coverage data..." (cd "$dir" && (find ./ -name '*.o' | xargs gcov --preserve-paths)) else echo "Skipping non-existent or non-executable directory: $dir, $dir/$(basename "$dir")" fi done } # 上传 result.zip 到平台 URL=$1 upload_result() { echo "current pwd : $(pwd)" # 收集覆盖率信息 lcov -d . -c -o r.info # 删除不需要的文件或路径 lcov -r r.info "$(pwd)/unit_test_*" "$(pwd)/../registeredSession/universalinterface.cpp" "/usr/include/*" "/opt/*" -o coverage.info # 生成html覆盖率报告 genhtml "$(pwd)/coverage.info" -o result # 打包 zip -r result.zip result # 上传平台 curl --insecure -X POST -F "file=@/$(pwd)/result.zip" -F "package=ukui-control-center" -F "username=hesisheng" $URL echo "all parameter : $@" } # 编译项目 echo "Compiling the project..." qmake . && make # 运行各个单元测试 echo "Running unit tests..." run_unit_tests # 上传到平台 #upload_result echo "All tests have been run successfully, and coverage data has been collected."