Repository: Yos-X/ClashYou Branch: main Commit: 367b3292d3e1 Files: 484 Total size: 951.7 KB Directory structure: gitextract_6w_2unif/ ├── .gitattributes ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── 01-bug-report-en.yml │ │ ├── 02-feature-request-en.yml │ │ ├── 03-bug-report-zh-cn.yml │ │ ├── 04-feature-request-zh-cn.yml │ │ └── config.yml │ └── workflows/ │ └── build.yaml ├── .gitignore ├── .gitmodules ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── PRIVACY_POLICY.md ├── README.md ├── README_en.md ├── app/ │ ├── build.gradle.kts │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── yos/ │ │ └── clash/ │ │ └── material/ │ │ ├── AccessControlActivity.kt │ │ ├── ApkBrokenActivity.kt │ │ ├── AppCrashedActivity.kt │ │ ├── AppSettingsActivity.kt │ │ ├── BaseActivity.kt │ │ ├── ExternalImportActivity.kt │ │ ├── FilesActivity.kt │ │ ├── HelpActivity.kt │ │ ├── LogcatActivity.kt │ │ ├── LogcatService.kt │ │ ├── LogsActivity.kt │ │ ├── MainActivity.kt │ │ ├── MainApplication.kt │ │ ├── NetworkSettingsActivity.kt │ │ ├── NewProfileActivity.kt │ │ ├── OverrideSettingsActivity.kt │ │ ├── ProfilesActivity.kt │ │ ├── PropertiesActivity.kt │ │ ├── ProvidersActivity.kt │ │ ├── ProxyActivity.kt │ │ ├── RestartReceiver.kt │ │ ├── SettingsActivity.kt │ │ ├── TileService.kt │ │ ├── log/ │ │ │ ├── LogcatCache.kt │ │ │ ├── LogcatFilter.kt │ │ │ ├── LogcatReader.kt │ │ │ ├── LogcatWriter.kt │ │ │ └── SystemLogcat.kt │ │ ├── remote/ │ │ │ ├── Broadcasts.kt │ │ │ ├── FilesClient.kt │ │ │ ├── Remote.kt │ │ │ ├── Resource.kt │ │ │ ├── Service.kt │ │ │ └── StatusClient.kt │ │ ├── store/ │ │ │ ├── AppStore.kt │ │ │ └── TipsStore.kt │ │ └── util/ │ │ ├── Activity.kt │ │ ├── Application.kt │ │ ├── Clash.kt │ │ ├── Content.kt │ │ ├── Files.kt │ │ ├── Remote.kt │ │ ├── Service.kt │ │ └── Uri.kt │ └── res/ │ ├── drawable/ │ │ └── ic_launcher_foreground.xml │ ├── mipmap-anydpi-v26/ │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ ├── values/ │ │ ├── colors.xml │ │ ├── ids.xml │ │ └── themes.xml │ ├── values-night/ │ │ └── themes.xml │ └── xml/ │ ├── full_backup_content.xml │ └── network_security_config.xml ├── build.gradle.kts ├── common/ │ ├── build.gradle.kts │ ├── consumer-rules.pro │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── yos/ │ │ └── clash/ │ │ └── material/ │ │ └── common/ │ │ ├── Global.kt │ │ ├── compat/ │ │ │ ├── App.kt │ │ │ ├── Context.kt │ │ │ ├── Html.kt │ │ │ ├── Intents.kt │ │ │ ├── Package.kt │ │ │ ├── Resource.kt │ │ │ ├── Services.kt │ │ │ ├── UI.kt │ │ │ └── View.kt │ │ ├── constants/ │ │ │ ├── Authorities.kt │ │ │ ├── Components.kt │ │ │ ├── Intents.kt │ │ │ ├── Metadata.kt │ │ │ └── Permissions.kt │ │ ├── id/ │ │ │ └── UndefinedIds.kt │ │ ├── log/ │ │ │ └── Log.kt │ │ ├── store/ │ │ │ ├── Providers.kt │ │ │ ├── Store.kt │ │ │ └── StoreProvider.kt │ │ └── util/ │ │ ├── Components.kt │ │ ├── Global.kt │ │ ├── Intent.kt │ │ ├── Parcelable.kt │ │ ├── Patterns.kt │ │ └── Ticker.kt │ └── res/ │ ├── values/ │ │ └── strings.xml │ ├── values-zh/ │ │ └── strings.xml │ └── values-zh-rTW/ │ └── strings.xml ├── core/ │ ├── build.gradle.kts │ ├── consumer-rules.pro │ ├── proguard-rules.pro │ └── src/ │ ├── foss/ │ │ └── golang/ │ │ ├── go.mod │ │ ├── go.sum │ │ └── main.go │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── cpp/ │ │ │ ├── CMakeLists.txt │ │ │ ├── bridge_helper.c │ │ │ ├── bridge_helper.h │ │ │ ├── jni_helper.c │ │ │ ├── jni_helper.h │ │ │ └── main.c │ │ ├── golang/ │ │ │ ├── go.mod │ │ │ ├── go.sum │ │ │ └── native/ │ │ │ ├── all/ │ │ │ │ └── imports.go │ │ │ ├── app/ │ │ │ │ ├── app.go │ │ │ │ ├── content.go │ │ │ │ ├── dns.go │ │ │ │ ├── tun.go │ │ │ │ └── ui.go │ │ │ ├── app.go │ │ │ ├── bridge.c │ │ │ ├── bridge.h │ │ │ ├── common/ │ │ │ │ └── path.go │ │ │ ├── config/ │ │ │ │ ├── defaults.go │ │ │ │ ├── fetch.go │ │ │ │ ├── load.go │ │ │ │ ├── override.go │ │ │ │ ├── process.go │ │ │ │ ├── process_open.go │ │ │ │ ├── process_premium.go │ │ │ │ ├── provider_open.go │ │ │ │ └── provider_premium.go │ │ │ ├── config.go │ │ │ ├── debug.go │ │ │ ├── delegate/ │ │ │ │ └── init.go │ │ │ ├── log_open.go │ │ │ ├── log_premium.go │ │ │ ├── main.go │ │ │ ├── platform/ │ │ │ │ ├── limit.go │ │ │ │ └── procfs.go │ │ │ ├── proxy/ │ │ │ │ └── http.go │ │ │ ├── proxy.go │ │ │ ├── trace.c │ │ │ ├── trace.h │ │ │ ├── tun/ │ │ │ │ ├── dns.go │ │ │ │ ├── metadata_open.go │ │ │ │ ├── metadata_premium.go │ │ │ │ ├── tun.go │ │ │ │ └── udp.go │ │ │ ├── tun.go │ │ │ ├── tunnel/ │ │ │ │ ├── conn.go │ │ │ │ ├── connectivity.go │ │ │ │ ├── geoip.go │ │ │ │ ├── init.go │ │ │ │ ├── loopback_open.go │ │ │ │ ├── loopback_premium.go │ │ │ │ ├── providers_open.go │ │ │ │ ├── providers_premium.go │ │ │ │ ├── proxies.go │ │ │ │ ├── state.go │ │ │ │ ├── statistic.go │ │ │ │ └── suspend.go │ │ │ ├── tunnel.go │ │ │ └── utils.go │ │ └── java/ │ │ └── com/ │ │ └── github/ │ │ └── kr328/ │ │ └── clash/ │ │ └── core/ │ │ ├── Clash.kt │ │ ├── bridge/ │ │ │ ├── Bridge.kt │ │ │ ├── ClashException.kt │ │ │ ├── Content.kt │ │ │ ├── FetchCallback.kt │ │ │ ├── LogcatInterface.kt │ │ │ └── TunInterface.kt │ │ ├── model/ │ │ │ ├── ConfigurationOverride.kt │ │ │ ├── FetchStatus.kt │ │ │ ├── LogMessage.kt │ │ │ ├── Provider.kt │ │ │ ├── ProviderList.kt │ │ │ ├── Proxy.kt │ │ │ ├── ProxyGroup.kt │ │ │ ├── ProxySort.kt │ │ │ ├── Traffic.kt │ │ │ ├── TunnelState.kt │ │ │ └── UiConfiguration.kt │ │ └── util/ │ │ ├── Net.kt │ │ ├── Parcelizer.kt │ │ ├── Serializers.kt │ │ └── Traffic.kt │ └── premium/ │ └── golang/ │ ├── go.mod │ ├── go.sum │ └── main.go ├── design/ │ ├── build.gradle.kts │ ├── consumer-rules.pro │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── yos/ │ │ └── clash/ │ │ └── material/ │ │ └── design/ │ │ ├── AccessControlDesign.kt │ │ ├── ApkBrokenDesign.kt │ │ ├── AppCrashedDesign.kt │ │ ├── AppSettingsDesign.kt │ │ ├── Design.kt │ │ ├── FilesDesign.kt │ │ ├── HelpDesign.kt │ │ ├── LogcatDesign.kt │ │ ├── LogsDesign.kt │ │ ├── MainDesign.kt │ │ ├── NetworkSettingsDesign.kt │ │ ├── NewProfileDesign.kt │ │ ├── OverrideSettingsDesign.kt │ │ ├── ProfilesDesign.kt │ │ ├── PropertiesDesign.kt │ │ ├── ProvidersDesign.kt │ │ ├── ProxyDesign.kt │ │ ├── SettingsDesign.kt │ │ ├── YosConfigAchieve.kt │ │ ├── adapter/ │ │ │ ├── AppAdapter.kt │ │ │ ├── EditableTextListAdapter.kt │ │ │ ├── EditableTextMapAdapter.kt │ │ │ ├── FileAdapter.kt │ │ │ ├── LogFileAdapter.kt │ │ │ ├── LogMessageAdapter.kt │ │ │ ├── PopupListAdapter.kt │ │ │ ├── ProfileAdapter.kt │ │ │ ├── ProfileProviderAdapter.kt │ │ │ ├── ProviderAdapter.kt │ │ │ ├── ProxyAdapter.kt │ │ │ ├── ProxyPageAdapter.kt │ │ │ └── SideloadProviderAdapter.kt │ │ ├── component/ │ │ │ ├── AccessControlMenu.kt │ │ │ ├── ProxyMenu.kt │ │ │ ├── ProxyPageFactory.kt │ │ │ ├── ProxyView.kt │ │ │ ├── ProxyViewConfig.kt │ │ │ └── ProxyViewState.kt │ │ ├── dialog/ │ │ │ ├── Dialogs.kt │ │ │ ├── Input.kt │ │ │ └── Progress.kt │ │ ├── model/ │ │ │ ├── AppInfo.kt │ │ │ ├── AppInfoSort.kt │ │ │ ├── Behavior.kt │ │ │ ├── DarkMode.kt │ │ │ ├── File.kt │ │ │ ├── LogFile.kt │ │ │ ├── ProfileProvider.kt │ │ │ ├── ProviderState.kt │ │ │ ├── ProxyPageState.kt │ │ │ └── ProxyState.kt │ │ ├── preference/ │ │ │ ├── Category.kt │ │ │ ├── Clickable.kt │ │ │ ├── EditableText.kt │ │ │ ├── EditableTextList.kt │ │ │ ├── EditableTextMap.kt │ │ │ ├── Overlay.kt │ │ │ ├── Preference.kt │ │ │ ├── Screen.kt │ │ │ ├── SelectableList.kt │ │ │ ├── Switch.kt │ │ │ ├── Tips.kt │ │ │ └── Value.kt │ │ ├── store/ │ │ │ └── UiStore.kt │ │ ├── ui/ │ │ │ ├── DayNight.kt │ │ │ ├── Insets.kt │ │ │ ├── ObservableCurrentTime.kt │ │ │ ├── Surface.kt │ │ │ └── ToastDuration.kt │ │ ├── util/ │ │ │ ├── ActivityBar.kt │ │ │ ├── App.kt │ │ │ ├── Binding.kt │ │ │ ├── Context.kt │ │ │ ├── Diff.kt │ │ │ ├── Elevation.kt │ │ │ ├── I18n.kt │ │ │ ├── Inserts.kt │ │ │ ├── Interval.kt │ │ │ ├── Landscape.kt │ │ │ ├── ListView.kt │ │ │ ├── RecyclerView.kt │ │ │ ├── ScrollView.kt │ │ │ ├── Theme.kt │ │ │ ├── Toast.kt │ │ │ ├── Validator.kt │ │ │ └── View.kt │ │ └── view/ │ │ ├── ActionLabel.kt │ │ ├── ActionTextField.kt │ │ ├── ActivityBarLayout.kt │ │ ├── AppRecyclerView.kt │ │ ├── LargeActionCard.kt │ │ ├── LargeActionLabel.kt │ │ ├── ObservableScrollView.kt │ │ └── VerticalScrollableHost.kt │ └── res/ │ ├── drawable/ │ │ ├── bg_bottom_sheet.xml │ │ ├── ic_baseline_adb.xml │ │ ├── ic_baseline_add.xml │ │ ├── ic_baseline_apps.xml │ │ ├── ic_baseline_arrow_back.xml │ │ ├── ic_baseline_assignment.xml │ │ ├── ic_baseline_attach_file.xml │ │ ├── ic_baseline_brightness_4.xml │ │ ├── ic_baseline_clear_all.xml │ │ ├── ic_baseline_close.xml │ │ ├── ic_baseline_cloud_download.xml │ │ ├── ic_baseline_content_copy.xml │ │ ├── ic_baseline_delete.xml │ │ ├── ic_baseline_dns.xml │ │ ├── ic_baseline_domain.xml │ │ ├── ic_baseline_edit.xml │ │ ├── ic_baseline_extension.xml │ │ ├── ic_baseline_flash_on.xml │ │ ├── ic_baseline_get_app.xml │ │ ├── ic_baseline_help_center.xml │ │ ├── ic_baseline_info.xml │ │ ├── ic_baseline_more_vert.xml │ │ ├── ic_baseline_publish.xml │ │ ├── ic_baseline_replay.xml │ │ ├── ic_baseline_restore.xml │ │ ├── ic_baseline_save.xml │ │ ├── ic_baseline_search.xml │ │ ├── ic_baseline_settings.xml │ │ ├── ic_baseline_stop.xml │ │ ├── ic_baseline_swap_vert.xml │ │ ├── ic_baseline_swap_vertical_circle.xml │ │ ├── ic_baseline_sync.xml │ │ ├── ic_baseline_update.xml │ │ ├── ic_baseline_view_list.xml │ │ ├── ic_baseline_vpn_lock.xml │ │ ├── ic_baseline_work.xml │ │ ├── ic_clash.xml │ │ ├── ic_outline_article.xml │ │ ├── ic_outline_check_circle.xml │ │ ├── ic_outline_delete.xml │ │ ├── ic_outline_folder.xml │ │ ├── ic_outline_inbox.xml │ │ ├── ic_outline_info.xml │ │ ├── ic_outline_label.xml │ │ ├── ic_outline_not_interested.xml │ │ ├── ic_outline_update.xml │ │ ├── yos_shape.xml │ │ └── yos_shape_color.xml │ ├── layout/ │ │ ├── adapter_app.xml │ │ ├── adapter_editable_text_list.xml │ │ ├── adapter_editable_text_map.xml │ │ ├── adapter_file.xml │ │ ├── adapter_log_message.xml │ │ ├── adapter_profile.xml │ │ ├── adapter_profile_provider.xml │ │ ├── adapter_provider.xml │ │ ├── adapter_sideload_provider.xml │ │ ├── common_activity_bar.xml │ │ ├── common_recycler_list.xml │ │ ├── component_action_label.xml │ │ ├── component_action_text_field.xml │ │ ├── component_large_action_label.xml │ │ ├── design_about.xml │ │ ├── design_access_control.xml │ │ ├── design_app_crashed.xml │ │ ├── design_files.xml │ │ ├── design_logcat.xml │ │ ├── design_logs.xml │ │ ├── design_main.xml │ │ ├── design_new_profile.xml │ │ ├── design_profiles.xml │ │ ├── design_properties.xml │ │ ├── design_providers.xml │ │ ├── design_proxy.xml │ │ ├── design_settings.xml │ │ ├── design_settings_common.xml │ │ ├── design_settings_overide.xml │ │ ├── dialog_editable_map_text_field.xml │ │ ├── dialog_fetch_status.xml │ │ ├── dialog_files_menu.xml │ │ ├── dialog_preference_list.xml │ │ ├── dialog_profiles_menu.xml │ │ ├── dialog_search.xml │ │ ├── dialog_text_field.xml │ │ ├── preference_category.xml │ │ ├── preference_clickable.xml │ │ ├── preference_switch.xml │ │ └── preference_tips.xml │ ├── menu/ │ │ ├── menu_access_control.xml │ │ └── menu_proxy.xml │ ├── values/ │ │ ├── attrs.xml │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── ids.xml │ │ ├── strings.xml │ │ ├── styles.xml │ │ └── themes.xml │ ├── values-v23/ │ │ └── themes.xml │ ├── values-v27/ │ │ └── themes.xml │ ├── values-v29/ │ │ └── themes.xml │ ├── values-v31/ │ │ └── colors.xml │ ├── values-v34/ │ │ └── colors.xml │ ├── values-zh/ │ │ └── strings.xml │ ├── values-zh-rHK/ │ │ └── strings.xml │ └── values-zh-rTW/ │ └── strings.xml ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── hideapi/ │ ├── build.gradle.kts │ ├── consumer-rules.pro │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ └── java/ │ └── android/ │ └── app/ │ └── ActivityThread.java ├── service/ │ ├── build.gradle.kts │ ├── consumer-rules.pro │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── yos/ │ │ └── clash/ │ │ └── material/ │ │ └── service/ │ │ ├── BaseService.kt │ │ ├── ClashManager.kt │ │ ├── ClashService.kt │ │ ├── FilesProvider.kt │ │ ├── PreferenceProvider.kt │ │ ├── ProfileManager.kt │ │ ├── ProfileProcessor.kt │ │ ├── ProfileReceiver.kt │ │ ├── ProfileWorker.kt │ │ ├── RemoteService.kt │ │ ├── StatusProvider.kt │ │ ├── TunService.kt │ │ ├── clash/ │ │ │ ├── ClashRuntime.kt │ │ │ └── module/ │ │ │ ├── AppListCacheModule.kt │ │ │ ├── CloseModule.kt │ │ │ ├── ConfigurationModule.kt │ │ │ ├── DynamicNotificationModule.kt │ │ │ ├── Module.kt │ │ │ ├── NetworkObserveModule.kt │ │ │ ├── SideloadDatabaseModule.kt │ │ │ ├── StaticNotificationModule.kt │ │ │ ├── SuspendModule.kt │ │ │ ├── TimeZoneModule.kt │ │ │ └── TunModule.kt │ │ ├── data/ │ │ │ ├── Converters.kt │ │ │ ├── Daos.kt │ │ │ ├── Database.kt │ │ │ ├── Imported.kt │ │ │ ├── ImportedDao.kt │ │ │ ├── Pending.kt │ │ │ ├── PendingDao.kt │ │ │ ├── ProviderMoreInfo.kt │ │ │ ├── ProviderMoreInfoDao.kt │ │ │ ├── Selection.kt │ │ │ ├── SelectionDao.kt │ │ │ └── migrations/ │ │ │ ├── LegacyMigration.kt │ │ │ └── Migrations.kt │ │ ├── document/ │ │ │ ├── Document.kt │ │ │ ├── FileDocument.kt │ │ │ ├── Flag.kt │ │ │ ├── Path.kt │ │ │ ├── Paths.kt │ │ │ ├── Picker.kt │ │ │ └── VirtualDocument.kt │ │ ├── model/ │ │ │ ├── AccessControlMode.kt │ │ │ └── Profile.kt │ │ ├── remote/ │ │ │ ├── IClashManager.kt │ │ │ ├── IFetchObserver.kt │ │ │ ├── ILogObserver.kt │ │ │ ├── IProfileManager.kt │ │ │ └── IRemoteService.kt │ │ ├── sideload/ │ │ │ └── ExternalGeoip.kt │ │ ├── store/ │ │ │ └── ServiceStore.kt │ │ └── util/ │ │ ├── Address.kt │ │ ├── Broadcast.kt │ │ ├── Connectivity.kt │ │ ├── Coroutine.kt │ │ ├── Database.kt │ │ ├── Files.kt │ │ ├── Intent.kt │ │ ├── Net.kt │ │ └── Serializers.kt │ └── res/ │ ├── drawable/ │ │ └── ic_logo_service.xml │ ├── values/ │ │ ├── arrays.xml │ │ ├── colors.xml │ │ ├── ids.xml │ │ └── strings.xml │ ├── values-zh/ │ │ └── strings.xml │ ├── values-zh-rHK/ │ │ └── strings.xml │ └── values-zh-rTW/ │ └── strings.xml └── settings.gradle.kts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ * text=auto eol=lf *.bat text eol=crlf *.jar binary ================================================ FILE: .github/ISSUE_TEMPLATE/01-bug-report-en.yml ================================================ name: "[English] Bug Report" description: "Create a report to help us debug bugs" title: "[BUG] " body: - type: markdown attributes: value: | Thanks for taking the time to fill out this bug report! NOTE: Be sure to put a clear and concise title **AFTER** `[BUG]` in the text box above. NOTE: We do not provide any services such as proxies, DO NOT feedback any problems not caused by this application here. - type: textarea id: description attributes: label: "Describe the bug" description: "A clear and concise description of what the bug is." validations: required: true - type: textarea id: reproduce attributes: label: "To Reproduce" description: "Steps to reproduce the behavior:" value: | Step 1: ... Step 2: ... Step 3: ... ... validations: required: true - type: textarea id: device-info attributes: label: "Device Info" description: | Input your device information. Example: - Device: Pixel 4 - ROM: AOSP - Android Version: 10 value: | - Device: - ROM: - Android Version: validations: required: true - type: textarea id: app-info attributes: label: "Application Info" description: | Input application you are using information. Example: ``` - Version: 2.5.4-premium - APK filename: cfa-2.5.4-premium-arm64-v8a-release.apk - Distribution Channel: Google Play ``` value: | - Version: - APK filename: - Distribution Channel: validations: required: true - type: textarea id: configure attributes: render: yml label: "Configure File" description: | Please paste or upload the configuration file here. TIPS: If you only have a subscription link, please use your browser to download it. **NOTE: Please remove proxies from the configuration file before uploading it.** **NOTE: Please remove proxies from the configuration file before uploading it.** **NOTE: Please remove proxies from the configuration file before uploading it.** validations: required: true - type: textarea id: logs attributes: render: raw label: "Logs" description: | Please paste or upload the log file here. TIPS: Please use the `Logcat` in application or `adb logcat`. `adb logcat` would be better. validations: required: true - type: textarea id: screenshot attributes: label: "Screenshot" description: "If applicable, add screenshots to help explain your problem." placeholder: "Optional" - type: textarea id: additional attributes: label: "Additional" description: "Add any other context about the problem here." ================================================ FILE: .github/ISSUE_TEMPLATE/02-feature-request-en.yml ================================================ name: "[English] Feature Request" description: "Create a report to help us improve" title: "[Feature Request] " body: - type: markdown attributes: value: | Thanks for taking the time to fill out this feature request! NOTE: Be sure to put a clear and concise title **AFTER** `[Feature Request]` in the text box above. - type: textarea id: "description" attributes: label: "Feature Description" description: | A clear and concise description of the feature. validations: required: true - type: textarea id: "additional" attributes: label: "Additional" description: | Add any other context or screenshots about the feature request here. ================================================ FILE: .github/ISSUE_TEMPLATE/03-bug-report-zh-cn.yml ================================================ name: "[简体中文] 错误报告" description: "创建错误报告以帮助我们修正应用" title: "[BUG] " body: - type: markdown attributes: value: | 感谢您在百忙之中填写此错误报告。 注意: 请务必在上方文本框的 `[BUG]` **之后**填写清晰明了的标题。 注意:这里不提供像是代理服务器之类的服务,请不要反馈非应用自身引起的问题。 - type: textarea id: description attributes: label: "描述此错误" description: "请清晰简洁的描述你遇到的错误。" validations: required: true - type: textarea id: reproduce attributes: label: "如何复现该错误" description: "复现步骤:" value: | 步骤 1: ... 步骤 2: ... 步骤 3: ... ... validations: required: true - type: textarea id: device-info attributes: label: "设备信息" description: | 输入您正在使用的设备信息。 例子: - 机型: Pixel 4 - 系统类型: MIUI/AOSP - Android 版本: 10 value: | - 机型: - 系统类型: - Android 版本: validations: required: true - type: textarea id: app-info attributes: label: "应用信息" description: | 输入您正在使用的应用信息。 例子: ``` - 版本: 2.5.4-premium - 安装包文件名: cfa-2.5.4-premium-arm64-v8a-release.apk - 应用来源: Google Play ``` value: | - 版本: - 安装包文件名: - 应用来源: validations: required: true - type: textarea id: configure attributes: render: yml label: "配置文件" description: | 请在此粘贴和上传配置文件。 提示:如果您仅有一个订阅链接,请使用浏览器打开此链接以下载配置文件。 **注意: 请在上传配置文件前,移除其中的代理服务器信息。** **注意: 请在上传配置文件前,移除其中的代理服务器信息。** **注意: 请在上传配置文件前,移除其中的代理服务器信息。** validations: required: true - type: textarea id: logs attributes: render: raw label: "日志" description: | 请在此粘贴或上传日志。 提示: 请使用应用内的 `Logcat` 或 `adb logcat` 捕获日志. `adb logcat` 能更好地帮助侦测问题. validations: required: true - type: textarea id: screenshot attributes: label: "屏幕截图" description: "如果适用,请在此粘贴或上传屏幕截图。" placeholder: "可选" - type: textarea id: additional attributes: label: "附加信息" description: "其他的可能与改错误相关的信息。" placeholder: "可选" ================================================ FILE: .github/ISSUE_TEMPLATE/04-feature-request-zh-cn.yml ================================================ name: "[简体中文] 功能请求" description: "您希望的能够在应用中增加功能" title: "[Feature Request] " body: - type: markdown attributes: value: | 感谢您在百忙之中填写此功能请求报告。 注意: 请务必在上方文本框的 `[Feature Request]` **之后**填写清晰明了的标题。 - type: textarea id: "description" attributes: label: "功能描述" description: | 简介明了的描述此功能。 validations: required: true - type: textarea id: "additional" attributes: label: "附加信息" description: | 与此功能相关的其他附加信息。 ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false ================================================ FILE: .github/workflows/build.yaml ================================================ name: Android CI on: push: branches: - main paths-ignore: # - '.github/**' - '.idea/**' - '.gitattributes' - '.gitignore' - '.gitmodules' - '**.md' - 'LICENSE' - 'NOTICE' pull_request: paths-ignore: # - '.github/**' - '.idea/**' - '.gitattributes' - '.gitignore' - '.gitmodules' - '**.md' - 'LICENSE' - 'NOTICE' workflow_dispatch: jobs: Build: runs-on: ubuntu-latest steps: - name: Checkout Repository uses: actions/checkout@v3 with: submodules: recursive - name: Setup Java uses: actions/setup-java@v3 with: distribution: 'oracle' java-version: 17 - name: Setup Go uses: actions/setup-go@v3 with: go-version: 'stable' - name: Cache Go Files uses: actions/cache@v3 with: path: | ~/.cache/go-build ~/go/pkg/mod key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} restore-keys: | ${{ runner.os }}-go- - name: Setup Gradle uses: gradle/gradle-build-action@v2 # with: # arguments: --no-daemon assemble - name: Create Sign File run: | echo ${{ secrets.SIGNING_KEY }} | base64 -d > keystore.jks echo ${{ secrets.SIGNING_PROPERTIES }} | base64 -d > signing.properties - name: Build with Gradle run: | ./gradlew --no-daemon assemble - name: Find APKs run: | echo "APK_FILE_RELEASE_ARM32=$(find app/build/outputs/apk/foss/release -name '*armeabi-v7a*')" >> $GITHUB_ENV echo "APK_FILE_RELEASE_ARM64=$(find app/build/outputs/apk/foss/release -name '*arm64-v8a*')" >> $GITHUB_ENV echo "APK_FILE_RELEASE_X86=$(find app/build/outputs/apk/foss/release -name '*x86-*')" >> $GITHUB_ENV echo "APK_FILE_RELEASE_X64=$(find app/build/outputs/apk/foss/release -name '*x86_64*')" >> $GITHUB_ENV echo "APK_FILE_RELEASE_UNIVERSAL=$(find app/build/outputs/apk/foss/release -name '*universal*')" >> $GITHUB_ENV echo "APK_FILE_DEBUG_ARM32=$(find app/build/outputs/apk/foss/debug -name '*armeabi-v7a*')" >> $GITHUB_ENV echo "APK_FILE_DEBUG_ARM64=$(find app/build/outputs/apk/foss/debug -name '*arm64-v8a*')" >> $GITHUB_ENV echo "APK_FILE_DEBUG_X86=$(find app/build/outputs/apk/foss/debug -name '*x86-*')" >> $GITHUB_ENV echo "APK_FILE_DEBUG_X64=$(find app/build/outputs/apk/foss/debug -name '*x86_64*')" >> $GITHUB_ENV echo "APK_FILE_DEBUG_UNIVERSAL=$(find app/build/outputs/apk/foss/debug -name '*universal*')" >> $GITHUB_ENV - name: Show Artifacts SHA256 run: | echo "### Build Success" >> $GITHUB_STEP_SUMMARY echo "|Artifact|SHA256|" >> $GITHUB_STEP_SUMMARY echo "|:--------:|:----------|" >> $GITHUB_STEP_SUMMARY # Release Artifacts release_arm32=($(sha256sum ${{ env.APK_FILE_RELEASE_ARM32 }})) echo "|release_armeabi-v7a|$release_arm32" >> $GITHUB_STEP_SUMMARY release_arm64=($(sha256sum ${{ env.APK_FILE_RELEASE_ARM64 }})) echo "|release_arm64-v8a|$release_arm64" >> $GITHUB_STEP_SUMMARY release_x86=($(sha256sum ${{ env.APK_FILE_RELEASE_X86 }})) echo "|release_x86|$release_x86" >> $GITHUB_STEP_SUMMARY release_x64=($(sha256sum ${{ env.APK_FILE_RELEASE_X64 }})) echo "|release_x86_64|$release_x64" >> $GITHUB_STEP_SUMMARY release_universal=($(sha256sum ${{ env.APK_FILE_RELEASE_UNIVERSAL }})) echo "|release_universal|$release_universal" >> $GITHUB_STEP_SUMMARY # Debug Artifacts debug_arm32=($(sha256sum ${{ env.APK_FILE_DEBUG_ARM32 }})) echo "|debug_armeabi-v7a|$debug_arm32" >> $GITHUB_STEP_SUMMARY debug_arm64=($(sha256sum ${{ env.APK_FILE_DEBUG_ARM64 }})) echo "|debug_arm64-v8a|$debug_arm64" >> $GITHUB_STEP_SUMMARY debug_x86=($(sha256sum ${{ env.APK_FILE_DEBUG_X86 }})) echo "|debug_x86|$debug_x86" >> $GITHUB_STEP_SUMMARY debug_x64=($(sha256sum ${{ env.APK_FILE_DEBUG_X64 }})) echo "|debug_x86_64|$debug_x64" >> $GITHUB_STEP_SUMMARY debug_universal=($(sha256sum ${{ env.APK_FILE_DEBUG_UNIVERSAL }})) echo "|debug_universal|$debug_universal" >> $GITHUB_STEP_SUMMARY - name: Upload Release APK (armeabi-v7a) uses: actions/upload-artifact@v3 with: path: ${{ env.APK_FILE_RELEASE_ARM32 }} name: ClashYou-release-armeabi-v7a-${{ github.event.head_commit.id }} - name: Upload Release APK (arm64-v8a) uses: actions/upload-artifact@v3 with: path: ${{ env.APK_FILE_RELEASE_ARM64 }} name: ClashYou-release-arm64-v8a-${{ github.event.head_commit.id }} - name: Upload Release APK (x86) uses: actions/upload-artifact@v3 with: path: ${{ env.APK_FILE_RELEASE_X86 }} name: ClashYou-release-x86-${{ github.event.head_commit.id }} - name: Upload Release APK (x86_64) uses: actions/upload-artifact@v3 with: path: ${{ env.APK_FILE_RELEASE_X64 }} name: ClashYou-release-x86_64-${{ github.event.head_commit.id }} - name: Upload Release APK (Universal) uses: actions/upload-artifact@v3 with: path: ${{ env.APK_FILE_RELEASE_UNIVERSAL }} name: ClashYou-release-universal-${{ github.event.head_commit.id }} - name: Upload Debug APK (armeabi-v7a) uses: actions/upload-artifact@v3 with: path: ${{ env.APK_FILE_DEBUG_ARM32 }} name: ClashYou-debug-armeabi-v7a-${{ github.event.head_commit.id }} - name: Upload Debug APK (arm64-v8a) uses: actions/upload-artifact@v3 with: path: ${{ env.APK_FILE_DEBUG_ARM64 }} name: ClashYou-debug-arm64-v8a-${{ github.event.head_commit.id }} - name: Upload Debug APK (x86) uses: actions/upload-artifact@v3 with: path: ${{ env.APK_FILE_DEBUG_X86 }} name: ClashYou-debug-x86-${{ github.event.head_commit.id }} - name: Upload Debug APK (x86_64) uses: actions/upload-artifact@v3 with: path: ${{ env.APK_FILE_DEBUG_X64 }} name: ClashYou-debug-x86_64-${{ github.event.head_commit.id }} - name: Upload Debug APK (Universal) uses: actions/upload-artifact@v3 with: path: ${{ env.APK_FILE_DEBUG_UNIVERSAL }} name: ClashYou-debug-universal-${{ github.event.head_commit.id }} ================================================ FILE: .gitignore ================================================ .gradle build/ /app/foss/release /app/premium/release /captures # Ignore Gradle GUI config gradle-app.setting # Avoid ignoring Gradle wrapper jar targetFile (.jar files are usually ignored) !gradle-wrapper.jar # Cache of project .gradletasknamecache # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 # gradle/wrapper/gradle-wrapper.properties # Ignore IDEA config *.iml /.idea/* /core/src/main/golang/.idea/* /core/src/foss/golang/.idea/* /core/src/premium/golang/.idea/* # KeyStore signing.properties *.keystore *.jks # clion cmake build cmake-build-* # local.properties local.properties # tracker tracker.properties # vscode .vscode # cxx .cxx *.hprof # firebase google-services.json # Dolphin .directory # logs *.log # MacOS .DS_Store ================================================ FILE: .gitmodules ================================================ [submodule "clash-foss"] path = core/src/foss/golang/clash url = https://github.com/xuhaoyang/ClashForAndroid.git [submodule "clash-premium"] path = core/src/premium/golang/clash url = https://github.com/xuhaoyang/ClashForAndroid.git ================================================ FILE: CONTRIBUTING.md ================================================ ## Contributing to Clash for Android #### Code Style Please use `Android Studio` or `Intellij IDEA` to open the project and use the project code style profile. `File` -> `Settings` -> `Editor` -> `Code Style` -> `C/C++ and Kotlin` -> `Scheme` -> `Project` #### License Contributing to Clash for Android that assumes you allow code to be merged into closed-source branch of Clash for Android. Other terms follow the [GPLv3](https://www.gnu.org/licenses/gpl-3.0.html) ================================================ FILE: LICENSE ================================================ 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 . ================================================ FILE: NOTICE ================================================ 3th-party software licenses * Clash ========================================================================== 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 . * Android Open Source Project * Android X Support Library ========================================================================== Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS ================================================ FILE: PRIVACY_POLICY.md ================================================ ## Privacy Policy The Clash for Android is built as an Open Source software. This app is provided by personal at no cost and is intended for use as is. This page is used to inform visitors regarding our policies with the collection, use, and disclosure of Personal Information if anyone decided to use our app. **Information Collection and Use** We will not upload any of your personally information and that will be stored in the internal storage or memory. We collect the following information and store it in memory, and such information will be destroyed when the application is fully exited. - Installed Applications This data is used for the PROCESS-NAME rule. **Log Data** We do not collect log data unless you use log collector. **Cookies** Cookies are files with a small amount of data that are commonly used as anonymous unique identifiers. These are sent to your browser from the websites that you visit and are stored on your device's internal memory. This app does not use these “cookies” explicitly. However, the app may use third party code and libraries that use “cookies” to collect information and improve their services. You have the option to either accept or refuse these cookies and know when a cookie is being sent to your device. If you choose to refuse our cookies, you may not be able to use some portions of this app. **Security** We value your trust in providing us your Personal Information, thus we are striving to use commercially acceptable means of protecting it. But remember that no method of transmission over the internet, or method of electronic storage is 100% secure and reliable, and we cannot guarantee its absolute security. **Links to Other Sites** This app may contain links to other sites. If you click on a third-party link, you will be directed to that site. Note that these external sites are not operated by us. Therefore, we strongly advise you to review the Privacy Policy of these websites. We have no control over and assume no responsibility for the content, privacy policies, or practices of any third-party sites or services. **Changes to This Privacy Policy** We may update our Privacy Policy from time to time. Thus, you are advised to review this page periodically for any changes. We will notify you of any changes by posting the new Privacy Policy on this page. These changes are effective immediately after they are posted on this page. **Contact Us** If you have any questions or suggestions about our Privacy Policy, do not hesitate to contact us. ================================================ FILE: README.md ================================================ ## Clash You 📕 [English Version](./README_en.md) 基于 [Clash for Android](),为安卓设备设计的 [Clash]() GUI,使用 Material You 设计语言。 可在 [Releases](https://github.com/Yos-X/ClashYou/releases) 获取最新发布版本,也可在 [Actions](https://github.com/Yos-X/ClashYou/actions) 获取 CI 版(需要登录,感谢 [@淡い夏](https://github.com/lightsummer233)) ### 版本特性 - 适配新安卓版本权限 - 应用主题支持动态取色 - 遵循 MD3 设计风格的 UI ### 注意 Clash You 基于的 Clash for Android **已是最终版本**,进入**长久不更新**状态。 因此 Clash You 使用的旧内核将可能**不支持**新 Clash 内核的部分特性。 若想使用 Clash 的**较新特性**,可以考虑~原作者~ ????? 正在开发的 ????? 项目。 Telegram Channel: ????? ### 特性 完整 [Clash]() 特性实现 ### 运行环境要求 - Android 5.0+ (最低) - Android 12.0+ (推荐) - `armeabi-v7a` , `arm64-v8a`, `x86` 或 `x86_64` 架构 ### 许可证 参见 [LICENSE](./LICENSE) 与 [NOTICE](./NOTICE) ### 隐私协议 参见 [隐私协议](./PRIVACY_POLICY.md) ### 构建 1. 更新子模块(IDEA 项目内 `终端`) ```sh git submodule update --init --recursive ``` 2. 安装 **OpenJDK 11**, **Android SDK**, **CMake** 和 **Golang** 3. 在项目根目录新建 `local.properties`,并写入以下内容 ```properties sdk.dir=/path/to/android-sdk ``` 4. 在项目根目录新建 `signing.properties`,并写入以下内容 ```properties keystore.path=/path/to/keystore/file(签名密钥路径) keystore.password=<签名密钥密码> key.alias=<签名密钥别名> key.password=<签名密钥密码> ``` 5. 构建 ```sh ./gradlew app:assembleFossRelease ``` 6. 输出文件 `app--foss--release.apk` 在 `app/build/outputs/apk/foss/release/` 目录下 ================================================ FILE: README_en.md ================================================ ## Clash You **⚠ This page is translated by GPT 4.** Based on [Clash for Android](), a [Clash]() GUI designed for Android devices, using the Material You design language. The latest Release version can be obtained from [Releases](https://github.com/Yos-X/ClashYou/releases) and CI version can be obtained from [Actions](https://github.com/Yos-X/ClashYou/actions) (login is required, thanks to [@Light_summer](https://github.com/lightsummer233)). ### Version Features - Adapted to new Android version permissions - Application theme supports dynamic color picking - UI following MD3 design style ### Attention Clash You is based on **the final version** of Clash for Android, which has entered **a long-term non update state**. Therefore, the old core used by Clash You may **not support** some features of the new Clash core. For **the newer features** of Clash, consider the ????? project being developed by ~the original author~ ?????. Telegram Channel:????? ### Feature Fully feature of [Clash]() ### Runtime Requirements - Android 5.0+ (minimum) - Android 12.0+ (recommended) - `armeabi-v7a`, `arm64-v8a`, `x86` or `x86_64` architecture ### License See [LICENSE](./LICENSE) and [NOTICE](./NOTICE) ### Privacy Policy See [Privacy Policy](./PRIVACY_POLICY.md) ### Building 1. Update submodules (in IDEA project `terminal`) ```sh git submodule update --init --recursive ``` 2. Install **OpenJDK 11**, **Android SDK**, **CMake** and **Golang** 3. Create a new `local.properties` file in the project root directory and write the following content ```properties sdk.dir=/path/to/android-sdk ``` 4. Create a new `signing.properties` file in the project root directory and write the following content ```properties keystore.path=/path/to/keystore/file keystore.password= key.alias= key.password= ``` 5. Build ```sh ./gradlew app:assembleFossRelease ``` 6. Output file `app--foss--release.apk` is located in the `app/build/outputs/apk/foss/release/` directory. ================================================ FILE: app/build.gradle.kts ================================================ plugins { kotlin("android") kotlin("kapt") id("com.android.application") } dependencies { repositories { mavenLocal() mavenCentral() gradlePluginPortal() google() maven("https://jitpack.io") maven("https://oss.sonatype.org/content/repositories/snapshots/") maven("https://maven.kr328.app/releases") } compileOnly(project(":hideapi")) implementation(project(":core")) implementation(project(":service")) implementation(project(":design")) implementation(project(":common")) implementation(libs.kotlin.coroutine) implementation(libs.androidx.core) implementation(libs.androidx.activity) implementation(libs.androidx.fragment) implementation(libs.androidx.appcompat) implementation(libs.androidx.coordinator) implementation(libs.androidx.recyclerview) implementation(libs.google.material) implementation(libs.androidx.splashscreen) implementation(libs.getactivity.xxpermission) } tasks.getByName("clean", type = Delete::class) { delete(file("release")) } /* android { defaultConfig { applicationId = "yos.clash.material" } } */ ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile -dontobfuscate -assumenosideeffects class kotlin.jvm.internal.Intrinsics { public static void checkNotNull(...); public static void checkExpressionValueIsNotNull(...); public static void checkNotNullExpressionValue(...); public static void checkReturnedValueIsNotNull(...); public static void checkFieldIsNotNull(...); public static void checkParameterIsNotNull(...); public static void checkNotNullParameter(...); } # Kotlin Coroutine # Allow R8 to optimize away the FastServiceLoader. # Together with ServiceLoader optimization in R8 # this results in direct instantiation when loading Dispatchers.Main -assumenosideeffects class kotlinx.coroutines.internal.MainDispatcherLoader { boolean FAST_SERVICE_LOADER_ENABLED return false; } -assumenosideeffects class kotlinx.coroutines.internal.FastServiceLoaderKt { boolean ANDROID_DETECTED return true; } -keep class kotlinx.coroutines.android.AndroidDispatcherFactory {*;} # Disable support for "Missing Main Dispatcher", since we always have Android main dispatcher -assumenosideeffects class kotlinx.coroutines.internal.MainDispatchersKt { boolean SUPPORT_MISSING return false; } # Statically turn off all debugging facilities and assertions -assumenosideeffects class kotlinx.coroutines.DebugKt { boolean getASSERTIONS_ENABLED() return false; boolean getDEBUG() return false; boolean getRECOVER_STACK_TRACES() return false; } ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/yos/clash/material/AccessControlActivity.kt ================================================ package yos.clash.material import android.Manifest.permission.INTERNET import android.content.ClipData import android.content.ClipboardManager import android.content.pm.ApplicationInfo import android.content.pm.PackageInfo import android.content.pm.PackageManager import androidx.core.content.getSystemService import yos.clash.material.design.AccessControlDesign import yos.clash.material.design.model.AppInfo import yos.clash.material.design.util.toAppInfo import yos.clash.material.service.store.ServiceStore import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive import kotlinx.coroutines.selects.select import kotlinx.coroutines.withContext class AccessControlActivity : BaseActivity() { override suspend fun main() { val service = ServiceStore(this) val selected = withContext(Dispatchers.IO) { service.accessControlPackages.toMutableSet() } defer { withContext(Dispatchers.IO) { service.accessControlPackages = selected } } val design = AccessControlDesign(this, uiStore, selected) setContentDesign(design) design.requests.send(AccessControlDesign.Request.ReloadApps) while (isActive) { select { events.onReceive { } design.requests.onReceive { when (it) { AccessControlDesign.Request.ReloadApps -> { design.patchApps(loadApps(selected)) } AccessControlDesign.Request.SelectAll -> { val all = withContext(Dispatchers.Default) { design.apps.map(AppInfo::packageName) } selected.clear() selected.addAll(all) design.rebindAll() } AccessControlDesign.Request.SelectNone -> { selected.clear() design.rebindAll() } AccessControlDesign.Request.SelectInvert -> { val all = withContext(Dispatchers.Default) { design.apps.map(AppInfo::packageName).toSet() - selected } selected.clear() selected.addAll(all) design.rebindAll() } AccessControlDesign.Request.Import -> { val clipboard = getSystemService() val data = clipboard?.primaryClip if (data != null && data.itemCount > 0) { val packages = data.getItemAt(0).text.split("\n").toSet() val all = design.apps.map(AppInfo::packageName).intersect(packages) selected.clear() selected.addAll(all) } design.rebindAll() } AccessControlDesign.Request.Export -> { val clipboard = getSystemService() val data = ClipData.newPlainText( "packages", selected.joinToString("\n") ) clipboard?.setPrimaryClip(data) } } } } } } private suspend fun loadApps(selected: Set): List = withContext(Dispatchers.IO) { val reverse = uiStore.accessControlReverse val sort = uiStore.accessControlSort val systemApp = uiStore.accessControlSystemApp val base = compareByDescending { it.packageName in selected } val comparator = if (reverse) base.thenDescending(sort) else base.then(sort) val pm = packageManager val packages = pm.getInstalledPackages(PackageManager.GET_PERMISSIONS) packages.asSequence() .filter { it.packageName != packageName } .filter { it.packageName == "android" || it.requestedPermissions?.contains(INTERNET) == true } .filter { systemApp || !it.isSystemApp } .map { it.toAppInfo(pm) } .sortedWith(comparator) .toList() } private val PackageInfo.isSystemApp: Boolean get() { return applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0 } } ================================================ FILE: app/src/main/java/yos/clash/material/ApkBrokenActivity.kt ================================================ package yos.clash.material import android.content.Intent import android.net.Uri import yos.clash.material.design.ApkBrokenDesign import kotlinx.coroutines.isActive class ApkBrokenActivity : BaseActivity() { override suspend fun main() { val design = ApkBrokenDesign(this) setContentDesign(design) while (isActive) { val req = design.requests.receive() startActivity(Intent(Intent.ACTION_VIEW).setData(Uri.parse(req.url))) } } } ================================================ FILE: app/src/main/java/yos/clash/material/AppCrashedActivity.kt ================================================ package yos.clash.material import yos.clash.material.common.compat.versionCodeCompat import yos.clash.material.common.log.Log import yos.clash.material.design.AppCrashedDesign import yos.clash.material.log.SystemLogcat import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive import kotlinx.coroutines.withContext class AppCrashedActivity : BaseActivity() { override suspend fun main() { val design = AppCrashedDesign(this) setContentDesign(design) val packageInfo = withContext(Dispatchers.IO) { packageManager.getPackageInfo(packageName, 0) } Log.i("App version: versionName = ${packageInfo.versionName} versionCode = ${packageInfo.versionCodeCompat}") val logs = withContext(Dispatchers.IO) { SystemLogcat.dumpCrash() } design.setAppLogs(logs) while (isActive) { events.receive() } } } ================================================ FILE: app/src/main/java/yos/clash/material/AppSettingsActivity.kt ================================================ package yos.clash.material import android.content.pm.PackageManager import yos.clash.material.common.util.componentName import yos.clash.material.design.AppSettingsDesign import yos.clash.material.design.model.Behavior import yos.clash.material.service.store.ServiceStore import yos.clash.material.util.ApplicationObserver import kotlinx.coroutines.isActive import kotlinx.coroutines.selects.select class AppSettingsActivity : BaseActivity(), Behavior { override suspend fun main() { val design = AppSettingsDesign( this, uiStore, ServiceStore(this), this, clashRunning, ) setContentDesign(design) while (isActive) { select { events.onReceive { when (it) { Event.ClashStart, Event.ClashStop, Event.ServiceRecreated -> recreate() else -> Unit } } design.requests.onReceive { ApplicationObserver.createdActivities.forEach { it.recreate() } } } } } override var autoRestart: Boolean get() { val status = packageManager.getComponentEnabledSetting( RestartReceiver::class.componentName ) return status == PackageManager.COMPONENT_ENABLED_STATE_ENABLED } set(value) { val status = if (value) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED packageManager.setComponentEnabledSetting( RestartReceiver::class.componentName, status, PackageManager.DONT_KILL_APP, ) } } ================================================ FILE: app/src/main/java/yos/clash/material/BaseActivity.kt ================================================ package yos.clash.material import android.content.res.Configuration import android.os.Build import android.os.Bundle import android.view.View import androidx.activity.result.contract.ActivityResultContract import androidx.appcompat.app.AppCompatActivity import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import com.google.android.material.color.DynamicColors import yos.clash.material.common.compat.isAllowForceDarkCompat import yos.clash.material.common.compat.isLightNavigationBarCompat import yos.clash.material.common.compat.isLightStatusBarsCompat import yos.clash.material.common.compat.isSystemBarsTranslucentCompat import com.github.kr328.clash.core.bridge.ClashException import yos.clash.material.design.Design import yos.clash.material.design.model.DarkMode import yos.clash.material.design.store.UiStore import yos.clash.material.design.ui.DayNight import yos.clash.material.design.util.resolveThemedBoolean import yos.clash.material.design.util.resolveThemedColor import yos.clash.material.design.util.showExceptionToast import yos.clash.material.remote.Broadcasts import yos.clash.material.remote.Remote import yos.clash.material.util.ActivityResultLifecycle import yos.clash.material.util.ApplicationObserver import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import java.util.concurrent.atomic.AtomicInteger import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine abstract class BaseActivity> : AppCompatActivity(), CoroutineScope by MainScope(), Broadcasts.Observer { enum class Event { ServiceRecreated, ActivityStart, ActivityStop, ClashStop, ClashStart, ProfileLoaded, ProfileChanged } protected val uiStore by lazy { UiStore(this) } protected val events = Channel(Channel.UNLIMITED) protected var activityStarted: Boolean = false protected val clashRunning: Boolean get() = Remote.broadcasts.clashRunning protected var design: D? = null private set(value) { field = value if (value != null) { setContentView(value.root) } else { setContentView(View(this)) } } private var defer: suspend () -> Unit = {} private var deferRunning = false private val nextRequestKey = AtomicInteger(0) private var dayNight: DayNight = DayNight.Day protected abstract suspend fun main() fun defer(operation: suspend () -> Unit) { this.defer = operation } suspend fun startActivityForResult( contracts: ActivityResultContract, input: I ): O = withContext(Dispatchers.Main) { val requestKey = nextRequestKey.getAndIncrement().toString() ActivityResultLifecycle().use { lifecycle, start -> suspendCoroutine { c -> activityResultRegistry.register(requestKey, lifecycle, contracts) { c.resumeWith(Result.success(it)) }.apply { start() }.launch(input) } } } suspend fun setContentDesign(design: D) { suspendCoroutine { window.decorView.post { this.design = design it.resume(Unit) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) DynamicColors.applyToActivitiesIfAvailable(this.application) applyDayNight() launch { main() finish() } } override fun onStart() { super.onStart() activityStarted = true Remote.broadcasts.addObserver(this) events.trySend(Event.ActivityStart) } override fun onStop() { super.onStop() activityStarted = false Remote.broadcasts.removeObserver(this) events.trySend(Event.ActivityStop) } override fun onDestroy() { design?.cancel() cancel() super.onDestroy() } override fun finish() { if (deferRunning) { return } deferRunning = true launch { try { defer() } finally { withContext(NonCancellable) { super.finish() } } } } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) if (queryDayNight(newConfig) != dayNight) { ApplicationObserver.createdActivities.forEach { it.recreate() } } } open fun shouldDisplayHomeAsUpEnabled(): Boolean { return true } override fun onSupportNavigateUp(): Boolean { this.onBackPressed() return true } override fun onProfileChanged() { events.trySend(Event.ProfileChanged) } override fun onProfileLoaded() { events.trySend(Event.ProfileLoaded) } override fun onServiceRecreated() { events.trySend(Event.ServiceRecreated) } override fun onStarted() { events.trySend(Event.ClashStart) } override fun onStopped(cause: String?) { events.trySend(Event.ClashStop) if (cause != null && activityStarted) { launch { design?.showExceptionToast(ClashException(cause)) } } } private fun queryDayNight(config: Configuration = resources.configuration): DayNight { return when (uiStore.darkMode) { DarkMode.Auto -> { if (config.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES) DayNight.Night else DayNight.Day } DarkMode.ForceLight -> { DayNight.Day } DarkMode.ForceDark -> { DayNight.Night } } } private fun applyDayNight(config: Configuration = resources.configuration) { val dayNight = queryDayNight(config) when (dayNight) { DayNight.Night -> { theme.applyStyle(R.style.AppThemeDark, true) } DayNight.Day -> { theme.applyStyle(R.style.AppThemeLight, true) } } window.isAllowForceDarkCompat = false window.isSystemBarsTranslucentCompat = true window.statusBarColor = resolveThemedColor(android.R.attr.statusBarColor) window.navigationBarColor = resolveThemedColor(android.R.attr.navigationBarColor) if (Build.VERSION.SDK_INT >= 23) { window.isLightStatusBarsCompat = resolveThemedBoolean(android.R.attr.windowLightStatusBar) } if (Build.VERSION.SDK_INT >= 27) { window.isLightNavigationBarCompat = resolveThemedBoolean(android.R.attr.windowLightNavigationBar) } this.dayNight = dayNight } } ================================================ FILE: app/src/main/java/yos/clash/material/ExternalImportActivity.kt ================================================ package yos.clash.material import android.app.Activity import android.content.Intent import android.os.Bundle import yos.clash.material.R import yos.clash.material.common.util.intent import yos.clash.material.common.util.setUUID import yos.clash.material.service.model.Profile import yos.clash.material.util.withProfile import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import java.util.* class ExternalImportActivity : Activity(), CoroutineScope by MainScope() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (intent.action != Intent.ACTION_VIEW) return finish() val uri = intent.data ?: return finish() val url = uri.getQueryParameter("url") ?: return finish() launch { val uuid = withProfile { val type = when (uri.getQueryParameter("type")?.lowercase(Locale.getDefault())) { "url" -> Profile.Type.Url "file" -> Profile.Type.File else -> Profile.Type.Url } val name = uri.getQueryParameter("name") ?: getString(R.string.new_profile) create(type, name).also { patch(it, name, url, 0) } } startActivity(PropertiesActivity::class.intent.setUUID(uuid)) finish() } } } ================================================ FILE: app/src/main/java/yos/clash/material/FilesActivity.kt ================================================ @file:Suppress("BlockingMethodInNonBlockingContext") package yos.clash.material import android.content.Intent import android.net.Uri import androidx.activity.result.contract.ActivityResultContracts import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import com.hjq.permissions.OnPermissionCallback import com.hjq.permissions.Permission import com.hjq.permissions.XXPermissions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.selects.select import yos.clash.material.common.util.grantPermissions import yos.clash.material.common.util.ticker import yos.clash.material.common.util.uuid import yos.clash.material.design.FilesDesign import yos.clash.material.design.util.showExceptionToast import yos.clash.material.remote.FilesClient import yos.clash.material.service.model.Profile import yos.clash.material.util.fileName import yos.clash.material.util.withProfile import java.util.* import java.util.concurrent.TimeUnit class FilesActivity : BaseActivity() { override suspend fun main() { val uuid = intent.uuid ?: return finish() val profile = withProfile { queryByUUID(uuid) } ?: return finish() val root = uuid.toString() val design = FilesDesign(this) val client = FilesClient(this) val stack = Stack() design.configurationEditable = profile.type != Profile.Type.Url design.fetch(client, stack, root) setContentDesign(design) val ticker = ticker(TimeUnit.MINUTES.toMillis(1)) while (isActive) { select { events.onReceive { when (it) { Event.ActivityStart, Event.ActivityStop -> { design.fetch(client, stack, root) } else -> Unit } } design.requests.onReceive { try { when (it) { FilesDesign.Request.PopStack -> { if (stack.empty()) { finish() } else { stack.pop() } } is FilesDesign.Request.OpenDirectory -> { stack.push(it.file.id) } is FilesDesign.Request.OpenFile -> { startActivityForResult( ActivityResultContracts.StartActivityForResult(), Intent(Intent.ACTION_VIEW).setDataAndType( client.buildDocumentUri(it.file.id), "text/plain" ).grantPermissions() ) } is FilesDesign.Request.DeleteFile -> { client.deleteDocument(it.file.id) } is FilesDesign.Request.RenameFile -> { val newName = design.requestFileName(it.file.name) client.renameDocument(it.file.id, newName) } is FilesDesign.Request.ImportFile -> { val hasPermission = XXPermissions.isGranted( this@FilesActivity, Permission.MANAGE_EXTERNAL_STORAGE ) if (!hasPermission) { XXPermissions.with(this@FilesActivity) .permission(Permission.MANAGE_EXTERNAL_STORAGE) .request(object : OnPermissionCallback { override fun onGranted( permissions: MutableList, allGranted: Boolean ) { /*if (!allGranted) { Toast.makeText(this@MainActivity, "部分权限未授予,某些功能可能无法使用", Toast.LENGTH_SHORT).show() }*/ //成功 launch(Dispatchers.Main) { val uri: Uri? = startActivityForResult( ActivityResultContracts.GetContent(), "*/*" ) if (uri != null) { if (it.file == null) { val name = design.requestFileName( uri.fileName ?: "File" ) client.importDocument( stack.last(), uri, name ) } else { client.copyDocument( it.file!!.id, uri ) } design.fetch(client, stack, root) } } } override fun onDenied( permissions: MutableList, doNotAskAgain: Boolean ) { if (doNotAskAgain) { // 如果是被永久拒绝就跳转到应用权限系统设置页面 XXPermissions.startPermissionActivity( this@FilesActivity, permissions ) } } }) /*val granted = startActivityForResult( ActivityResultContracts.RequestPermission(), Manifest.permission.READ_EXTERNAL_STORAGE, ) if (!granted) { return@onReceive }*/ } else { val uri: Uri? = startActivityForResult( ActivityResultContracts.GetContent(), "*/*" ) if (uri != null) { if (it.file == null) { val name = design.requestFileName( uri.fileName ?: "File" ) client.importDocument( stack.last(), uri, name ) } else { client.copyDocument( it.file!!.id, uri ) } design.fetch(client, stack, root) } } } is FilesDesign.Request.ExportFile -> { val uri: Uri? = startActivityForResult( ActivityResultContracts.CreateDocument("text/plain"), it.file.name ) if (uri != null) { client.copyDocument(uri, it.file.id) } } } } catch (e: Exception) { design.showExceptionToast(e) } design.fetch(client, stack, root) } if (activityStarted) { ticker.onReceive { design.updateElapsed() } } } } } override fun onBackPressed() { design?.requests?.trySend(FilesDesign.Request.PopStack) } private suspend fun FilesDesign.fetch(client: FilesClient, stack: Stack, root: String) { val documentId = stack.lastOrNull() ?: root val files = if (stack.empty()) { val list = client.list(documentId) val config = list.firstOrNull { it.id.endsWith("config.yaml") } if (config == null || config.size > 0) list else listOf(config) } else { client.list(documentId) } swapFiles(files, stack.empty()) } } ================================================ FILE: app/src/main/java/yos/clash/material/HelpActivity.kt ================================================ package yos.clash.material import android.content.Intent import yos.clash.material.design.HelpDesign import kotlinx.coroutines.isActive class HelpActivity : BaseActivity() { override suspend fun main() { val design = HelpDesign(this) { startActivity(Intent(Intent.ACTION_VIEW).setData(it)) } setContentDesign(design) while (isActive) { events.receive() } } } ================================================ FILE: app/src/main/java/yos/clash/material/LogcatActivity.kt ================================================ package yos.clash.material import android.content.ComponentName import android.content.Context import android.content.ServiceConnection import android.net.Uri import android.os.IBinder import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import yos.clash.material.common.compat.startForegroundServiceCompat import yos.clash.material.common.util.fileName import yos.clash.material.common.util.intent import yos.clash.material.common.util.ticker import com.github.kr328.clash.core.model.LogMessage import yos.clash.material.design.LogcatDesign import yos.clash.material.design.dialog.withModelProgressBar import yos.clash.material.design.model.LogFile import yos.clash.material.design.ui.ToastDuration import yos.clash.material.design.util.showExceptionToast import yos.clash.material.log.LogcatFilter import yos.clash.material.log.LogcatReader import yos.clash.material.util.logsDir import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive import kotlinx.coroutines.selects.select import kotlinx.coroutines.withContext import java.io.OutputStreamWriter import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class LogcatActivity : BaseActivity() { private var conn: ServiceConnection? = null override suspend fun main() { val fileName = intent?.fileName if (fileName != null) { val file = LogFile.parseFromFileName(fileName) ?: return showInvalid() return mainLocalFile(file) } return mainStreaming() } private suspend fun mainLocalFile(file: LogFile) { val messages = try { LogcatReader(this, file).readAll() } catch (e: Exception) { return showInvalid() } val design = LogcatDesign(this, false) setContentDesign(design) design.patchMessages(messages, 0, messages.size) while (isActive) { when (design.requests.receive()) { LogcatDesign.Request.Delete -> { withContext(Dispatchers.IO) { logsDir.resolve(file.fileName).delete() } finish() } LogcatDesign.Request.Export -> { val output = startActivityForResult( ActivityResultContracts.CreateDocument("text/plain"), file.fileName ) if (output != null) { try { withContext(Dispatchers.IO) { writeLogTo(messages, file, output) } design.showToast(R.string.file_exported, ToastDuration.Long) } catch (e: Exception) { design.showExceptionToast(e) } } } else -> Unit } } } private suspend fun mainStreaming() { val design = LogcatDesign(this, true) setContentDesign(design) startForegroundServiceCompat(LogcatService::class.intent) val logcat = bindLogcatService() val ticker = ticker(500) var initial = true while (isActive) { select { events.onReceive { } design.requests.onReceive { when (it) { LogcatDesign.Request.Close -> { stopService(LogcatService::class.intent) finish() } else -> Unit } } if (activityStarted) { ticker.onReceive { val snapshot = logcat.snapshot(initial) ?: return@onReceive design.patchMessages(snapshot.messages, snapshot.removed, snapshot.appended) initial = false } } } } } override fun onDestroy() { conn?.apply(this::unbindService) super.onDestroy() } private suspend fun bindLogcatService(): LogcatService { return suspendCoroutine { ctx -> bindService(LogcatService::class.intent, object : ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { val srv = service!!.queryLocalInterface("") as LogcatService ctx.resume(srv) conn = this } override fun onServiceDisconnected(name: ComponentName?) { conn = null } }, Context.BIND_AUTO_CREATE) } } @Suppress("BlockingMethodInNonBlockingContext") private suspend fun writeLogTo(messages: List, file: LogFile, uri: Uri) { LogcatFilter(OutputStreamWriter(contentResolver.openOutputStream(uri)), this).use { withContext(Dispatchers.Main) { withModelProgressBar { configure { isIndeterminate = true max = messages.size } withContext(Dispatchers.IO) { it.writeHeader(file.date) messages.forEachIndexed { idx, msg -> configure { isIndeterminate = false progress = idx } it.writeMessage(msg) } } } } } } private fun showInvalid() { Toast.makeText(this, R.string.invalid_log_file, Toast.LENGTH_LONG).show() } } ================================================ FILE: app/src/main/java/yos/clash/material/LogcatService.kt ================================================ package yos.clash.material import android.app.PendingIntent import android.app.Service import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE import android.os.Binder import android.os.Build import android.os.IBinder import android.os.IInterface import androidx.core.app.NotificationChannelCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.github.kr328.clash.core.model.LogMessage import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import yos.clash.material.common.compat.getColorCompat import yos.clash.material.common.compat.pendingIntentFlags import yos.clash.material.common.log.Log import yos.clash.material.common.util.intent import yos.clash.material.log.LogcatCache import yos.clash.material.log.LogcatWriter import yos.clash.material.service.RemoteService import yos.clash.material.service.remote.ILogObserver import yos.clash.material.service.remote.IRemoteService import yos.clash.material.service.remote.unwrap import yos.clash.material.util.logsDir import java.io.IOException class LogcatService : Service(), CoroutineScope by CoroutineScope(Dispatchers.Default), IInterface { private val cache = LogcatCache() private val connection = object : ServiceConnection { override fun onServiceDisconnected(name: ComponentName?) { stopSelf() } override fun onServiceConnected(name: ComponentName?, service: IBinder?) { startObserver(service ?: return stopSelf()) } } override fun onCreate() { super.onCreate() running = true createNotificationChannel() showNotification() bindService(RemoteService::class.intent, connection, Context.BIND_AUTO_CREATE) } override fun onDestroy() { cancel() unbindService(connection) stopForeground(true) running = false super.onDestroy() } override fun onBind(intent: Intent?): IBinder { return this.asBinder() } override fun asBinder(): IBinder { return object : Binder() { override fun queryLocalInterface(descriptor: String): IInterface { return this@LogcatService } } } suspend fun snapshot(full: Boolean): LogcatCache.Snapshot? { return cache.snapshot(full) } private fun startObserver(binder: IBinder) { if (!binder.isBinderAlive) return stopSelf() launch(Dispatchers.IO) { val service = binder.unwrap(IRemoteService::class).clash() val channel = Channel(CACHE_CAPACITY) try { logsDir.mkdirs() LogcatWriter(this@LogcatService).use { val observer = object : ILogObserver { override fun newItem(log: LogMessage) { channel.trySend(log) } } service.setLogObserver(observer) while (isActive) { val msg = channel.receive() it.appendMessage(msg) cache.append(msg) } } } catch (e: IOException) { Log.e("Write log file: $e", e) } finally { withContext(NonCancellable) { if (binder.isBinderAlive) { service.setLogObserver(null) } stopSelf() } } } } private fun createNotificationChannel() { NotificationManagerCompat.from(this) .createNotificationChannel( NotificationChannelCompat.Builder( CHANNEL_ID, NotificationManagerCompat.IMPORTANCE_DEFAULT ).setName(getString(R.string.clash_logcat)).build() ) } private fun showNotification() { val notification = NotificationCompat .Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_logo_service) .setColor(getColorCompat(R.color.color_clash_light)) .setContentTitle(getString(R.string.clash_logcat)) .setContentText(getString(R.string.running)) .setContentIntent( PendingIntent.getActivity( this, R.id.nf_logcat_status, LogcatActivity::class.intent .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP), pendingIntentFlags(PendingIntent.FLAG_UPDATE_CURRENT) ) ) .build() // startForeground(R.id.nf_logcat_status, notification) if (Build.VERSION.SDK_INT >= 34) { startForeground( R.id.nf_logcat_status, notification, FOREGROUND_SERVICE_TYPE_SPECIAL_USE ) } else { startForeground(R.id.nf_logcat_status, notification) } // Adapt to Android 14 } companion object { private const val CHANNEL_ID = "clash_logcat_channel" private const val CACHE_CAPACITY = 128 var running: Boolean = false } } ================================================ FILE: app/src/main/java/yos/clash/material/LogsActivity.kt ================================================ package yos.clash.material import yos.clash.material.common.util.intent import yos.clash.material.common.util.setFileName import yos.clash.material.design.LogsDesign import yos.clash.material.design.model.LogFile import yos.clash.material.util.logsDir import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive import kotlinx.coroutines.selects.select import kotlinx.coroutines.withContext class LogsActivity : BaseActivity() { override suspend fun main() { if (LogcatService.running) { return startActivity(LogcatActivity::class.intent) } val design = LogsDesign(this) setContentDesign(design) while (isActive) { select { events.onReceive { when (it) { Event.ActivityStart -> { val files = withContext(Dispatchers.IO) { loadFiles() } design.patchLogs(files) } else -> Unit } } design.requests.onReceive { when (it) { LogsDesign.Request.StartLogcat -> { startActivity(LogcatActivity::class.intent) finish() } LogsDesign.Request.DeleteAll -> { if (design.requestDeleteAll()) { withContext(Dispatchers.IO) { deleteAllLogs() } events.trySend(Event.ActivityStart) } } is LogsDesign.Request.OpenFile -> { startActivity(LogcatActivity::class.intent.setFileName(it.file.fileName)) } } } } } } private fun loadFiles(): List { val list = cacheDir.resolve("logs").listFiles()?.toList() ?: emptyList() return list.mapNotNull { LogFile.parseFromFileName(it.name) } } private fun deleteAllLogs() { logsDir.deleteRecursively() } } ================================================ FILE: app/src/main/java/yos/clash/material/MainActivity.kt ================================================ package yos.clash.material import android.content.Context import androidx.activity.result.contract.ActivityResultContracts import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import com.hjq.permissions.OnPermissionCallback import com.hjq.permissions.Permission import com.hjq.permissions.XXPermissions import yos.clash.material.R import yos.clash.material.common.util.intent import yos.clash.material.common.util.ticker import yos.clash.material.design.MainDesign import yos.clash.material.design.ui.ToastDuration import yos.clash.material.store.TipsStore import yos.clash.material.util.startClashService import yos.clash.material.util.stopClashService import yos.clash.material.util.withClash import yos.clash.material.util.withProfile import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.selects.select import kotlinx.coroutines.withContext import java.util.concurrent.TimeUnit class MainActivity : BaseActivity() { override suspend fun main() { installSplashScreen() val design = MainDesign(this) setContentDesign(design) launch(Dispatchers.IO) { showUpdatedTips(design) checkNotificationPermission(design) } design.fetch() val ticker = ticker(TimeUnit.SECONDS.toMillis(1)) while (isActive) { select { events.onReceive { when (it) { Event.ActivityStart, Event.ServiceRecreated, Event.ClashStop, Event.ClashStart, Event.ProfileLoaded, Event.ProfileChanged -> design.fetch() else -> Unit } } design.requests.onReceive { when (it) { MainDesign.Request.ToggleStatus -> { if (clashRunning) stopClashService() else design.startClash() } MainDesign.Request.OpenProxy -> startActivity(ProxyActivity::class.intent) MainDesign.Request.OpenProfiles -> startActivity(ProfilesActivity::class.intent) MainDesign.Request.OpenProviders -> startActivity(ProvidersActivity::class.intent) MainDesign.Request.OpenLogs -> startActivity(LogsActivity::class.intent) MainDesign.Request.OpenSettings -> startActivity(SettingsActivity::class.intent) MainDesign.Request.OpenHelp -> startActivity(HelpActivity::class.intent) MainDesign.Request.OpenAbout -> design.showAbout(queryAppVersionName()) } } if (clashRunning) { ticker.onReceive { design.fetchTraffic() } } } } } private suspend fun showUpdatedTips(design: MainDesign) { val tips = TipsStore(this) if (tips.primaryVersion != TipsStore.CURRENT_PRIMARY_VERSION) { tips.primaryVersion = TipsStore.CURRENT_PRIMARY_VERSION val pkg = packageManager.getPackageInfo(packageName, 0) if (pkg.firstInstallTime != pkg.lastUpdateTime) { design.showUpdatedTips() } } } private suspend fun checkNotificationPermission(design: MainDesign) { val permission = XXPermissions.isGranted(this, Permission.POST_NOTIFICATIONS) if (!permission) { design.showPermissionRequest() } } private suspend fun MainDesign.fetch() { setClashRunning(clashRunning) val state = withClash { queryTunnelState() } val providers = withClash { queryProviders() } setMode(state.mode) setHasProviders(providers.isNotEmpty()) withProfile { setProfileName(queryActive()?.name) } } private suspend fun MainDesign.fetchTraffic() { withClash { setForwarded(queryTrafficTotal()) } } private suspend fun MainDesign.startClash() { val active = withProfile { queryActive() } if (active == null || !active.imported) { showToast(R.string.no_profile_selected, ToastDuration.Long) { setAction(R.string.profiles) { startActivity(ProfilesActivity::class.intent) } } return } val vpnRequest = startClashService() try { if (vpnRequest != null) { val result = startActivityForResult( ActivityResultContracts.StartActivityForResult(), vpnRequest ) if (result.resultCode == RESULT_OK) startClashService() } } catch (e: Exception) { design?.showToast(R.string.unable_to_start_vpn, ToastDuration.Long) } } private suspend fun queryAppVersionName(): String { return withContext(Dispatchers.IO) { packageManager.getPackageInfo(packageName, 0).versionName } } } ================================================ FILE: app/src/main/java/yos/clash/material/MainApplication.kt ================================================ package yos.clash.material import android.app.Application import android.content.Context import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import yos.clash.material.common.Global import yos.clash.material.common.compat.currentProcessName import yos.clash.material.common.log.Log import yos.clash.material.remote.Remote import yos.clash.material.service.util.sendServiceRecreated @Suppress("unused") class MainApplication : Application() { override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) Global.init(this) } override fun onCreate() { super.onCreate() val processName = currentProcessName Log.d("Process $processName started") if (processName == packageName) { Remote.launch() } else { sendServiceRecreated() } } fun finalize() { Global.destroy() } } ================================================ FILE: app/src/main/java/yos/clash/material/NetworkSettingsActivity.kt ================================================ package yos.clash.material import yos.clash.material.common.util.intent import yos.clash.material.design.NetworkSettingsDesign import yos.clash.material.service.store.ServiceStore import kotlinx.coroutines.isActive import kotlinx.coroutines.selects.select class NetworkSettingsActivity : BaseActivity() { override suspend fun main() { val design = NetworkSettingsDesign( this, uiStore, ServiceStore(this), clashRunning, ) setContentDesign(design) while (isActive) { select { events.onReceive { when (it) { Event.ClashStart, Event.ClashStop, Event.ServiceRecreated -> recreate() else -> Unit } } design.requests.onReceive { when (it) { NetworkSettingsDesign.Request.StartAccessControlList -> startActivity(AccessControlActivity::class.intent) } } } } } } ================================================ FILE: app/src/main/java/yos/clash/material/NewProfileActivity.kt ================================================ package yos.clash.material import android.app.Activity import android.content.ComponentName import android.content.Intent import android.net.Uri import android.provider.Settings import androidx.activity.result.contract.ActivityResultContracts import yos.clash.material.R import yos.clash.material.common.constants.Intents import yos.clash.material.common.util.intent import yos.clash.material.common.util.setUUID import yos.clash.material.design.NewProfileDesign import yos.clash.material.design.model.ProfileProvider import yos.clash.material.service.model.Profile import yos.clash.material.util.withProfile import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive import kotlinx.coroutines.selects.select import kotlinx.coroutines.withContext import java.util.* class NewProfileActivity : BaseActivity() { private val self: NewProfileActivity get() = this override suspend fun main() { val design = NewProfileDesign(this) design.patchProviders(queryProfileProviders()) setContentDesign(design) while (isActive) { select { events.onReceive { } design.requests.onReceive { when (it) { is NewProfileDesign.Request.Create -> { withProfile { val name = getString(R.string.new_profile) val uuid: UUID? = when (val p = it.provider) { is ProfileProvider.File -> create(Profile.Type.File, name) is ProfileProvider.Url -> create(Profile.Type.Url, name) is ProfileProvider.External -> { val data = p.get() if (data != null) { val (uri, initialName) = data create( Profile.Type.External, initialName ?: name, uri.toString() ) } else { null } } } if (uuid != null) launchProperties(uuid) } } is NewProfileDesign.Request.OpenDetail -> { launchAppDetailed(it.provider) } } } } } } private fun launchAppDetailed(provider: ProfileProvider.External) { val data = Uri.fromParts( "package", provider.intent.component?.packageName ?: return, null ) startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).setData(data)) } private suspend fun launchProperties(uuid: UUID) { val r = startActivityForResult( ActivityResultContracts.StartActivityForResult(), PropertiesActivity::class.intent.setUUID(uuid) ) if (r.resultCode == Activity.RESULT_OK) finish() } private suspend fun ProfileProvider.External.get(): Pair? { val result = startActivityForResult( ActivityResultContracts.StartActivityForResult(), intent ) if (result.resultCode != RESULT_OK) return null val uri = result.data?.data val name = result.data?.getStringExtra(Intents.EXTRA_NAME) if (uri != null) { return uri to name } return null } private suspend fun queryProfileProviders(): List { return withContext(Dispatchers.IO) { val providers = packageManager.queryIntentActivities( Intent(Intents.ACTION_PROVIDE_URL), 0 ).map { val activity = it.activityInfo val name = activity.applicationInfo.loadLabel(packageManager) val summary = activity.loadLabel(packageManager) val icon = activity.loadIcon(packageManager) val intent = Intent(Intents.ACTION_PROVIDE_URL) .setComponent( ComponentName( activity.packageName, activity.name ) ) ProfileProvider.External(name.toString(), summary.toString(), icon, intent) } listOf(ProfileProvider.File(self), ProfileProvider.Url(self)) + providers } } } ================================================ FILE: app/src/main/java/yos/clash/material/OverrideSettingsActivity.kt ================================================ package yos.clash.material import android.content.pm.PackageManager import yos.clash.material.common.compat.getDrawableCompat import yos.clash.material.common.constants.Metadata import com.github.kr328.clash.core.Clash import yos.clash.material.design.OverrideSettingsDesign import yos.clash.material.design.model.AppInfo import yos.clash.material.design.util.toAppInfo import yos.clash.material.service.store.ServiceStore import yos.clash.material.util.withClash import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive import kotlinx.coroutines.selects.select import kotlinx.coroutines.withContext class OverrideSettingsActivity : BaseActivity() { override suspend fun main() { val configuration = withClash { queryOverride(Clash.OverrideSlot.Persist) } val service = ServiceStore(this) defer { withClash { patchOverride(Clash.OverrideSlot.Persist, configuration) } } val design = OverrideSettingsDesign( this, configuration ) setContentDesign(design) while (isActive) { select { events.onReceive { } design.requests.onReceive { when (it) { OverrideSettingsDesign.Request.ResetOverride -> { if (design.requestResetConfirm()) { defer { withClash { clearOverride(Clash.OverrideSlot.Persist) } service.sideloadGeoip = "" } finish() } } OverrideSettingsDesign.Request.EditSideloadGeoip -> { withContext(Dispatchers.IO) { val list = querySideloadProviders() val initial = service.sideloadGeoip val exist = list.any { info -> info.packageName == initial } service.sideloadGeoip = design.requestSelectSideload(if (exist) initial else "", list) } } } } } } } private fun querySideloadProviders(): List { val apps = packageManager.getInstalledPackages(PackageManager.GET_META_DATA) .filter { it.applicationInfo.metaData?.containsKey(Metadata.GEOIP_FILE_NAME) ?: false } .map { it.toAppInfo(packageManager) } return listOf( AppInfo( packageName = "", label = getString(R.string.use_built_in), icon = getDrawableCompat(R.drawable.ic_baseline_work)!!, installTime = 0, updateDate = 0, ) ) + apps } } ================================================ FILE: app/src/main/java/yos/clash/material/ProfilesActivity.kt ================================================ package yos.clash.material import yos.clash.material.common.util.intent import yos.clash.material.common.util.setUUID import yos.clash.material.common.util.ticker import yos.clash.material.design.ProfilesDesign import yos.clash.material.service.model.Profile import yos.clash.material.util.withProfile import kotlinx.coroutines.isActive import kotlinx.coroutines.selects.select import java.util.concurrent.TimeUnit class ProfilesActivity : BaseActivity() { override suspend fun main() { val design = ProfilesDesign(this) setContentDesign(design) val ticker = ticker(TimeUnit.MINUTES.toMillis(1)) while (isActive) { select { events.onReceive { when (it) { Event.ActivityStart, Event.ProfileChanged -> { design.fetch() } else -> Unit } } design.requests.onReceive { when (it) { ProfilesDesign.Request.Create -> startActivity(NewProfileActivity::class.intent) ProfilesDesign.Request.UpdateAll -> withProfile { queryAll().forEach { p -> if (p.imported && p.type != Profile.Type.File) update(p.uuid) } } is ProfilesDesign.Request.Update -> withProfile { update(it.profile.uuid) } is ProfilesDesign.Request.Delete -> withProfile { delete(it.profile.uuid) } is ProfilesDesign.Request.Edit -> startActivity(PropertiesActivity::class.intent.setUUID(it.profile.uuid)) is ProfilesDesign.Request.Active -> { withProfile { if (it.profile.imported) setActive(it.profile) else design.requestSave(it.profile) } } is ProfilesDesign.Request.Duplicate -> { val uuid = withProfile { clone(it.profile.uuid) } startActivity(PropertiesActivity::class.intent.setUUID(uuid)) } } } if (activityStarted) { ticker.onReceive { design.updateElapsed() } } } } } private suspend fun ProfilesDesign.fetch() { withProfile { patchProfiles(queryAll()) } } } ================================================ FILE: app/src/main/java/yos/clash/material/PropertiesActivity.kt ================================================ package yos.clash.material import yos.clash.material.R import yos.clash.material.common.util.intent import yos.clash.material.common.util.setUUID import yos.clash.material.common.util.uuid import yos.clash.material.design.PropertiesDesign import yos.clash.material.design.ui.ToastDuration import yos.clash.material.design.util.showExceptionToast import yos.clash.material.service.model.Profile import yos.clash.material.util.withProfile import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.selects.select class PropertiesActivity : BaseActivity() { private var canceled: Boolean = false override suspend fun main() { setResult(RESULT_CANCELED) val uuid = intent.uuid ?: return finish() val design = PropertiesDesign(this) val original = withProfile { queryByUUID(uuid) } ?: return finish() design.profile = original setContentDesign(design) defer { canceled = true withProfile { release(uuid) } } while (isActive) { select { events.onReceive { when (it) { Event.ActivityStop -> { val profile = design.profile if (!canceled && profile != original) { withProfile { patch(profile.uuid, profile.name, profile.source, profile.interval) } } } Event.ServiceRecreated -> { finish() } else -> Unit } } design.requests.onReceive { when (it) { PropertiesDesign.Request.BrowseFiles -> { startActivity(FilesActivity::class.intent.setUUID(uuid)) } PropertiesDesign.Request.Commit -> { design.verifyAndCommit() } } } } } } override fun onBackPressed() { design?.apply { launch { if (!progressing) { if (requestExitWithoutSaving()) finish() } } } ?: return super.onBackPressed() } private suspend fun PropertiesDesign.verifyAndCommit() { when { profile.name.isBlank() -> { showToast(R.string.empty_name, ToastDuration.Long) } profile.type != Profile.Type.File && profile.source.isBlank() -> { showToast(R.string.invalid_url, ToastDuration.Long) } else -> { try { withProcessing { updateStatus -> withProfile { patch(profile.uuid, profile.name, profile.source, profile.interval) coroutineScope { commit(profile.uuid) { launch { updateStatus(it) } } } } } setResult(RESULT_OK) finish() } catch (e: Exception) { showExceptionToast(e) } } } } } ================================================ FILE: app/src/main/java/yos/clash/material/ProvidersActivity.kt ================================================ package yos.clash.material import yos.clash.material.R import yos.clash.material.common.util.intent import yos.clash.material.common.util.ticker import yos.clash.material.design.ProvidersDesign import yos.clash.material.design.util.showExceptionToast import yos.clash.material.util.withClash import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.selects.select import java.util.concurrent.TimeUnit class ProvidersActivity : BaseActivity() { override suspend fun main() { val providers = withClash { queryProviders().sorted() } val design = ProvidersDesign(this, providers) setContentDesign(design) val ticker = ticker(TimeUnit.MINUTES.toMillis(1)) while (isActive) { select { events.onReceive { when (it) { Event.ProfileLoaded -> { val newList = withClash { queryProviders().sorted() } if (newList != providers) { startActivity(ProvidersActivity::class.intent) finish() } } else -> Unit } } design.requests.onReceive { when (it) { is ProvidersDesign.Request.Update -> { launch { try { withClash { updateProvider(it.provider.type, it.provider.name) } design.notifyChanged(it.index) } catch (e: Exception) { design.showExceptionToast( getString( R.string.format_update_provider_failure, it.provider.name, e.message ) ) design.notifyUpdated(it.index) } } } } } if (activityStarted) { ticker.onReceive { design.updateElapsed() } } } } } } ================================================ FILE: app/src/main/java/yos/clash/material/ProxyActivity.kt ================================================ package yos.clash.material import yos.clash.material.common.util.intent import com.github.kr328.clash.core.Clash import com.github.kr328.clash.core.model.Proxy import yos.clash.material.design.ProxyDesign import yos.clash.material.design.model.ProxyState import yos.clash.material.store.TipsStore import yos.clash.material.util.withClash import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.selects.select import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import java.util.concurrent.TimeUnit class ProxyActivity : BaseActivity() { override suspend fun main() { val mode = withClash { queryOverride(Clash.OverrideSlot.Session).mode } val names = withClash { queryProxyGroupNames(uiStore.proxyExcludeNotSelectable) } val states = List(names.size) { ProxyState("?") } val unorderedStates = names.indices.map { names[it] to states[it] }.toMap() val reloadLock = Semaphore(10) val tips = TipsStore(this) val design = ProxyDesign( this, mode, names, uiStore ) setContentDesign(design) launch(Dispatchers.IO) { val pkg = packageManager.getPackageInfo(packageName, 0) val validate = System.currentTimeMillis() - pkg.firstInstallTime > TimeUnit.DAYS.toMillis(5) if (tips.requestDonate && validate) { tips.requestDonate = false design.requestDonate() } } design.requests.send(ProxyDesign.Request.ReloadAll) while (isActive) { select { events.onReceive { when (it) { Event.ProfileLoaded -> { val newNames = withClash { queryProxyGroupNames(uiStore.proxyExcludeNotSelectable) } if (newNames != names) { startActivity(ProxyActivity::class.intent) finish() } } else -> Unit } } design.requests.onReceive { when (it) { ProxyDesign.Request.ReLaunch -> { startActivity(ProxyActivity::class.intent) finish() } ProxyDesign.Request.ReloadAll -> { names.indices.forEach { idx -> design.requests.trySend(ProxyDesign.Request.Reload(idx)) } } is ProxyDesign.Request.Reload -> { launch { val group = reloadLock.withPermit { withClash { queryProxyGroup(names[it.index], uiStore.proxySort) } } val state = states[it.index] state.now = group.now design.updateGroup( it.index, group.proxies, group.type == Proxy.Type.Selector, state, unorderedStates ) } } is ProxyDesign.Request.Select -> { withClash { patchSelector(names[it.index], it.name) states[it.index].now = it.name } design.requestRedrawVisible() } is ProxyDesign.Request.UrlTest -> { launch { withClash { healthCheck(names[it.index]) } design.requests.send(ProxyDesign.Request.Reload(it.index)) } } is ProxyDesign.Request.PatchMode -> { design.showModeSwitchTips() withClash { val o = queryOverride(Clash.OverrideSlot.Session) o.mode = it.mode patchOverride(Clash.OverrideSlot.Session, o) } } } } } } } } ================================================ FILE: app/src/main/java/yos/clash/material/RestartReceiver.kt ================================================ package yos.clash.material import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import yos.clash.material.service.StatusProvider import yos.clash.material.util.startClashService class RestartReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { when (intent.action) { Intent.ACTION_BOOT_COMPLETED, Intent.ACTION_MY_PACKAGE_REPLACED -> { if (StatusProvider.shouldStartClashOnBoot) context.startClashService() } } } } ================================================ FILE: app/src/main/java/yos/clash/material/SettingsActivity.kt ================================================ package yos.clash.material import yos.clash.material.common.util.intent import yos.clash.material.design.SettingsDesign import kotlinx.coroutines.isActive import kotlinx.coroutines.selects.select class SettingsActivity : BaseActivity() { override suspend fun main() { val design = SettingsDesign(this) setContentDesign(design) while (isActive) { select { events.onReceive { } design.requests.onReceive { when (it) { SettingsDesign.Request.StartApp -> startActivity(AppSettingsActivity::class.intent) SettingsDesign.Request.StartNetwork -> startActivity(NetworkSettingsActivity::class.intent) SettingsDesign.Request.StartOverride -> startActivity(OverrideSettingsActivity::class.intent) } } } } } } ================================================ FILE: app/src/main/java/yos/clash/material/TileService.kt ================================================ package yos.clash.material import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.drawable.Icon import android.os.Build import android.service.quicksettings.Tile import android.service.quicksettings.TileService import androidx.annotation.RequiresApi import yos.clash.material.R import yos.clash.material.common.constants.Intents import yos.clash.material.common.constants.Permissions import yos.clash.material.remote.StatusClient import yos.clash.material.util.startClashService import yos.clash.material.util.stopClashService @RequiresApi(Build.VERSION_CODES.N) class TileService : TileService() { private var currentProfile = "" private var clashRunning = false override fun onClick() { val tile = qsTile ?: return when (tile.state) { Tile.STATE_INACTIVE -> { startClashService() } Tile.STATE_ACTIVE -> { stopClashService() } } } override fun onStartListening() { super.onStartListening() registerReceiver( receiver, IntentFilter().apply { addAction(Intents.ACTION_CLASH_STARTED) addAction(Intents.ACTION_CLASH_STOPPED) addAction(Intents.ACTION_PROFILE_LOADED) addAction(Intents.ACTION_SERVICE_RECREATED) }, Permissions.RECEIVE_SELF_BROADCASTS, null ) val name = StatusClient(this).currentProfile() clashRunning = name != null currentProfile = name ?: "" updateTile() } override fun onStopListening() { super.onStopListening() unregisterReceiver(receiver) } private fun updateTile() { val tile = qsTile ?: return tile.state = if (clashRunning) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE tile.label = if (currentProfile.isEmpty()) getText(R.string.launch_name) else currentProfile tile.icon = Icon.createWithResource(this, R.drawable.ic_logo_service) tile.updateTile() } private val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (intent?.action) { Intents.ACTION_CLASH_STARTED -> { clashRunning = true currentProfile = "" } Intents.ACTION_CLASH_STOPPED, Intents.ACTION_SERVICE_RECREATED -> { clashRunning = false currentProfile = "" } Intents.ACTION_PROFILE_LOADED -> { currentProfile = StatusClient(this@TileService).currentProfile() ?: "" } } updateTile() } } } ================================================ FILE: app/src/main/java/yos/clash/material/log/LogcatCache.kt ================================================ package yos.clash.material.log import androidx.collection.CircularArray import com.github.kr328.clash.core.model.LogMessage import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock class LogcatCache { data class Snapshot(val messages: List, val removed: Int, val appended: Int) private val array = CircularArray(CAPACITY) private val lock = Mutex() private var removed: Int = 0 private var appended: Int = 0 suspend fun append(msg: LogMessage) { lock.withLock { if (array.size() >= CAPACITY) { array.removeFromStart(1) removed++ appended-- } array.addLast(msg) appended++ } } suspend fun snapshot(full: Boolean): Snapshot? { return lock.withLock { if (!full && removed == 0 && appended == 0) { return@withLock null } Snapshot( List(array.size()) { array[it] }, removed, if (full) array.size() + appended else appended ).also { removed = 0 appended = 0 } } } companion object { const val CAPACITY = 128 } } ================================================ FILE: app/src/main/java/yos/clash/material/log/LogcatFilter.kt ================================================ package yos.clash.material.log import android.content.Context import com.github.kr328.clash.core.model.LogMessage import yos.clash.material.design.util.format import java.io.BufferedWriter import java.io.Writer import java.util.* class LogcatFilter(output: Writer, private val context: Context) : BufferedWriter(output) { fun writeHeader(time: Date) { appendLine("# Capture on ${time.format(context)}") } fun writeMessage(message: LogMessage) { val time = message.time.format(context, includeDate = false) val level = message.level.name appendLine(FORMAT.format(time, level, message.message)) } companion object { private const val FORMAT = "%12s %7s: %s" } } ================================================ FILE: app/src/main/java/yos/clash/material/log/LogcatReader.kt ================================================ package yos.clash.material.log import android.content.Context import com.github.kr328.clash.core.model.LogMessage import yos.clash.material.design.model.LogFile import yos.clash.material.util.logsDir import java.io.BufferedReader import java.io.FileReader import java.util.* class LogcatReader(context: Context, file: LogFile) : AutoCloseable { private val reader = BufferedReader(FileReader(context.logsDir.resolve(file.fileName))) override fun close() { reader.close() } fun readAll(): List { return reader.lineSequence() .map { it.trim() } .filter { !it.startsWith("#") } .map { it.split(":", limit = 3) } .map { LogMessage( time = Date(it[0].toLong()), level = LogMessage.Level.valueOf(it[1]), message = it[2] ) } .toList() } } ================================================ FILE: app/src/main/java/yos/clash/material/log/LogcatWriter.kt ================================================ package yos.clash.material.log import android.content.Context import com.github.kr328.clash.core.model.LogMessage import yos.clash.material.design.model.LogFile import yos.clash.material.util.logsDir import java.io.BufferedWriter import java.io.FileWriter class LogcatWriter(context: Context) : AutoCloseable { private val file = LogFile.generate() private val writer = BufferedWriter(FileWriter(context.logsDir.resolve(file.fileName))) override fun close() { writer.close() } fun appendMessage(message: LogMessage) { writer.appendLine(FORMAT.format(message.time.time, message.level.name, message.message)) } companion object { private const val FORMAT = "%d:%s:%s" } } ================================================ FILE: app/src/main/java/yos/clash/material/log/SystemLogcat.kt ================================================ package yos.clash.material.log object SystemLogcat { private val command = arrayOf( "logcat", "-d", "-s", "Go", "DEBUG", "AndroidRuntime", "ClashForAndroid", "LwIP", ) fun dumpCrash(): String { return try { val process = Runtime.getRuntime().exec(command) val result = process.inputStream.use { stream -> stream.reader().readLines() .filterNot { it.startsWith("------") } .joinToString("\n") } process.waitFor() result.trim() } catch (e: Exception) { "" } } } ================================================ FILE: app/src/main/java/yos/clash/material/remote/Broadcasts.kt ================================================ package yos.clash.material.remote import android.app.Application import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import yos.clash.material.common.constants.Intents import yos.clash.material.common.log.Log class Broadcasts(private val context: Application) { interface Observer { fun onServiceRecreated() fun onStarted() fun onStopped(cause: String?) fun onProfileChanged() fun onProfileLoaded() } var clashRunning: Boolean = false private var registered = false private val receivers = mutableListOf() private val broadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.`package` != context?.packageName) return when (intent?.action) { Intents.ACTION_SERVICE_RECREATED -> { clashRunning = false receivers.forEach { it.onServiceRecreated() } } Intents.ACTION_CLASH_STARTED -> { clashRunning = true receivers.forEach { it.onStarted() } } Intents.ACTION_CLASH_STOPPED -> { clashRunning = false receivers.forEach { it.onStopped(intent.getStringExtra(Intents.EXTRA_STOP_REASON)) } } Intents.ACTION_PROFILE_CHANGED -> receivers.forEach { it.onProfileChanged() } Intents.ACTION_PROFILE_LOADED -> { receivers.forEach { it.onProfileLoaded() } } } } } fun addObserver(observer: Observer) { receivers.add(observer) } fun removeObserver(observer: Observer) { receivers.remove(observer) } fun register() { if (registered) return try { context.registerReceiver(broadcastReceiver, IntentFilter().apply { addAction(Intents.ACTION_SERVICE_RECREATED) addAction(Intents.ACTION_CLASH_STARTED) addAction(Intents.ACTION_CLASH_STOPPED) addAction(Intents.ACTION_PROFILE_CHANGED) addAction(Intents.ACTION_PROFILE_LOADED) }) clashRunning = StatusClient(context).currentProfile() != null } catch (e: Exception) { Log.w("Register global receiver: $e", e) } } fun unregister() { if (!registered) return try { context.unregisterReceiver(broadcastReceiver) clashRunning = false } catch (e: Exception) { Log.w("Unregister global receiver: $e", e) } } } ================================================ FILE: app/src/main/java/yos/clash/material/remote/FilesClient.kt ================================================ @file:Suppress("BlockingMethodInNonBlockingContext") package yos.clash.material.remote import android.content.Context import android.net.Uri import yos.clash.material.common.constants.Authorities import yos.clash.material.design.model.File import yos.clash.material.util.copyContentTo import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import android.provider.DocumentsContract as DC class FilesClient(private val context: Context) { suspend fun list(parentDocumentId: String): List = withContext(Dispatchers.IO) { val uri = DC.buildChildDocumentsUri(Authorities.FILES_PROVIDER, parentDocumentId) context.contentResolver.query(uri, FilesProjection, null, null, null)?.use { cursor -> val idIndex = cursor.getColumnIndex(DC.Document.COLUMN_DOCUMENT_ID) val nameIndex = cursor.getColumnIndex(DC.Document.COLUMN_DISPLAY_NAME) val sizeIndex = cursor.getColumnIndex(DC.Document.COLUMN_SIZE) val lastModified = cursor.getColumnIndex(DC.Document.COLUMN_LAST_MODIFIED) val mimeTypeIndex = cursor.getColumnIndex(DC.Document.COLUMN_MIME_TYPE) cursor.moveToFirst() List(cursor.count) { File( id = cursor.getString(idIndex), name = cursor.getString(nameIndex), size = cursor.getLong(sizeIndex), lastModified = cursor.getLong(lastModified), isDirectory = cursor.getString(mimeTypeIndex) == DC.Document.MIME_TYPE_DIR, ).also { cursor.moveToNext() } }.sortedWith(compareBy({ !it.isDirectory }, { it.name })) } ?: emptyList() } suspend fun renameDocument(documentId: String, name: String) = withContext(Dispatchers.IO) { val uri = buildDocumentUri(documentId) DC.renameDocument(context.contentResolver, uri, name) } suspend fun deleteDocument(documentId: String) = withContext(Dispatchers.IO) { val uri = buildDocumentUri(documentId) DC.deleteDocument(context.contentResolver, uri) } suspend fun importDocument( parentDocumentId: String, source: Uri, name: String ) = withContext(Dispatchers.IO) { val target = buildDocumentUri("$parentDocumentId/$name") context.contentResolver.copyContentTo(source, target) } suspend fun copyDocument( documentId: String, source: Uri ) { val target = buildDocumentUri(documentId) context.contentResolver.copyContentTo(source, target) } suspend fun copyDocument( target: Uri, documentId: String ) { val source = buildDocumentUri(documentId) context.contentResolver.copyContentTo(source, target) } fun buildDocumentUri(documentId: String): Uri { return DC.buildDocumentUri(Authorities.FILES_PROVIDER, documentId) } companion object { private val FilesProjection = arrayOf( DC.Document.COLUMN_DOCUMENT_ID, DC.Document.COLUMN_DISPLAY_NAME, DC.Document.COLUMN_SIZE, DC.Document.COLUMN_LAST_MODIFIED, DC.Document.COLUMN_MIME_TYPE, ) } } ================================================ FILE: app/src/main/java/yos/clash/material/remote/Remote.kt ================================================ package yos.clash.material.remote import android.content.Context import android.content.Intent import yos.clash.material.ApkBrokenActivity import yos.clash.material.AppCrashedActivity import yos.clash.material.common.Global import yos.clash.material.common.util.intent import yos.clash.material.store.AppStore import yos.clash.material.util.ApplicationObserver import yos.clash.material.util.verifyApk import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch object Remote { val broadcasts: Broadcasts = Broadcasts(Global.application) val service: Service = Service(Global.application) { ApplicationObserver.createdActivities.forEach { it.finish() } val intent = AppCrashedActivity::class.intent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) Global.application.startActivity(intent) } private val visible = Channel(Channel.CONFLATED) fun launch() { ApplicationObserver.attach(Global.application) ApplicationObserver.onVisibleChanged { visible.trySend(it) } Global.launch(Dispatchers.IO) { run() } } private suspend fun run() { val context = Global.application val store = AppStore(context) val updatedAt = getLastUpdated(context) if (store.updatedAt != updatedAt) { if (!context.verifyApk()) { ApplicationObserver.createdActivities.forEach { it.finish() } val intent = ApkBrokenActivity::class.intent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) return context.startActivity(intent) } else { store.updatedAt = updatedAt } } while (true) { if (visible.receive()) { service.bind() broadcasts.register() } else { service.unbind() broadcasts.unregister() } } } private fun getLastUpdated(context: Context): Long { return context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime } } ================================================ FILE: app/src/main/java/yos/clash/material/remote/Resource.kt ================================================ package yos.clash.material.remote import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume class Resource { private interface Callback { fun accept(value: T) } private val pending: MutableSet> = mutableSetOf() private var value: T? = null suspend fun get(): T { return suspendCancellableCoroutine { ctx -> val callback = object : Callback { override fun accept(value: T) { ctx.resume(value) } } ctx.invokeOnCancellation { cancel(callback) } get(callback) } } fun set(v: T?) { setAndNotify(v) } fun reset(v: T) { resetIfMatched(v) } @Synchronized private fun get(callback: Callback) { val v = value if (v == null) { pending.add(callback) } else { callback.accept(v) } } @Synchronized private fun setAndNotify(value: T?) { this.value = value if (value != null) { pending.forEach { it.accept(value) } pending.clear() } } @Synchronized private fun resetIfMatched(value: T) { if (this.value === value) { this.value = null } } @Synchronized private fun cancel(callback: Callback) { pending.remove(callback) } } ================================================ FILE: app/src/main/java/yos/clash/material/remote/Service.kt ================================================ package yos.clash.material.remote import android.app.Application import android.content.ComponentName import android.content.Context import android.content.ServiceConnection import android.os.IBinder import yos.clash.material.common.log.Log import yos.clash.material.common.util.intent import yos.clash.material.service.RemoteService import yos.clash.material.service.remote.IRemoteService import yos.clash.material.service.remote.unwrap import yos.clash.material.util.unbindServiceSilent import java.util.concurrent.TimeUnit class Service(private val context: Application, val crashed: () -> Unit) { val remote = Resource() private val connection = object : ServiceConnection { private var lastCrashed: Long = -1 override fun onServiceConnected(name: ComponentName?, service: IBinder) { remote.set(service.unwrap(IRemoteService::class)) } override fun onServiceDisconnected(name: ComponentName?) { remote.set(null) if (System.currentTimeMillis() - lastCrashed < TOGGLE_CRASHED_INTERVAL) { unbind() crashed() } lastCrashed = System.currentTimeMillis() Log.w("RemoteManager crashed") } } fun bind() { try { context.bindService(RemoteService::class.intent, connection, Context.BIND_AUTO_CREATE) } catch (e: Exception) { unbind() crashed() } } fun unbind() { context.unbindServiceSilent(connection) remote.set(null) } companion object { private val TOGGLE_CRASHED_INTERVAL = TimeUnit.SECONDS.toMillis(10) } } ================================================ FILE: app/src/main/java/yos/clash/material/remote/StatusClient.kt ================================================ package yos.clash.material.remote import android.content.Context import android.net.Uri import yos.clash.material.common.constants.Authorities import yos.clash.material.common.log.Log import yos.clash.material.service.StatusProvider class StatusClient(private val context: Context) { private val uri: Uri get() { return Uri.Builder() .scheme("content") .authority(Authorities.STATUS_PROVIDER) .build() } fun currentProfile(): String? { return try { val result = context.contentResolver.call( uri, StatusProvider.METHOD_CURRENT_PROFILE, null, null ) result?.getString("name") } catch (e: Exception) { Log.w("Query current profile: $e", e) null } } } ================================================ FILE: app/src/main/java/yos/clash/material/store/AppStore.kt ================================================ package yos.clash.material.store import android.content.Context import yos.clash.material.common.store.Store import yos.clash.material.common.store.asStoreProvider class AppStore(context: Context) { private val store = Store( context .getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) .asStoreProvider() ) var updatedAt: Long by store.long( key = "updated_at", defaultValue = -1, ) companion object { private const val FILE_NAME = "app" } } ================================================ FILE: app/src/main/java/yos/clash/material/store/TipsStore.kt ================================================ package yos.clash.material.store import android.content.Context import yos.clash.material.common.store.Store import yos.clash.material.common.store.asStoreProvider class TipsStore(context: Context) { private val store = Store( context .getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) .asStoreProvider() ) var requestDonate: Boolean by store.boolean( key = "request_donate", defaultValue = true, ) var primaryVersion: Int by store.int( key = "primary_version", defaultValue = -1, ) companion object { const val CURRENT_PRIMARY_VERSION = 1 private const val FILE_NAME = "tips" } } ================================================ FILE: app/src/main/java/yos/clash/material/util/Activity.kt ================================================ @file:Suppress("LeakingThis") package yos.clash.material.util import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.withContext class ActivityResultLifecycle : LifecycleOwner { private val lifecycle = LifecycleRegistry(this) init { lifecycle.currentState = Lifecycle.State.INITIALIZED } /*override fun getLifecycle(): Lifecycle { return lifecycle }*/ suspend fun use(block: suspend (lifecycle: ActivityResultLifecycle, start: () -> Unit) -> T): T { return try { markCreated() block(this, this::markStarted) } finally { withContext(NonCancellable) { markDestroy() } } } private fun markCreated() { lifecycle.currentState = Lifecycle.State.CREATED } private fun markStarted() { lifecycle.currentState = Lifecycle.State.STARTED lifecycle.currentState = Lifecycle.State.RESUMED } private fun markDestroy() { lifecycle.currentState = Lifecycle.State.DESTROYED } override fun getLifecycle(): Lifecycle { return lifecycle } } ================================================ FILE: app/src/main/java/yos/clash/material/util/Application.kt ================================================ package yos.clash.material.util import android.app.Activity import android.app.Application import android.content.Context import android.os.Build import android.os.Bundle import java.io.File import java.util.zip.ZipFile object ApplicationObserver { private val activities: MutableSet = mutableSetOf() private var visibleChanged: (Boolean) -> Unit = {} private var appVisible = false private set(value) { if (field != value) { field = value visibleChanged(value) } } val createdActivities: Set get() = activities private val activityObserver = object : Application.ActivityLifecycleCallbacks { @Synchronized override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { activities.add(activity) appVisible = true } @Synchronized override fun onActivityDestroyed(activity: Activity) { activities.remove(activity) appVisible = activities.isNotEmpty() } override fun onActivityStarted(activity: Activity) {} override fun onActivityStopped(activity: Activity) {} override fun onActivityPaused(activity: Activity) {} override fun onActivityResumed(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} } fun onVisibleChanged(visibleChanged: (Boolean) -> Unit) { ApplicationObserver.visibleChanged = visibleChanged } fun attach(application: Application) { application.registerActivityLifecycleCallbacks(activityObserver) } } fun Context.verifyApk(): Boolean { return try { val info = applicationInfo val sources = info.splitSourceDirs ?: arrayOf(info.sourceDir) ?: return false val regexNativeLibrary = Regex("lib/(\\S+)/libclash.so") val availableAbi = Build.SUPPORTED_ABIS.toSet() val apkAbi = sources .asSequence() .filter { File(it).exists() } .flatMap { ZipFile(it).entries().asSequence() } .mapNotNull { regexNativeLibrary.matchEntire(it.name) } .mapNotNull { it.groups[1]?.value } .toSet() availableAbi.intersect(apkAbi).isNotEmpty() } catch (e: Exception) { false } } ================================================ FILE: app/src/main/java/yos/clash/material/util/Clash.kt ================================================ package yos.clash.material.util import android.content.Context import android.content.Intent import android.net.VpnService import yos.clash.material.common.compat.startForegroundServiceCompat import yos.clash.material.common.constants.Intents import yos.clash.material.common.util.intent import yos.clash.material.design.store.UiStore import yos.clash.material.service.ClashService import yos.clash.material.service.TunService import yos.clash.material.service.util.sendBroadcastSelf fun Context.startClashService(): Intent? { val startTun = UiStore(this).enableVpn if (startTun) { val vpnRequest = VpnService.prepare(this) if (vpnRequest != null) return vpnRequest startForegroundServiceCompat(TunService::class.intent) } else { startForegroundServiceCompat(ClashService::class.intent) } return null } fun Context.stopClashService() { sendBroadcastSelf(Intent(Intents.ACTION_CLASH_REQUEST_STOP)) } ================================================ FILE: app/src/main/java/yos/clash/material/util/Content.kt ================================================ package yos.clash.material.util import android.content.ContentResolver import android.net.Uri import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.FileNotFoundException private fun fileNotFound(file: Uri): FileNotFoundException { return FileNotFoundException("$file not found") } @Suppress("BlockingMethodInNonBlockingContext") suspend fun ContentResolver.copyContentTo( source: Uri, target: Uri ) { withContext(Dispatchers.IO) { (openInputStream(source) ?: throw fileNotFound(source)).use { input -> (openOutputStream(target, "rwt") ?: throw fileNotFound(target)).use { output -> input.copyTo(output) } } } } ================================================ FILE: app/src/main/java/yos/clash/material/util/Files.kt ================================================ package yos.clash.material.util import android.content.Context import java.io.File val Context.logsDir: File get() = cacheDir.resolve("logs") ================================================ FILE: app/src/main/java/yos/clash/material/util/Remote.kt ================================================ package yos.clash.material.util import android.os.DeadObjectException import yos.clash.material.common.log.Log import yos.clash.material.remote.Remote import yos.clash.material.service.remote.IClashManager import yos.clash.material.service.remote.IProfileManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlin.coroutines.CoroutineContext suspend fun withClash( context: CoroutineContext = Dispatchers.IO, block: suspend IClashManager.() -> T ): T { while (true) { val remote = Remote.service.remote.get() val client = remote.clash() try { return withContext(context) { client.block() } } catch (e: DeadObjectException) { Log.w("Remote services panic") Remote.service.remote.reset(remote) } } } suspend fun withProfile( context: CoroutineContext = Dispatchers.IO, block: suspend IProfileManager.() -> T ): T { while (true) { val remote = Remote.service.remote.get() val client = remote.profile() try { return withContext(context) { client.block() } } catch (e: DeadObjectException) { Log.w("Remote services panic") Remote.service.remote.reset(remote) } } } ================================================ FILE: app/src/main/java/yos/clash/material/util/Service.kt ================================================ package yos.clash.material.util import android.content.Context import android.content.ServiceConnection fun Context.unbindServiceSilent(connection: ServiceConnection) { try { unbindService(connection) } catch (e: Exception) { // ignore } } ================================================ FILE: app/src/main/java/yos/clash/material/util/Uri.kt ================================================ package yos.clash.material.util import android.net.Uri val Uri.fileName: String? get() = schemeSpecificPart.split("/").lastOrNull() ================================================ FILE: app/src/main/res/drawable/ic_launcher_foreground.xml ================================================ ================================================ FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml ================================================ ================================================ FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml ================================================ ================================================ FILE: app/src/main/res/values/colors.xml ================================================ #FFFFFF ================================================ FILE: app/src/main/res/values/ids.xml ================================================ ================================================ FILE: app/src/main/res/values/themes.xml ================================================ ================================================ FILE: app/src/main/res/values-night/themes.xml ================================================ ================================================ FILE: app/src/main/res/xml/full_backup_content.xml ================================================ ================================================ FILE: app/src/main/res/xml/network_security_config.xml ================================================ ================================================ FILE: build.gradle.kts ================================================ @file:Suppress("UNUSED_VARIABLE") import com.android.build.gradle.AppExtension import com.android.build.gradle.BaseExtension import java.net.URL import java.util.* buildscript { repositories { mavenLocal() mavenCentral() gradlePluginPortal() google() maven("https://jitpack.io") maven("https://oss.sonatype.org/content/repositories/snapshots/") maven("https://maven.kr328.app/releases") } dependencies { classpath(libs.build.android) classpath(libs.build.kotlin.common) classpath(libs.build.kotlin.serialization) classpath(libs.build.ksp) classpath(libs.build.golang) } } subprojects { repositories { mavenCentral() google() maven("https://maven.kr328.app/releases") } val isApp = name == "app" apply(plugin = if (isApp) "com.android.application" else "com.android.library") extensions.configure { defaultConfig { if (isApp) { applicationId = "yos.clash.material" } minSdk = 21 targetSdk = 34 versionName = "0.1.2" versionCode = 3 resValue("string", "release_name", "v$versionName") resValue("integer", "release_code", "$versionCode") externalNativeBuild { cmake { abiFilters("arm64-v8a", "armeabi-v7a", "x86", "x86_64") } } if (!isApp) { consumerProguardFiles("consumer-rules.pro") } else { setProperty("archivesBaseName", "clash-you-${versionName}-yosx") } } ndkVersion = "23.0.7599858" compileSdkVersion(defaultConfig.targetSdk!!) if (isApp) { packagingOptions { resources { excludes.add("DebugProbesKt.bin") } } } productFlavors { flavorDimensions("feature") /*create("foss") { isDefault = true dimension = flavorDimensionList[0] versionNameSuffix = ".foss" buildConfigField("boolean", "PREMIUM", "Boolean.parseBoolean(\"false\")") if (isApp) { applicationIdSuffix = ".foss" } }*/ create("foss") { dimension = flavorDimensionList[0] versionNameSuffix = "" buildConfigField("boolean", "PREMIUM", "Boolean.parseBoolean(\"true\")") } create("premium") { dimension = flavorDimensionList[0] versionNameSuffix = ".premium" buildConfigField("boolean", "PREMIUM", "Boolean.parseBoolean(\"true\")") } } signingConfigs { val keystore = rootProject.file("signing.properties") if (keystore.exists()) { create("release") { val prop = Properties().apply { keystore.inputStream().use(this::load) } storeFile = rootProject.file(prop.getProperty("keystore.path")!!) storePassword = prop.getProperty("keystore.password")!! keyAlias = prop.getProperty("key.alias")!! keyPassword = prop.getProperty("key.password")!! } } } buildTypes { named("release") { isMinifyEnabled = isApp isShrinkResources = isApp signingConfig = signingConfigs.findByName("release") proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } named("debug") { versionNameSuffix = ".debug" } } buildFeatures.apply { dataBinding { isEnabled = name != "hideapi" } } variantFilter { ignore = name.startsWith("premium") && !project(":core") .file("src/premium/golang/clash/go.mod").exists() } if (isApp) { this as AppExtension splits { abi { isEnable = true isUniversalApk = true } } } } } task("clean", type = Delete::class) { delete(rootProject.buildDir) } tasks.wrapper { distributionType = Wrapper.DistributionType.ALL doLast { val sha256 = URL("$distributionUrl.sha256").openStream() .use { it.reader().readText().trim() } file("gradle/wrapper/gradle-wrapper.properties") .appendText("distributionSha256Sum=$sha256") } } ================================================ FILE: common/build.gradle.kts ================================================ plugins { kotlin("android") id("com.android.library") } dependencies { compileOnly(project(":hideapi")) implementation(libs.kotlin.coroutine) implementation(libs.androidx.core) } ================================================ FILE: common/consumer-rules.pro ================================================ ================================================ FILE: common/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: common/src/main/AndroidManifest.xml ================================================ ================================================ FILE: common/src/main/java/yos/clash/material/common/Global.kt ================================================ package yos.clash.material.common import android.app.Application import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel object Global : CoroutineScope by CoroutineScope(Dispatchers.IO) { val application: Application get() = application_ private lateinit var application_: Application fun init(application: Application) { this.application_ = application } fun destroy() { cancel() } } ================================================ FILE: common/src/main/java/yos/clash/material/common/compat/App.kt ================================================ package yos.clash.material.common.compat import android.app.ActivityThread import android.app.Application import android.graphics.drawable.AdaptiveIconDrawable import android.graphics.drawable.Drawable import android.os.Build import yos.clash.material.common.log.Log val Application.currentProcessName: String get() { if (Build.VERSION.SDK_INT >= 28) return Application.getProcessName() return try { ActivityThread.currentProcessName() } catch (throwable: Throwable) { Log.w("Resolve process name: $throwable") packageName } } fun Drawable.foreground(): Drawable { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && this is AdaptiveIconDrawable && this.background == null ) { return this.foreground } return this } ================================================ FILE: common/src/main/java/yos/clash/material/common/compat/Context.kt ================================================ @file:Suppress("DEPRECATION") package yos.clash.material.common.compat import android.content.Context import android.graphics.drawable.Drawable import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat fun Context.getColorCompat(@ColorRes id: Int): Int { return ContextCompat.getColor(this, id) } fun Context.getDrawableCompat(@DrawableRes id: Int): Drawable? { return ContextCompat.getDrawable(this, id) } ================================================ FILE: common/src/main/java/yos/clash/material/common/compat/Html.kt ================================================ @file:Suppress("DEPRECATION") package yos.clash.material.common.compat import android.os.Build import android.text.Html import android.text.Spanned fun fromHtmlCompat(content: String): Spanned { return if (Build.VERSION.SDK_INT >= 24) { Html.fromHtml(content, Html.FROM_HTML_MODE_COMPACT) } else { Html.fromHtml(content) } } ================================================ FILE: common/src/main/java/yos/clash/material/common/compat/Intents.kt ================================================ package yos.clash.material.common.compat import android.app.PendingIntent import android.os.Build fun pendingIntentFlags(flags: Int, mutable: Boolean = false): Int { return if (Build.VERSION.SDK_INT >= 24) { if (Build.VERSION.SDK_INT > 30 && mutable) { flags or PendingIntent.FLAG_MUTABLE } else { flags or PendingIntent.FLAG_IMMUTABLE } } else { flags } } ================================================ FILE: common/src/main/java/yos/clash/material/common/compat/Package.kt ================================================ @file:Suppress("DEPRECATION") package yos.clash.material.common.compat import android.content.pm.PackageInfo val PackageInfo.versionCodeCompat: Long get() { return if (android.os.Build.VERSION.SDK_INT >= 28) { longVersionCode } else { versionCode.toLong() } } ================================================ FILE: common/src/main/java/yos/clash/material/common/compat/Resource.kt ================================================ @file:Suppress("DEPRECATION") package yos.clash.material.common.compat import android.content.res.Configuration import android.os.Build import java.util.* val Configuration.preferredLocale: Locale get() { return if (Build.VERSION.SDK_INT >= 24) { locales[0] } else { locale } } ================================================ FILE: common/src/main/java/yos/clash/material/common/compat/Services.kt ================================================ package yos.clash.material.common.compat import android.content.Context import android.content.Intent import android.os.Build fun Context.startForegroundServiceCompat(intent: Intent) { if (Build.VERSION.SDK_INT >= 26) { startForegroundService(intent) } else { startService(intent) } } ================================================ FILE: common/src/main/java/yos/clash/material/common/compat/UI.kt ================================================ @file:Suppress("DEPRECATION") package yos.clash.material.common.compat import android.annotation.TargetApi import android.os.Build import android.view.View import android.view.View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR import android.view.View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR import android.view.Window import android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS import android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS import android.view.WindowManager var Window.isSystemBarsTranslucentCompat: Boolean get() { throw UnsupportedOperationException("set value only") } set(value) { if (Build.VERSION.SDK_INT >= 30) { setDecorFitsSystemWindows(!value) } else { decorView.systemUiVisibility = if (value) { decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION } else { decorView.systemUiVisibility and (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION).inv() } } if (Build.VERSION.SDK_INT >= 28) { if (value) { attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES } else { attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT } } } var Window.isLightStatusBarsCompat: Boolean get() { throw UnsupportedOperationException("set value only") } @TargetApi(23) set(value) { if (value) { if (Build.VERSION.SDK_INT >= 30) { decorView.windowInsetsController?.apply { setSystemBarsAppearance( APPEARANCE_LIGHT_STATUS_BARS, APPEARANCE_LIGHT_STATUS_BARS ) } } else { decorView.systemUiVisibility = decorView.systemUiVisibility or SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } } else { if (Build.VERSION.SDK_INT >= 30) { decorView.windowInsetsController?.apply { setSystemBarsAppearance( 0, APPEARANCE_LIGHT_STATUS_BARS ) } } else { decorView.systemUiVisibility = decorView.systemUiVisibility and SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() } } } var Window.isLightNavigationBarCompat: Boolean get() { throw UnsupportedOperationException("set value only") } @TargetApi(27) set(value) { if (value) { if (Build.VERSION.SDK_INT >= 30) { decorView.windowInsetsController?.apply { setSystemBarsAppearance( APPEARANCE_LIGHT_NAVIGATION_BARS, APPEARANCE_LIGHT_NAVIGATION_BARS ) } } else { decorView.systemUiVisibility = decorView.systemUiVisibility or SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR } } else { if (Build.VERSION.SDK_INT >= 30) { decorView.windowInsetsController?.apply { setSystemBarsAppearance( 0, APPEARANCE_LIGHT_NAVIGATION_BARS ) } } else { decorView.systemUiVisibility = decorView.systemUiVisibility and SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv() } } } var Window.isAllowForceDarkCompat: Boolean get() { return if (Build.VERSION.SDK_INT >= 29) { decorView.isForceDarkAllowed } else { false } } set(value) { if (Build.VERSION.SDK_INT >= 29) { decorView.isForceDarkAllowed = value } } ================================================ FILE: common/src/main/java/yos/clash/material/common/compat/View.kt ================================================ @file:Suppress("DEPRECATION") package yos.clash.material.common.compat import android.os.Build import android.widget.TextView import androidx.annotation.StyleRes var TextView.textAppearance: Int get() = throw UnsupportedOperationException("set value only") set(@StyleRes value) { if (Build.VERSION.SDK_INT >= 23) { setTextAppearance(value) } else { setTextAppearance(context, value) } } ================================================ FILE: common/src/main/java/yos/clash/material/common/constants/Authorities.kt ================================================ package yos.clash.material.common.constants import yos.clash.material.common.util.packageName object Authorities { val STATUS_PROVIDER = "$packageName.status" val SETTINGS_PROVIDER = "$packageName.settings" val FILES_PROVIDER = "$packageName.files" } ================================================ FILE: common/src/main/java/yos/clash/material/common/constants/Components.kt ================================================ package yos.clash.material.common.constants import android.content.ComponentName import yos.clash.material.common.util.packageName object Components { private const val componentsPackageName = "yos.clash.material" val MAIN_ACTIVITY = ComponentName(packageName, "$componentsPackageName.MainActivity") val PROPERTIES_ACTIVITY = ComponentName(packageName, "$componentsPackageName.PropertiesActivity") } ================================================ FILE: common/src/main/java/yos/clash/material/common/constants/Intents.kt ================================================ package yos.clash.material.common.constants import yos.clash.material.common.util.packageName object Intents { // Public val ACTION_PROVIDE_URL = "$packageName.action.PROVIDE_URL" const val EXTRA_NAME = "name" // Self val ACTION_SERVICE_RECREATED = "$packageName.intent.action.CLASH_RECREATED" val ACTION_CLASH_STARTED = "$packageName.intent.action.CLASH_STARTED" val ACTION_CLASH_STOPPED = "$packageName.intent.action.CLASH_STOPPED" val ACTION_CLASH_REQUEST_STOP = "$packageName.intent.action.CLASH_REQUEST_STOP" val ACTION_PROFILE_CHANGED = "$packageName.intent.action.PROFILE_CHANGED" val ACTION_PROFILE_REQUEST_UPDATE = "$packageName.intent.action.REQUEST_UPDATE" val ACTION_PROFILE_SCHEDULE_UPDATES = "$packageName.intent.action.SCHEDULE_UPDATES" val ACTION_PROFILE_LOADED = "$packageName.intent.action.PROFILE_LOADED" val ACTION_OVERRIDE_CHANGED = "$packageName.intent.action.OVERRIDE_CHANGED" const val EXTRA_STOP_REASON = "stop_reason" const val EXTRA_UUID = "uuid" } ================================================ FILE: common/src/main/java/yos/clash/material/common/constants/Metadata.kt ================================================ package yos.clash.material.common.constants import yos.clash.material.common.util.packageName object Metadata { val GEOIP_FILE_NAME = "$packageName.GEOIP_FILE_NAME" } ================================================ FILE: common/src/main/java/yos/clash/material/common/constants/Permissions.kt ================================================ package yos.clash.material.common.constants import yos.clash.material.common.util.packageName object Permissions { val RECEIVE_SELF_BROADCASTS = "$packageName.permission.RECEIVE_BROADCASTS" } ================================================ FILE: common/src/main/java/yos/clash/material/common/id/UndefinedIds.kt ================================================ package yos.clash.material.common.id object UndefinedIds { private const val PREFIX = 0x14000000 private const val MASK = 0x00FFFFFF private var current: Int = 0 @Synchronized fun next(): Int { current = ((current and MASK) + 1 or PREFIX) return current } } ================================================ FILE: common/src/main/java/yos/clash/material/common/log/Log.kt ================================================ package yos.clash.material.common.log object Log { private const val TAG = "ClashForAndroid" fun i(message: String, throwable: Throwable? = null) = android.util.Log.i(TAG, message, throwable) fun w(message: String, throwable: Throwable? = null) = android.util.Log.w(TAG, message, throwable) fun e(message: String, throwable: Throwable? = null) = android.util.Log.e(TAG, message, throwable) fun d(message: String, throwable: Throwable? = null) = android.util.Log.d(TAG, message, throwable) fun v(message: String, throwable: Throwable? = null) = android.util.Log.v(TAG, message, throwable) fun f(message: String, throwable: Throwable) = android.util.Log.wtf(message, throwable) } ================================================ FILE: common/src/main/java/yos/clash/material/common/store/Providers.kt ================================================ package yos.clash.material.common.store import android.content.SharedPreferences import androidx.core.content.edit class SharedPreferenceProvider(private val preferences: SharedPreferences) : StoreProvider { override fun getInt(key: String, defaultValue: Int): Int { return preferences.getInt(key, defaultValue) } override fun setInt(key: String, value: Int) { preferences.edit { putInt(key, value) } } override fun getLong(key: String, defaultValue: Long): Long { return preferences.getLong(key, defaultValue) } override fun setLong(key: String, value: Long) { preferences.edit { putLong(key, value) } } override fun getString(key: String, defaultValue: String): String { return preferences.getString(key, defaultValue)!! } override fun setString(key: String, value: String) { preferences.edit { putString(key, value) } } override fun getStringSet(key: String, defaultValue: Set): Set { return preferences.getStringSet(key, defaultValue)!! } override fun setStringSet(key: String, value: Set) { preferences.edit { putStringSet(key, value) } } override fun getBoolean(key: String, defaultValue: Boolean): Boolean { return preferences.getBoolean(key, defaultValue) } override fun setBoolean(key: String, value: Boolean) { preferences.edit { putBoolean(key, value) } } } fun SharedPreferences.asStoreProvider(): StoreProvider { return SharedPreferenceProvider(this) } ================================================ FILE: common/src/main/java/yos/clash/material/common/store/Store.kt ================================================ package yos.clash.material.common.store import kotlin.reflect.KProperty class Store(val provider: StoreProvider) { interface Delegate { operator fun getValue(thisRef: Any?, property: KProperty<*>): T operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) } fun int(key: String, defaultValue: Int): Delegate { return object : Delegate { override fun getValue(thisRef: Any?, property: KProperty<*>): Int { return provider.getInt(key, defaultValue) } override fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) { provider.setInt(key, value) } } } fun long(key: String, defaultValue: Long): Delegate { return object : Delegate { override fun getValue(thisRef: Any?, property: KProperty<*>): Long { return provider.getLong(key, defaultValue) } override fun setValue(thisRef: Any?, property: KProperty<*>, value: Long) { provider.setLong(key, value) } } } fun string(key: String, defaultValue: String): Delegate { return object : Delegate { override fun getValue(thisRef: Any?, property: KProperty<*>): String { return provider.getString(key, defaultValue) } override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { provider.setString(key, value) } } } fun stringSet(key: String, defaultValue: Set): Delegate> { return object : Delegate> { override fun getValue(thisRef: Any?, property: KProperty<*>): Set { return provider.getStringSet(key, defaultValue) } override fun setValue(thisRef: Any?, property: KProperty<*>, value: Set) { provider.setStringSet(key, value) } } } fun boolean(key: String, defaultValue: Boolean): Delegate { return object : Delegate { override fun getValue(thisRef: Any?, property: KProperty<*>): Boolean { return provider.getBoolean(key, defaultValue) } override fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) { provider.setBoolean(key, value) } } } fun > enum(key: String, defaultValue: T, values: Array): Delegate { return object : Delegate { override fun getValue(thisRef: Any?, property: KProperty<*>): T { val name = provider.getString(key, defaultValue.name) return values.find { name == it.name } ?: defaultValue } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { provider.setString(key, value.name) } } } fun typedString(key: String, from: (String) -> T?, to: (T?) -> String): Delegate { return object : Delegate { override fun getValue(thisRef: Any?, property: KProperty<*>): T? { val value = provider.getString(key, to(null)) return from(value) } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) { provider.setString(key, to(value)) } } } } ================================================ FILE: common/src/main/java/yos/clash/material/common/store/StoreProvider.kt ================================================ package yos.clash.material.common.store interface StoreProvider { fun getInt(key: String, defaultValue: Int): Int fun setInt(key: String, value: Int) fun getLong(key: String, defaultValue: Long): Long fun setLong(key: String, value: Long) fun getString(key: String, defaultValue: String): String fun setString(key: String, value: String) fun getStringSet(key: String, defaultValue: Set): Set fun setStringSet(key: String, value: Set) fun getBoolean(key: String, defaultValue: Boolean): Boolean fun setBoolean(key: String, value: Boolean) } ================================================ FILE: common/src/main/java/yos/clash/material/common/util/Components.kt ================================================ package yos.clash.material.common.util import android.content.ComponentName import android.content.Intent import yos.clash.material.common.Global import kotlin.reflect.KClass val KClass<*>.componentName: ComponentName get() = ComponentName(Global.application.packageName, this.java.name) val KClass<*>.intent: Intent get() = Intent(Global.application, this.java) ================================================ FILE: common/src/main/java/yos/clash/material/common/util/Global.kt ================================================ package yos.clash.material.common.util import yos.clash.material.common.Global val packageName: String = Global.application.packageName ================================================ FILE: common/src/main/java/yos/clash/material/common/util/Intent.kt ================================================ package yos.clash.material.common.util import android.content.Intent import android.net.Uri import java.util.* fun Intent.grantPermissions(read: Boolean = true, write: Boolean = true): Intent { var flags = 0 if (read) flags = flags or Intent.FLAG_GRANT_READ_URI_PERMISSION if (write) flags = flags or Intent.FLAG_GRANT_WRITE_URI_PERMISSION addFlags(flags) return this } var Intent.fileName: String? get() { return data?.takeIf { it.scheme == "file" }?.schemeSpecificPart } set(value) { data = Uri.fromParts("file", value, null) } var Intent.uuid: UUID? get() { return data?.takeIf { it.scheme == "uuid" }?.schemeSpecificPart?.let(UUID::fromString) } set(value) { data = Uri.fromParts("uuid", value.toString(), null) } fun Intent.setUUID(uuid: UUID): Intent { this.uuid = uuid return this } fun Intent.setFileName(fileName: String): Intent { this.fileName = fileName return this } ================================================ FILE: common/src/main/java/yos/clash/material/common/util/Parcelable.kt ================================================ package yos.clash.material.common.util import android.os.Binder import android.os.Parcel import android.os.Parcelable private class SliceParcelableListBpBinder(val list: List, val flags: Int) : Binder() { override fun onTransact(code: Int, data: Parcel, reply: Parcel?, tFlags: Int): Boolean { when (code) { TRANSACTION_GET_ITEMS -> { reply ?: return false val offset = data.readInt() val chunk = data.readInt() val end = (offset + chunk).coerceAtMost(list.size) reply.writeInt(end - offset) for (i in offset until end) { list[i].writeToParcel(reply, flags) } return true } } return super.onTransact(code, data, reply, flags) } companion object { const val TRANSACTION_GET_ITEMS = 10 } } fun List.writeToParcelSlice(parcel: Parcel, flags: Int) { val bp = SliceParcelableListBpBinder(this, flags) parcel.writeInt(size) parcel.writeStrongBinder(bp) } fun Parcelable.Creator.createListFromParcelSlice( parcel: Parcel, flags: Int, chunk: Int, ): List { val total = parcel.readInt() val remote = parcel.readStrongBinder() val result = ArrayList(total) var offset = 0 while (offset < total) { val data = Parcel.obtain() val reply = Parcel.obtain() try { data.writeInt(offset) data.writeInt(chunk) if (!remote.transact( SliceParcelableListBpBinder.TRANSACTION_GET_ITEMS, data, reply, flags ) ) { break } val size = reply.readInt() repeat(size) { result.add(createFromParcel(reply)) } offset += size if (size == 0) break } finally { data.recycle() reply.recycle() } } return result } ================================================ FILE: common/src/main/java/yos/clash/material/common/util/Patterns.kt ================================================ package yos.clash.material.common.util val PatternFileName = Regex("[^*&%\\n\\r/]+") ================================================ FILE: common/src/main/java/yos/clash/material/common/util/Ticker.kt ================================================ package yos.clash.material.common.util import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch fun CoroutineScope.ticker(period: Long): Channel { val channel = Channel(Channel.RENDEZVOUS) launch { try { while (isActive) { channel.send(System.currentTimeMillis()) delay(period) } } catch (ignored: Exception) { } } return channel } ================================================ FILE: common/src/main/res/values/strings.xml ================================================ Receive Clash You Broadcasts Receive broadcasts of Clash You services ================================================ FILE: common/src/main/res/values-zh/strings.xml ================================================ 接收 Clash You 广播 接收来自 Clash You 内部的广播 ================================================ FILE: common/src/main/res/values-zh-rTW/strings.xml ================================================ 接收 Clash You 廣播 接收來自 Clash You 內部的廣播 ================================================ FILE: core/build.gradle.kts ================================================ import com.github.kr328.golang.GolangBuildTask import com.github.kr328.golang.GolangPlugin import java.io.FileOutputStream import java.net.URL import java.time.Duration plugins { kotlin("android") id("com.android.library") id("kotlinx-serialization") id("golang-android") } val geoipDatabaseUrl = "https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb" val geoipInvalidate = Duration.ofDays(7)!! val geoipOutput = buildDir.resolve("intermediates/golang_blob") val golangSource = file("src/main/golang/native") golang { sourceSets { create("foss") { tags.set(listOf("foss")) srcDir.set(file("src/foss/golang")) } create("premium") { tags.set(listOf("premium", "without_gvisor", "without_system")) srcDir.set(file("src/premium/golang")) } all { fileName.set("libclash.so") packageName.set("cfa/native") } } } android { productFlavors { all { externalNativeBuild { cmake { arguments("-DGO_SOURCE:STRING=${golangSource}") arguments("-DGO_OUTPUT:STRING=${GolangPlugin.outputDirOf(project, null, null)}") arguments("-DFLAVOR_NAME:STRING=$name") } } } } externalNativeBuild { cmake { path = file("src/main/cpp/CMakeLists.txt") } } } dependencies { implementation(project(":common")) implementation(libs.androidx.core) implementation(libs.kotlin.coroutine) implementation(libs.kotlin.serialization.json) } afterEvaluate { tasks.withType(GolangBuildTask::class.java).forEach { it.inputs.dir(golangSource) } } task("downloadGeoipDatabase") { val databaseFile = geoipOutput.resolve("Country.mmdb") val moduleFile = geoipOutput.resolve("go.mod") val sourceFile = geoipOutput.resolve("blob.go") val moduleContent = """ module "cfa/blob" """.trimIndent() val sourceContent = """ package blob import _ "embed" //go:embed Country.mmdb var GeoipDatabase []byte """.trimIndent() outputs.dir(geoipOutput) onlyIf { System.currentTimeMillis() - databaseFile.lastModified() > geoipInvalidate.toMillis() } doLast { geoipOutput.mkdirs() moduleFile.writeText(moduleContent) sourceFile.writeText(sourceContent) URL(geoipDatabaseUrl).openConnection().getInputStream().use { input -> FileOutputStream(databaseFile).use { output -> input.copyTo(output) } } } } afterEvaluate { val downloadTask = tasks["downloadGeoipDatabase"] tasks.forEach { if (it.name.startsWith("externalGolangBuild")) { it.dependsOn(downloadTask) } } } ================================================ FILE: core/consumer-rules.pro ================================================ -keep class kotlinx.coroutines.CompletableDeferred { *; } -keep class kotlin.Unit { *; } -keepattributes *Annotation*, InnerClasses -dontnote kotlinx.serialization.AnnotationsKt # core serialization annotations # kotlinx-serialization-json specific. Add this if you have java.lang.NoClassDefFoundError kotlinx.serialization.json.JsonObjectSerializer -keepclassmembers class kotlinx.serialization.json.** { *** Companion; } -keepclasseswithmembers class kotlinx.serialization.json.** { kotlinx.serialization.KSerializer serializer(...); } ================================================ FILE: core/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: core/src/foss/golang/go.mod ================================================ module foss go 1.18 require cfa v0.0.0 require ( cfa/blob v0.0.0 // indirect github.com/Dreamacro/clash v1.7.1 // indirect github.com/Kr328/tun2socket v0.0.0-20220414050025-d07c78d06d34 // indirect github.com/dlclark/regexp2 v1.4.0 // indirect github.com/gofrs/uuid v4.2.0+incompatible // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/insomniacslk/dhcp v0.0.0-20220504074936-1ca156eafb9f // indirect github.com/kr/pretty v0.1.0 // indirect github.com/miekg/dns v1.1.49 // indirect github.com/oschwald/geoip2-golang v1.7.0 // indirect github.com/oschwald/maxminddb-golang v1.9.0 // indirect github.com/sirupsen/logrus v1.8.1 // indirect github.com/u-root/uio v0.0.0-20210528151154-e40b768296a7 // indirect go.etcd.io/bbolt v1.3.6 // indirect go.uber.org/atomic v1.9.0 // indirect golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e // indirect golang.org/x/mod v0.4.2 // indirect golang.org/x/net v0.0.0-20220617184016-355a448f1bc9 // indirect golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f // indirect golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) replace cfa => ../../main/golang replace github.com/Dreamacro/clash => ./clash replace cfa/blob => ../../../build/intermediates/golang_blob ================================================ FILE: core/src/foss/golang/go.sum ================================================ github.com/Kr328/tun2socket v0.0.0-20220414050025-d07c78d06d34 h1:USCTqih5d1bUXUxWNS9ZD5Tx/lb0jXHEtRIIx/F9dMc= github.com/Kr328/tun2socket v0.0.0-20220414050025-d07c78d06d34/go.mod h1:YR9wK13TgI5ww8iKWm91MHiSoHC7Oz0U4beCCmtXqLw= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E= github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/fanliao/go-promise v0.0.0-20141029170127-1890db352a72/go.mod h1:PjfxuH4FZdUyfMdtBio2lsRr1AKEaVPwelzuHuh8Lqc= github.com/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0= github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/hugelgupf/socketpair v0.0.0-20190730060125-05d35a94e714/go.mod h1:2Goc3h8EklBH5mspfHFxBnEoURQCGzQQH1ga9Myjvis= github.com/insomniacslk/dhcp v0.0.0-20220504074936-1ca156eafb9f h1:l1QCwn715k8nYkj4Ql50rzEog3WnMdrd4YYMMwemxEo= github.com/insomniacslk/dhcp v0.0.0-20220504074936-1ca156eafb9f/go.mod h1:h+MxyHxRg9NH3terB1nfRIUaQEcI0XOVkdR9LNBlp8E= github.com/jsimonetti/rtnetlink v0.0.0-20190606172950-9527aa82566a/go.mod h1:Oz+70psSo5OFh8DBl0Zv2ACw7Esh6pPUphlvZG9x7uw= github.com/jsimonetti/rtnetlink v0.0.0-20200117123717-f846d4f6c1f4/go.mod h1:WGuG/smIU4J/54PblvSbh+xvCZmpJnFgr3ds6Z55XMQ= github.com/jsimonetti/rtnetlink v0.0.0-20201009170750-9c6f07d100c1/go.mod h1:hqoO/u39cqLeBLebZ8fWdE96O7FxrAsRYhnVOdgHxok= github.com/jsimonetti/rtnetlink v0.0.0-20201110080708-d2c240429e6c/go.mod h1:huN4d1phzjhlOsNIjFsw2SVRbwIHj3fJDMEU2SDPTmg= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/mdlayher/ethernet v0.0.0-20190606142754-0394541c37b7/go.mod h1:U6ZQobyTjI/tJyq2HG+i/dfSoFUt8/aZCM+GKtmFk/Y= github.com/mdlayher/netlink v0.0.0-20190409211403-11939a169225/go.mod h1:eQB3mZE4aiYnlUsyGGCOpPETfdQq4Jhsgf1fk3cwQaA= github.com/mdlayher/netlink v1.0.0/go.mod h1:KxeJAFOFLG6AjpyDkQ/iIhxygIUKD+vcwqcnu43w/+M= github.com/mdlayher/netlink v1.1.0/go.mod h1:H4WCitaheIsdF9yOYu8CFmCgQthAPIWZmcKp9uZHgmY= github.com/mdlayher/netlink v1.1.1/go.mod h1:WTYpFb/WTvlRJAyKhZL5/uy69TDDpHHu2VZmb2XgV7o= github.com/mdlayher/raw v0.0.0-20190606142536-fef19f00fc18/go.mod h1:7EpbotpCmVZcu+KCX4g9WaRNuu11uyhiW7+Le1dKawg= github.com/mdlayher/raw v0.0.0-20191009151244-50f2db8cc065/go.mod h1:7EpbotpCmVZcu+KCX4g9WaRNuu11uyhiW7+Le1dKawg= github.com/miekg/dns v1.1.49 h1:qe0mQU3Z/XpFeE+AEBo2rqaS1IPBJ3anmqZ4XiZJVG8= github.com/miekg/dns v1.1.49/go.mod h1:e3IlAVfNqAllflbibAZEWOXOQ+Ynzk/dDozDxY7XnME= github.com/oschwald/geoip2-golang v1.7.0 h1:JW1r5AKi+vv2ujSxjKthySK3jo8w8oKWPyXsw+Qs/S8= github.com/oschwald/geoip2-golang v1.7.0/go.mod h1:mdI/C7iK7NVMcIDDtf4bCKMJ7r0o7UwGeCo9eiitCMQ= github.com/oschwald/maxminddb-golang v1.9.0 h1:tIk4nv6VT9OiPyrnDAfJS1s1xKDQMZOsGojab6EjC1Y= github.com/oschwald/maxminddb-golang v1.9.0/go.mod h1:TK+s/Z2oZq0rSl4PSeAEoP0bgm82Cp5HyvYbt8K3zLY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= github.com/u-root/uio v0.0.0-20210528114334-82958018845c/go.mod h1:LpEX5FO/cB+WF4TYGY1V5qktpaZLkKkSegbr0V4eYXA= github.com/u-root/uio v0.0.0-20210528151154-e40b768296a7 h1:XMAtQHwKjWHIRwg+8Nj/rzUomQY1q6cM3ncA0wP8GU4= github.com/u-root/uio v0.0.0-20210528151154-e40b768296a7/go.mod h1:LpEX5FO/cB+WF4TYGY1V5qktpaZLkKkSegbr0V4eYXA= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.etcd.io/bbolt v1.3.6 h1:/ecaJf0sk1l4l6V4awd65v2C3ILy7MSj+s/x1ADCIMU= go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e h1:T8NU3HyQ8ClP4SEE+KbFlg6n0NhuTsN4MyznaarGsZM= golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190419010253-1f3472d942ba/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191007182048-72f939374954/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220617184016-355a448f1bc9 h1:Yqz/iviulwKwAREEeUd3nbBFn0XuyJqkoft2IlrvOhc= golang.org/x/net v0.0.0-20220617184016-355a448f1bc9/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f h1:Ax0t5p6N38Ga0dThY21weqDEyz2oklo4IvDkpigvkD8= golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190411185658-b44545bcd369/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190418153312-f0ce4c0180be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606122018-79a91cf218c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200923182605-d9f96fdee20d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201009025420-dfb3f7c4e634/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201101102859-da207088b7d1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210525143221-35b2ab0089ea/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c h1:aFV+BgZ4svzjfabn8ERpuB4JI4N6/rdy1iusx77G3oU= golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2 h1:BonxutuHCTL0rBDnZlKjpGIQFTjyUVTexFOdWkB6Fg0= golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= ================================================ FILE: core/src/foss/golang/main.go ================================================ package golang import ( _ "cfa/native/all" ) ================================================ FILE: core/src/main/AndroidManifest.xml ================================================ ================================================ FILE: core/src/main/cpp/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.0) project(clash-bridge C) set(CMAKE_POSITION_INDEPENDENT_CODE on) set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -O3") set(GO_OUTPUT_BASE ${GO_OUTPUT}/${FLAVOR_NAME}) if ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") set(GO_OUTPUT_BASE "${GO_OUTPUT_BASE}Debug") elseif ("${CMAKE_BUILD_TYPE}" STREQUAL "Release") set(GO_OUTPUT_BASE "${GO_OUTPUT_BASE}Release") elseif ("${CMAKE_BUILD_TYPE}" STREQUAL "RelWithDebInfo") set(GO_OUTPUT_BASE "${GO_OUTPUT_BASE}Release") else () message(FATAL_ERROR "Unknown build type ${CMAKE_BUILD_TYPE}") endif () include_directories("${GO_OUTPUT_BASE}/${CMAKE_ANDROID_ARCH_ABI}") include_directories("${GO_SOURCE}") link_directories("${GO_OUTPUT_BASE}/${CMAKE_ANDROID_ARCH_ABI}") add_library(bridge SHARED main.c jni_helper.c bridge_helper.c) target_link_libraries(bridge log clash) ================================================ FILE: core/src/main/cpp/bridge_helper.c ================================================ #include "bridge_helper.h" uint64_t down_scale_traffic(uint64_t value) { if (value > 1042 * 1024 * 1024) return ((value * 100u / 1024u / 1024u / 1024u) & 0x3FFFFFFFu) | (3u << 30u); if (value > 1024 * 1024) return ((value * 100u / 1024u / 1024u) & 0x3FFFFFFFu) | (2u << 30u); if (value > 1024) return ((value * 100u / 1024u) & 0x3FFFFFFFu) | (1u << 30u); return value & 0x3FFFFFFFu; } ================================================ FILE: core/src/main/cpp/bridge_helper.h ================================================ #pragma once #include uint64_t down_scale_traffic(uint64_t value); ================================================ FILE: core/src/main/cpp/jni_helper.c ================================================ #include "jni_helper.h" #include #include static JavaVM *global_vm; static jclass c_string; static jmethodID m_new_string; static jmethodID m_get_bytes; void initialize_jni(JavaVM *vm, JNIEnv *env) { global_vm = vm; c_string = (jclass) new_global(find_class("java/lang/String")); m_new_string = find_method(c_string, "", "([B)V"); m_get_bytes = find_method(c_string, "getBytes", "()[B"); } JavaVM *global_java_vm() { return global_vm; } char *jni_get_string(JNIEnv *env, jstring str) { jbyteArray array = (*env)->CallObjectMethod(env, str, m_get_bytes); int length = (*env)->GetArrayLength(env, array); char *content = (char *) malloc(length + 1); (*env)->GetByteArrayRegion(env, array, 0, length, (jbyte *) content); content[length] = 0; return content; } jstring jni_new_string(JNIEnv *env, const char *str) { int length = strlen(str); jbyteArray array = (*env)->NewByteArray(env, length); (*env)->SetByteArrayRegion(env, array, 0, length, (const jbyte *) str); return (jstring) (*env)->NewObject(env, c_string, m_new_string, array); } int jni_catch_exception(JNIEnv *env) { int result = (*env)->ExceptionCheck(env); if (result) { (*env)->ExceptionDescribe(env); (*env)->ExceptionClear(env); } return result; } void jni_attach_thread(struct _scoped_jni *jni) { JavaVM *vm = global_java_vm(); if ((*vm)->GetEnv(vm, (void **) &jni->env, JNI_VERSION_1_6) == JNI_OK) { jni->require_release = 0; return; } if ((*vm)->AttachCurrentThread(vm, &jni->env, NULL) != JNI_OK) { abort(); } jni->require_release = 1; } void jni_detach_thread(struct _scoped_jni *jni) { JavaVM *vm = global_java_vm(); if (jni->require_release) { (*vm)->DetachCurrentThread(vm); } } void release_string(char **str) { free(*str); } ================================================ FILE: core/src/main/cpp/jni_helper.h ================================================ #pragma once #include #include #include #include #include struct _scoped_jni { JNIEnv *env; int require_release; }; extern void initialize_jni(JavaVM *vm, JNIEnv *env); extern jstring jni_new_string(JNIEnv *env, const char *str); extern char *jni_get_string(JNIEnv *env, jstring str); extern int jni_catch_exception(JNIEnv *env); extern void jni_attach_thread(struct _scoped_jni *jni); extern void jni_detach_thread(struct _scoped_jni *env); extern void release_string(char **str); #define ATTACH_JNI() __attribute__((unused, cleanup(jni_detach_thread))) \ struct _scoped_jni _jni; \ jni_attach_thread(&_jni); \ JNIEnv *env = _jni.env #define scoped_string __attribute__((cleanup(release_string))) char* #define find_class(name) (*env)->FindClass(env, name) #define find_method(cls, name, signature) (*env)->GetMethodID(env, cls, name, signature) #define new_global(obj) (*env)->NewGlobalRef(env, obj) #define del_global(obj) (*env)->DeleteGlobalRef(env, obj) #define get_string(jstr) jni_get_string(env, jstr) #define new_string(cstr) jni_new_string(env, cstr) ================================================ FILE: core/src/main/cpp/main.c ================================================ #include #include #include #include #include "bridge_helper.h" #include "libclash.h" #include "jni_helper.h" #include "trace.h" JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeInit(JNIEnv *env, jobject thiz, jstring home, jstring version_name, jint sdk_version) { TRACE_METHOD(); scoped_string _home = get_string(home); scoped_string _version_name = get_string(version_name); coreInit(_home, _version_name, sdk_version); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeReset(JNIEnv *env, jobject thiz) { TRACE_METHOD(); reset(); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeForceGc(JNIEnv *env, jobject thiz) { TRACE_METHOD(); forceGc(); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeSuspend(JNIEnv *env, jobject thiz, jboolean suspended) { TRACE_METHOD(); suspend((int) suspended); } JNIEXPORT jstring JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeQueryTunnelState(JNIEnv *env, jobject thiz) { TRACE_METHOD(); scoped_string response = queryTunnelState(); return new_string(response); } JNIEXPORT jlong JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeQueryTrafficNow(JNIEnv *env, jobject thiz) { TRACE_METHOD(); uint64_t upload = 0l, download = 0l; queryNow(&upload, &download); return (jlong) (down_scale_traffic(upload) << 32u | down_scale_traffic(download)); } JNIEXPORT jlong JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeQueryTrafficTotal(JNIEnv *env, jobject thiz) { TRACE_METHOD(); uint64_t upload = 0l, download = 0l; queryTotal(&upload, &download); return (jlong) (down_scale_traffic(upload) << 32u | down_scale_traffic(download)); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeNotifyDnsChanged(JNIEnv *env, jobject thiz, jstring dns_list) { TRACE_METHOD(); scoped_string _dns_list = get_string(dns_list); notifyDnsChanged(_dns_list); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeNotifyTimeZoneChanged(JNIEnv *env, jobject thiz, jstring name, jint offset) { TRACE_METHOD(); scoped_string _name = get_string(name); notifyTimeZoneChanged(_name, offset); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeNotifyInstalledAppChanged(JNIEnv *env, jobject thiz, jstring uid_list) { TRACE_METHOD(); scoped_string _uid_list = get_string(uid_list); notifyInstalledAppsChanged(_uid_list); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeStartTun(JNIEnv *env, jobject thiz, jint fd, jstring gateway, jstring portal, jstring dns, jobject cb) { TRACE_METHOD(); scoped_string _gateway = get_string(gateway); scoped_string _portal = get_string(portal); scoped_string _dns = get_string(dns); jobject _interface = new_global(cb); startTun(fd, _gateway, _portal, _dns, _interface); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeStopTun(JNIEnv *env, jobject thiz) { TRACE_METHOD(); stopTun(); } JNIEXPORT jstring JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeStartHttp(JNIEnv *env, jobject thiz, jstring listen_at) { TRACE_METHOD(); scoped_string _listen_at = get_string(listen_at); scoped_string listened = startHttp(_listen_at); if (listened == NULL) return NULL; return new_string(listened); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeStopHttp(JNIEnv *env, jobject thiz) { TRACE_METHOD(); stopHttp(); } JNIEXPORT jstring JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeQueryGroupNames(JNIEnv *env, jobject thiz, jboolean exclude_not_selectable) { TRACE_METHOD(); scoped_string response = queryGroupNames((int) exclude_not_selectable); return new_string(response); } JNIEXPORT jstring JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeQueryGroup(JNIEnv *env, jobject thiz, jstring name, jstring mode) { TRACE_METHOD(); scoped_string _name = get_string(name); scoped_string _mode = get_string(mode); scoped_string response = queryGroup(_name, _mode); if (response == NULL) return NULL; return new_string(response); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeHealthCheck(JNIEnv *env, jobject thiz, jobject completable, jstring name) { TRACE_METHOD(); jobject _completable = new_global(completable); scoped_string _name = get_string(name); healthCheck(_completable, _name); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeHealthCheckAll(JNIEnv *env, jobject thiz) { TRACE_METHOD(); healthCheckAll(); } JNIEXPORT jboolean JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativePatchSelector(JNIEnv *env, jobject thiz, jstring selector, jstring name) { TRACE_METHOD(); scoped_string _selector = get_string(selector); scoped_string _name = get_string(name); return (jboolean) patchSelector(_selector, _name); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeLoad(JNIEnv *env, jobject thiz, jobject completable, jstring path) { TRACE_METHOD(); jobject _completable = new_global(completable); scoped_string _path = get_string(path); load(_completable, _path); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeFetchAndValid(JNIEnv *env, jobject thiz, jobject callback, jstring path, jstring url, jboolean force) { TRACE_METHOD(); jobject _completable = new_global(callback); scoped_string _path = get_string(path); scoped_string _url = get_string(url); fetchAndValid(_completable, _path, _url, force); } JNIEXPORT jstring JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeQueryProviders(JNIEnv *env, jobject thiz) { TRACE_METHOD(); scoped_string response = queryProviders(); return new_string(response); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeUpdateProvider(JNIEnv *env, jobject thiz, jobject completable, jstring type, jstring name) { TRACE_METHOD(); jobject _completable = new_global(completable); scoped_string _type = get_string(type); scoped_string _name = get_string(name); updateProvider(_completable, _type, _name); } JNIEXPORT jstring JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeReadOverride(JNIEnv *env, jobject thiz, jint slot) { TRACE_METHOD(); scoped_string response = readOverride(slot); return new_string(response); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeWriteOverride(JNIEnv *env, jobject thiz, jint slot, jstring content) { TRACE_METHOD(); scoped_string _content = get_string(content); writeOverride(slot, _content); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeClearOverride(JNIEnv *env, jobject thiz, jint slot) { TRACE_METHOD(); clearOverride(slot); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeInstallSideloadGeoip(JNIEnv *env, jobject thiz, jbyteArray data) { TRACE_METHOD(); if (data == NULL) { installSideloadGeoip(NULL, 0); return; } jbyte *bytes = (*env)->GetByteArrayElements(env, data, NULL); int size = (*env)->GetArrayLength(env, data); scoped_string err = installSideloadGeoip(bytes, size); (*env)->ReleaseByteArrayElements(env, data, bytes, JNI_ABORT); if (err != NULL) { (*env)->ThrowNew( env, find_class("com/github/kr328/clash/core/bridge/ClashException"), err ); } } JNIEXPORT jstring JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeQueryConfiguration(JNIEnv *env, jobject thiz) { TRACE_METHOD(); scoped_string response = queryConfiguration(); return new_string(response); } JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeSubscribeLogcat(JNIEnv *env, jobject thiz, jobject callback) { TRACE_METHOD(); jobject _callback = new_global(callback); subscribeLogcat(_callback); } static jmethodID m_tun_interface_mark_socket; static jmethodID m_tun_interface_query_socket_uid; static jmethodID m_completable_complete; static jmethodID m_completable_complete_exceptionally; static jmethodID m_logcat_interface_received; static jmethodID m_clash_exception; static jmethodID m_fetch_callback_report; static jmethodID m_fetch_callback_complete; static jmethodID m_open; static jmethodID m_get_message; static jclass c_clash_exception; static jclass c_content; static jobject o_unit; static void call_tun_interface_mark_socket_impl(void *tun_interface, int fd) { TRACE_METHOD(); ATTACH_JNI(); (*env)->CallVoidMethod(env, (jobject) tun_interface, (jmethodID) m_tun_interface_mark_socket, (jint) fd); } static int call_tun_interface_query_socket_uid_impl(void *tun_interface, int protocol, const char *source, const char *target) { TRACE_METHOD(); ATTACH_JNI(); return (*env)->CallIntMethod(env, (jobject) tun_interface, (jmethodID) m_tun_interface_query_socket_uid, (jint) protocol, (jstring) new_string(source), (jstring) new_string(target)); } static void call_completable_complete_impl(void *completable, const char *exception) { TRACE_METHOD(); ATTACH_JNI(); if (exception == NULL) { (*env)->CallBooleanMethod(env, (jobject) completable, (jmethodID) m_completable_complete, (jobject) o_unit); } else { jthrowable _exception = (jthrowable) (*env)->NewObject(env, (jclass) c_clash_exception, (jmethodID) m_clash_exception, (jstring) new_string(exception) ); (*env)->CallBooleanMethod(env, (jobject) completable, (jmethodID) m_completable_complete_exceptionally, (jobject) _exception); } } static void call_fetch_callback_report_impl(void *fetch_callback, const char *status_json) { TRACE_METHOD(); ATTACH_JNI(); jstring _status_json = new_string(status_json); (*env)->CallVoidMethod(env, (jobject) fetch_callback, (jmethodID) m_fetch_callback_report, (jstring) _status_json); } static void call_fetch_callback_complete_impl(void *fetch_callback, const char *error) { TRACE_METHOD(); ATTACH_JNI(); jstring _error = NULL; if (error != NULL) _error = new_string(error); (*env)->CallVoidMethod(env, (jobject) fetch_callback, (jmethodID) m_fetch_callback_complete, (jstring) _error); } static int call_logcat_interface_received_impl(void *callback, const char *payload) { TRACE_METHOD(); ATTACH_JNI(); (*env)->CallVoidMethod(env, (jobject) callback, (jmethodID) m_logcat_interface_received, (jstring) new_string(payload)); if (jni_catch_exception(env)) { return 1; } return 0; } static int open_content_impl(const char *url, char *error, int error_length) { TRACE_METHOD(); ATTACH_JNI(); int fd = (*env)->CallStaticIntMethod(env, c_content, m_open, new_string(url)); if ((*env)->ExceptionCheck(env)) { jthrowable exception = (*env)->ExceptionOccurred(env); (*env)->ExceptionClear(env); jstring message = (jstring) (*env)->CallObjectMethod( env, (jthrowable) exception, (jmethodID) m_get_message ); if (message == NULL) { strncpy(error, "unknown", error_length - 1); } else { scoped_string _message = get_string(message); strncpy(error, _message, error_length - 1); } return -1; } return fd; } static void release_jni_object_impl(void *obj) { TRACE_METHOD(); ATTACH_JNI(); del_global((jobject) obj); } JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { TRACE_METHOD(); JNIEnv *env = NULL; if ((*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6) != JNI_OK) return JNI_ERR; initialize_jni(vm, env); jclass c_tun_interface = find_class("com/github/kr328/clash/core/bridge/TunInterface"); jclass c_completable = find_class("kotlinx/coroutines/CompletableDeferred"); jclass c_fetch_callback = find_class("com/github/kr328/clash/core/bridge/FetchCallback"); jclass c_logcat_interface = find_class("com/github/kr328/clash/core/bridge/LogcatInterface"); jclass _c_clash_exception = find_class("com/github/kr328/clash/core/bridge/ClashException"); jclass _c_content = find_class("com/github/kr328/clash/core/bridge/Content"); jclass c_throwable = find_class("java/lang/Throwable"); jclass c_unit = find_class("kotlin/Unit"); m_tun_interface_mark_socket = find_method(c_tun_interface, "markSocket", "(I)V"); m_tun_interface_query_socket_uid = find_method(c_tun_interface, "querySocketUid", "(ILjava/lang/String;Ljava/lang/String;)I"); m_completable_complete = find_method(c_completable, "complete", "(Ljava/lang/Object;)Z"); m_fetch_callback_report = find_method(c_fetch_callback, "report", "(Ljava/lang/String;)V"); m_fetch_callback_complete = find_method(c_fetch_callback, "complete", "(Ljava/lang/String;)V"); m_completable_complete_exceptionally = find_method(c_completable, "completeExceptionally", "(Ljava/lang/Throwable;)Z"); m_logcat_interface_received = find_method(c_logcat_interface, "received", "(Ljava/lang/String;)V"); m_clash_exception = find_method(_c_clash_exception, "", "(Ljava/lang/String;)V"); m_get_message = find_method(c_throwable, "getMessage", "()Ljava/lang/String;"); m_open = (*env)->GetStaticMethodID(env, _c_content, "open", "(Ljava/lang/String;)I"); o_unit = (*env)->GetStaticObjectField(env, c_unit, (*env)->GetStaticFieldID(env, c_unit, "INSTANCE", "Lkotlin/Unit;")); c_clash_exception = (jclass) new_global(_c_clash_exception); c_content = (jclass) new_global(_c_content); o_unit = new_global(o_unit); mark_socket_func = &call_tun_interface_mark_socket_impl; query_socket_uid_func = &call_tun_interface_query_socket_uid_impl; complete_func = &call_completable_complete_impl; fetch_report_func = &call_fetch_callback_report_impl; fetch_complete_func = &call_fetch_callback_complete_impl; logcat_received_func = &call_logcat_interface_received_impl; open_content_func = &open_content_impl; release_object_func = &release_jni_object_impl; return JNI_VERSION_1_6; } ================================================ FILE: core/src/main/golang/go.mod ================================================ module cfa go 1.18 require ( github.com/Dreamacro/clash v1.7.1 github.com/Kr328/tun2socket v0.0.0-20220414050025-d07c78d06d34 github.com/dlclark/regexp2 v1.4.0 github.com/miekg/dns v1.1.43 github.com/oschwald/geoip2-golang v1.5.0 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c gopkg.in/yaml.v2 v2.4.0 ) require ( github.com/Dreamacro/go-shadowsocks2 v0.1.7 // indirect github.com/gofrs/uuid v4.0.0+incompatible // indirect github.com/gorilla/websocket v1.4.2 // indirect github.com/insomniacslk/dhcp v0.0.0-20210827173440-b95caade3eac // indirect github.com/oschwald/maxminddb-golang v1.8.0 // indirect github.com/sirupsen/logrus v1.8.1 // indirect github.com/u-root/uio v0.0.0-20210528114334-82958018845c // indirect go.uber.org/atomic v1.9.0 // indirect golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 // indirect golang.org/x/net v0.0.0-20210903162142-ad29c8ab022f // indirect golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8 // indirect golang.org/x/text v0.3.6 // indirect ) ================================================ FILE: core/src/main/golang/go.sum ================================================ github.com/Dreamacro/clash v1.7.1 h1:8iYYiyVf7ZAztwoFeTFihs5rI9Jjic0ZKmf05vQxzFU= github.com/Dreamacro/clash v1.7.1/go.mod h1:C9eLMAlDZSLrkdzGQdOHyeldwRjDbcGR2kaL80KdzGw= github.com/Dreamacro/go-shadowsocks2 v0.1.7 h1:8CtbE1HoPPMfrQZGXmlluq6dO2lL31W6WRRE8fabc4Q= github.com/Dreamacro/go-shadowsocks2 v0.1.7/go.mod h1:8p5G4cAj5ZlXwUR+Ww63gfSikr8kvw8uw3TDwLAJpUc= github.com/Kr328/tun2socket v0.0.0-20220414050025-d07c78d06d34 h1:USCTqih5d1bUXUxWNS9ZD5Tx/lb0jXHEtRIIx/F9dMc= github.com/Kr328/tun2socket v0.0.0-20220414050025-d07c78d06d34/go.mod h1:YR9wK13TgI5ww8iKWm91MHiSoHC7Oz0U4beCCmtXqLw= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E= github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/fanliao/go-promise v0.0.0-20141029170127-1890db352a72/go.mod h1:PjfxuH4FZdUyfMdtBio2lsRr1AKEaVPwelzuHuh8Lqc= github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw= github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/hugelgupf/socketpair v0.0.0-20190730060125-05d35a94e714/go.mod h1:2Goc3h8EklBH5mspfHFxBnEoURQCGzQQH1ga9Myjvis= github.com/insomniacslk/dhcp v0.0.0-20210827173440-b95caade3eac h1:IO6EfdRnPhxgKOsk9DbewdtQZHKZKnGlW7QCUttvNys= github.com/insomniacslk/dhcp v0.0.0-20210827173440-b95caade3eac/go.mod h1:h+MxyHxRg9NH3terB1nfRIUaQEcI0XOVkdR9LNBlp8E= github.com/jsimonetti/rtnetlink v0.0.0-20190606172950-9527aa82566a/go.mod h1:Oz+70psSo5OFh8DBl0Zv2ACw7Esh6pPUphlvZG9x7uw= github.com/jsimonetti/rtnetlink v0.0.0-20200117123717-f846d4f6c1f4/go.mod h1:WGuG/smIU4J/54PblvSbh+xvCZmpJnFgr3ds6Z55XMQ= github.com/jsimonetti/rtnetlink v0.0.0-20201009170750-9c6f07d100c1/go.mod h1:hqoO/u39cqLeBLebZ8fWdE96O7FxrAsRYhnVOdgHxok= github.com/jsimonetti/rtnetlink v0.0.0-20201110080708-d2c240429e6c/go.mod h1:huN4d1phzjhlOsNIjFsw2SVRbwIHj3fJDMEU2SDPTmg= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/mdlayher/ethernet v0.0.0-20190606142754-0394541c37b7/go.mod h1:U6ZQobyTjI/tJyq2HG+i/dfSoFUt8/aZCM+GKtmFk/Y= github.com/mdlayher/netlink v0.0.0-20190409211403-11939a169225/go.mod h1:eQB3mZE4aiYnlUsyGGCOpPETfdQq4Jhsgf1fk3cwQaA= github.com/mdlayher/netlink v1.0.0/go.mod h1:KxeJAFOFLG6AjpyDkQ/iIhxygIUKD+vcwqcnu43w/+M= github.com/mdlayher/netlink v1.1.0/go.mod h1:H4WCitaheIsdF9yOYu8CFmCgQthAPIWZmcKp9uZHgmY= github.com/mdlayher/netlink v1.1.1/go.mod h1:WTYpFb/WTvlRJAyKhZL5/uy69TDDpHHu2VZmb2XgV7o= github.com/mdlayher/raw v0.0.0-20190606142536-fef19f00fc18/go.mod h1:7EpbotpCmVZcu+KCX4g9WaRNuu11uyhiW7+Le1dKawg= github.com/mdlayher/raw v0.0.0-20191009151244-50f2db8cc065/go.mod h1:7EpbotpCmVZcu+KCX4g9WaRNuu11uyhiW7+Le1dKawg= github.com/miekg/dns v1.1.43 h1:JKfpVSCB84vrAmHzyrsxB5NAr5kLoMXZArPSw7Qlgyg= github.com/miekg/dns v1.1.43/go.mod h1:+evo5L0630/F6ca/Z9+GAqzhjGyn8/c+TBaOyfEl0V4= github.com/oschwald/geoip2-golang v1.5.0 h1:igg2yQIrrcRccB1ytFXqBfOHCjXWIoMv85lVJ1ONZzw= github.com/oschwald/geoip2-golang v1.5.0/go.mod h1:xdvYt5xQzB8ORWFqPnqMwZpCpgNagttWdoZLlJQzg7s= github.com/oschwald/maxminddb-golang v1.8.0 h1:Uh/DSnGoxsyp/KYbY1AuP0tYEwfs0sCph9p/UMXK/Hk= github.com/oschwald/maxminddb-golang v1.8.0/go.mod h1:RXZtst0N6+FY/3qCNmZMBApR19cdQj43/NM9VkrNAis= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/u-root/uio v0.0.0-20210528114334-82958018845c h1:BFvcl34IGnw8yvJi8hlqLFo9EshRInwWBs2M5fGWzQA= github.com/u-root/uio v0.0.0-20210528114334-82958018845c/go.mod h1:LpEX5FO/cB+WF4TYGY1V5qktpaZLkKkSegbr0V4eYXA= go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210317152858-513c2a44f670/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ= golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190419010253-1f3472d942ba/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191007182048-72f939374954/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210903162142-ad29c8ab022f h1:w6wWR0H+nyVpbSAQbzVEIACVyr/h8l/BEkY6Sokc7Eg= golang.org/x/net v0.0.0-20210903162142-ad29c8ab022f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190411185658-b44545bcd369/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190418153312-f0ce4c0180be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606122018-79a91cf218c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191224085550-c709ea063b76/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201009025420-dfb3f7c4e634/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201101102859-da207088b7d1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210525143221-35b2ab0089ea/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8 h1:OH54vjqzRWmbJ62fjuhxy7AxFFgoHN0/DPc/UrL8cAs= golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= ================================================ FILE: core/src/main/golang/native/all/imports.go ================================================ package all import ( _ "cfa/native/app" _ "cfa/native/common" _ "cfa/native/config" _ "cfa/native/delegate" _ "cfa/native/platform" _ "cfa/native/proxy" _ "cfa/native/tun" _ "cfa/native/tunnel" _ "golang.org/x/sync/semaphore" _ "github.com/Dreamacro/clash/log" ) ================================================ FILE: core/src/main/golang/native/app/app.go ================================================ package app import ( "strconv" "strings" "time" ) var appVersionName string var platformVersion int var installedAppsUid = map[int]string{} func ApplyVersionName(versionName string) { appVersionName = versionName } func ApplyPlatformVersion(version int) { platformVersion = version } func VersionName() string { return appVersionName } func PlatformVersion() int { return platformVersion } func NotifyInstallAppsChanged(uidList string) { uids := map[int]string{} for _, item := range strings.Split(uidList, ",") { kv := strings.Split(item, ":") if len(kv) == 2 { uid, err := strconv.Atoi(kv[0]) if err != nil { continue } uids[uid] = kv[1] } } installedAppsUid = uids } func QueryAppByUid(uid int) string { return installedAppsUid[uid] } func NotifyTimeZoneChanged(name string, offset int) { time.Local = time.FixedZone(name, offset) } ================================================ FILE: core/src/main/golang/native/app/content.go ================================================ package app import ( "errors" "os" "syscall" ) var openContentImpl = func(url string) (int, error) { return -1, errors.New("not implement") } func OpenContent(url string) (*os.File, error) { fd, err := openContentImpl(url) if err != nil { return nil, err } _ = syscall.SetNonblock(fd, true) return os.NewFile(uintptr(fd), "fd"), nil } func ApplyContentContext(openContent func(string) (int, error)) { openContentImpl = openContent } ================================================ FILE: core/src/main/golang/native/app/dns.go ================================================ package app import ( "strings" "github.com/Dreamacro/clash/dns" ) func NotifyDnsChanged(dnsList string) { dL := strings.Split(dnsList, ",") ns := make([]dns.NameServer, 0, len(dnsList)) for _, d := range dL { ns = append(ns, dns.NameServer{Addr: d}) } dns.UpdateSystemDNS(dL) dns.FlushCacheWithDefaultResolver() } ================================================ FILE: core/src/main/golang/native/app/tun.go ================================================ package app import ( "net" "syscall" "cfa/native/platform" ) var markSocketImpl func(fd int) var querySocketUidImpl func(protocol int, source, target string) int func MarkSocket(fd int) { markSocketImpl(fd) } func QuerySocketUid(source, target net.Addr) int { var protocol int switch source.Network() { case "udp", "udp4", "udp6": protocol = syscall.IPPROTO_UDP case "tcp", "tcp4", "tcp6": protocol = syscall.IPPROTO_TCP default: return -1 } if PlatformVersion() < 29 { return platform.QuerySocketUidFromProcFs(source, target) } return querySocketUidImpl(protocol, source.String(), target.String()) } func ApplyTunContext(markSocket func(fd int), querySocketUid func(int, string, string) int) { if markSocket == nil { markSocket = func(fd int) {} } if querySocketUid == nil { querySocketUid = func(int, string, string) int { return -1 } } markSocketImpl = markSocket querySocketUidImpl = querySocketUid } func init() { ApplyTunContext(nil, nil) } ================================================ FILE: core/src/main/golang/native/app/ui.go ================================================ package app import ( "github.com/dlclark/regexp2" "github.com/Dreamacro/clash/log" ) var uiSubtitlePattern *regexp2.Regexp func ApplySubtitlePattern(pattern string) { if pattern == "" { uiSubtitlePattern = nil return } if o := uiSubtitlePattern; o != nil && o.String() == pattern { return } reg, err := regexp2.Compile(pattern, regexp2.IgnoreCase|regexp2.Compiled) if err == nil { uiSubtitlePattern = reg } else { uiSubtitlePattern = nil log.Warnln("Compile ui-subtitle-pattern: %s", err.Error()) } } func SubtitlePattern() *regexp2.Regexp { return uiSubtitlePattern } ================================================ FILE: core/src/main/golang/native/app.go ================================================ package main //#include "bridge.h" import "C" import ( "errors" "unsafe" "cfa/native/app" "github.com/Dreamacro/clash/log" ) func openRemoteContent(url string) (int, error) { u := C.CString(url) e := (*C.char)(C.malloc(1024)) log.Debugln("Open remote url: %s", url) defer C.free(unsafe.Pointer(e)) fd := C.open_content(u, e, 1024) if fd < 0 { return -1, errors.New(C.GoString(e)) } return int(fd), nil } //export notifyDnsChanged func notifyDnsChanged(dnsList C.c_string) { d := C.GoString(dnsList) app.NotifyDnsChanged(d) } //export notifyInstalledAppsChanged func notifyInstalledAppsChanged(uids C.c_string) { u := C.GoString(uids) app.NotifyInstallAppsChanged(u) } //export notifyTimeZoneChanged func notifyTimeZoneChanged(name C.c_string, offset C.int) { app.NotifyTimeZoneChanged(C.GoString(name), int(offset)) } //export queryConfiguration func queryConfiguration() *C.char { response := &struct{}{} return marshalJson(&response) } func init() { app.ApplyContentContext(openRemoteContent) } ================================================ FILE: core/src/main/golang/native/bridge.c ================================================ #include "bridge.h" #include "trace.h" void (*mark_socket_func)(void *tun_interface, int fd); int (*query_socket_uid_func)(void *tun_interface, int protocol, const char *source, const char *target); void (*complete_func)(void *completable, const char *exception); void (*fetch_report_func)(void *fetch_callback, const char *status_json); void (*fetch_complete_func)(void *fetch_callback, const char *error); int (*logcat_received_func)(void *logcat_interface, const char *payload); int (*open_content_func)(const char *url, char *error, int error_length); void (*release_object_func)(void *obj); void mark_socket(void *interface, int fd) { TRACE_METHOD(); mark_socket_func(interface, fd); } int query_socket_uid(void *interface, int protocol, char *source, char *target) { TRACE_METHOD(); int result = query_socket_uid_func(interface, protocol, source, target); free(source); free(target); return result; } void complete(void *obj, char *error) { TRACE_METHOD(); complete_func(obj, error); free(error); } void fetch_complete(void *fetch_callback, char *exception) { TRACE_METHOD(); fetch_complete_func(fetch_callback, exception); free(exception); } void fetch_report(void *fetch_callback, char *json_status) { TRACE_METHOD(); fetch_report_func(fetch_callback, json_status); free(json_status); } int logcat_received(void *logcat_interface, char *payload) { TRACE_METHOD(); int result = logcat_received_func(logcat_interface, payload); free(payload); return result; } int open_content(char *url, char *error, int error_length) { TRACE_METHOD(); int result = open_content_func(url, error, error_length); free(url); return result; } void release_object(void *obj) { TRACE_METHOD(); release_object_func(obj); } void log_info(char *msg) { __android_log_write(ANDROID_LOG_INFO, TAG, msg); free(msg); } void log_error(char *msg) { __android_log_write(ANDROID_LOG_ERROR, TAG, msg); free(msg); } void log_warn(char *msg) { __android_log_write(ANDROID_LOG_WARN, TAG, msg); free(msg); } void log_debug(char *msg) { __android_log_write(ANDROID_LOG_DEBUG, TAG, msg); free(msg); } void log_verbose(char *msg) { __android_log_write(ANDROID_LOG_VERBOSE, TAG, msg); free(msg); } ================================================ FILE: core/src/main/golang/native/bridge.h ================================================ #pragma once #include #include #include #include #define TAG "ClashForAndroid" typedef const char *c_string; extern void (*mark_socket_func)(void *tun_interface, int fd); extern int (*query_socket_uid_func)(void *tun_interface, int protocol, const char *source, const char *target); extern void (*complete_func)(void *completable, const char *exception); extern void (*fetch_report_func)(void *fetch_callback, const char *status_json); extern void (*fetch_complete_func)(void *fetch_callback, const char *error); extern int (*logcat_received_func)(void *logcat_interface, const char *payload); extern void (*release_object_func)(void *obj); extern int (*open_content_func)(const char *url, char *error, int error_length); // cgo extern void mark_socket(void *interface, int fd); extern int query_socket_uid(void *interface, int protocol, char *source, char *target); extern void complete(void *obj, char *error); extern void fetch_complete(void *completable, char *exception); extern void fetch_report(void *fetch_callback, char *status_json); extern int logcat_received(void *logcat_interface, char *payload); extern void release_object(void *obj); extern int open_content(char *url, char *error, int error_length); extern void log_info(char *msg); extern void log_error(char *msg); extern void log_warn(char *msg); extern void log_debug(char *msg); extern void log_verbose(char *msg); ================================================ FILE: core/src/main/golang/native/common/path.go ================================================ package common import "strings" func ResolveAsRoot(path string) string { directories := strings.Split(path, "/") result := make([]string, 0, len(directories)) for _, directory := range directories { switch directory { case "", ".": continue case "..": if len(result) > 0 { result = result[:len(result)-1] } default: result = append(result, directory) } } return strings.Join(result, "/") } ================================================ FILE: core/src/main/golang/native/config/defaults.go ================================================ package config var ( defaultNameServers = []string{ "223.5.5.5", "119.29.29.29", "8.8.4.4", "1.0.0.1", } defaultFakeIPFilter = []string{ // Stun Services "+.stun.*.*", "+.stun.*.*.*", "+.stun.*.*.*.*", "+.stun.*.*.*.*.*", // Google Voices "lens.l.google.com", // Nintendo Switch STUN "*.n.n.srv.nintendo.net", // PlayStation STUN "+.stun.playstation.net", // XBox "xbox.*.*.microsoft.com", "*.*.xboxlive.com", // Microsoft Captive Portal "*.msftncsi.com", "*.msftconnecttest.com", // Bilibili CDN "*.mcdn.bilivideo.cn", // Windows Default LAN WorkGroup "WORKGROUP", } defaultFakeIPRange = "28.0.0.0/8" ) ================================================ FILE: core/src/main/golang/native/config/fetch.go ================================================ package config import ( "encoding/json" "fmt" "io" "net/http" U "net/url" "os" P "path" "runtime" "time" "cfa/native/app" "github.com/Dreamacro/clash/component/dialer" ) type Status struct { Action string `json:"action"` Args []string `json:"args"` Progress int `json:"progress"` MaxProgress int `json:"max"` } var client = &http.Client{ Transport: &http.Transport{ DisableKeepAlives: true, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, DialContext: dialer.DialTunnelContext, }, Timeout: 60 * time.Second, } func openUrl(url string) (io.ReadCloser, error) { request, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return nil, err } request.Header.Set("User-Agent", "ClashForAndroid/"+app.VersionName()) response, err := client.Do(request) if err != nil { return nil, err } return response.Body, nil } func openContent(url string) (io.ReadCloser, error) { return app.OpenContent(url) } func fetch(url *U.URL, file string) error { var reader io.ReadCloser var err error switch url.Scheme { case "http", "https": reader, err = openUrl(url.String()) case "content": reader, err = openContent(url.String()) default: err = fmt.Errorf("unsupported scheme %s of %s", url.Scheme, url) } if err != nil { return err } defer reader.Close() _ = os.MkdirAll(P.Dir(file), 0700) f, err := os.OpenFile(file, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600) if err != nil { return err } defer f.Close() _, err = io.Copy(f, reader) if err != nil { _ = os.Remove(file) } return err } func FetchAndValid( path string, url string, force bool, reportStatus func(string), ) error { configPath := P.Join(path, "config.yaml") if _, err := os.Stat(configPath); os.IsNotExist(err) || force { url, err := U.Parse(url) if err != nil { return err } bytes, _ := json.Marshal(&Status{ Action: "FetchConfiguration", Args: []string{url.Host}, Progress: -1, MaxProgress: -1, }) reportStatus(string(bytes)) if err := fetch(url, configPath); err != nil { return err } } defer runtime.GC() rawCfg, err := UnmarshalAndPatch(path) if err != nil { return err } forEachProviders(rawCfg, func(index int, total int, name string, provider map[string]any) { bytes, _ := json.Marshal(&Status{ Action: "FetchProviders", Args: []string{name}, Progress: index, MaxProgress: total, }) reportStatus(string(bytes)) u, uok := provider["url"] p, pok := provider["path"] if !uok || !pok { return } us, uok := u.(string) ps, pok := p.(string) if !uok || !pok { return } if _, err := os.Stat(ps); err == nil { return } url, err := U.Parse(us) if err != nil { return } _ = fetch(url, ps) }) bytes, _ := json.Marshal(&Status{ Action: "Verifying", Args: []string{}, Progress: 0xffff, MaxProgress: 0xffff, }) reportStatus(string(bytes)) cfg, err := Parse(rawCfg) if err != nil { return err } destroyProviders(cfg) return nil } ================================================ FILE: core/src/main/golang/native/config/load.go ================================================ package config import ( "io/ioutil" P "path" "runtime" "strings" "gopkg.in/yaml.v2" "cfa/native/app" "github.com/Dreamacro/clash/log" "github.com/Dreamacro/clash/config" "github.com/Dreamacro/clash/hub/executor" ) func logDns(cfg *config.RawConfig) { bytes, err := yaml.Marshal(&cfg.DNS) if err != nil { log.Warnln("Marshal dns: %s", err.Error()) return } log.Infoln("dns:") for _, line := range strings.Split(string(bytes), "\n") { log.Infoln(" %s", line) } } func UnmarshalAndPatch(profilePath string) (*config.RawConfig, error) { configPath := P.Join(profilePath, "config.yaml") configData, err := ioutil.ReadFile(configPath) if err != nil { return nil, err } rawConfig, err := config.UnmarshalRawConfig(configData) if err != nil { return nil, err } if err := process(rawConfig, profilePath); err != nil { return nil, err } return rawConfig, nil } func Parse(rawConfig *config.RawConfig) (*config.Config, error) { cfg, err := config.ParseRawConfig(rawConfig) if err != nil { return nil, err } return cfg, nil } func Load(path string) error { rawCfg, err := UnmarshalAndPatch(path) if err != nil { log.Errorln("Load %s: %s", path, err.Error()) return err } logDns(rawCfg) cfg, err := Parse(rawCfg) if err != nil { log.Errorln("Load %s: %s", path, err.Error()) return err } executor.ApplyConfig(cfg, true) app.ApplySubtitlePattern(rawCfg.ClashForAndroid.UiSubtitlePattern) runtime.GC() return nil } func LoadDefault() { cfg, err := config.Parse([]byte{}) if err != nil { panic(err.Error()) } executor.ApplyConfig(cfg, true) } ================================================ FILE: core/src/main/golang/native/config/override.go ================================================ package config import ( "io/ioutil" "os" "github.com/Dreamacro/clash/constant" ) type OverrideSlot int const ( OverrideSlotPersist OverrideSlot = iota OverrideSlotSession ) const defaultPersistOverride = `{"dns":{"enable": false}, "redir-port": 0, "tproxy-port": 0}` const defaultSessionOverride = `{}` var sessionOverride = defaultSessionOverride func overridePersistPath() string { return constant.Path.Resolve("override.json") } func ReadOverride(slot OverrideSlot) string { switch slot { case OverrideSlotPersist: file, err := os.OpenFile(overridePersistPath(), os.O_RDONLY, 0600) if err != nil { return defaultPersistOverride } buf, err := ioutil.ReadAll(file) if err != nil { return defaultPersistOverride } return string(buf) case OverrideSlotSession: return sessionOverride } return "" } func WriteOverride(slot OverrideSlot, content string) { switch slot { case OverrideSlotPersist: file, err := os.OpenFile(overridePersistPath(), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600) if err != nil { return } _, err = file.Write([]byte(content)) case OverrideSlotSession: sessionOverride = content } } func ClearOverride(slot OverrideSlot) { switch slot { case OverrideSlotPersist: _ = os.Remove(overridePersistPath()) case OverrideSlotSession: sessionOverride = defaultSessionOverride } } ================================================ FILE: core/src/main/golang/native/config/process.go ================================================ package config import ( "encoding/json" "errors" "fmt" "strings" "github.com/dlclark/regexp2" "cfa/native/common" C "github.com/Dreamacro/clash/constant" "github.com/Dreamacro/clash/log" "github.com/Dreamacro/clash/config" "github.com/Dreamacro/clash/dns" ) var processors = []processor{ patchOverride, patchGeneral, patchProfile, patchDns, patchProviders, patchTun, validConfig, } type processor func(cfg *config.RawConfig, profileDir string) error func patchOverride(cfg *config.RawConfig, _ string) error { if err := json.NewDecoder(strings.NewReader(ReadOverride(OverrideSlotPersist))).Decode(cfg); err != nil { log.Warnln("Apply persist override: %s", err.Error()) } if err := json.NewDecoder(strings.NewReader(ReadOverride(OverrideSlotSession))).Decode(cfg); err != nil { log.Warnln("Apply session override: %s", err.Error()) } return nil } func patchGeneral(cfg *config.RawConfig, _ string) error { cfg.Interface = "" cfg.ExternalUI = "" cfg.ExternalController = "" return nil } func patchProfile(cfg *config.RawConfig, _ string) error { cfg.Profile.StoreSelected = false cfg.Profile.StoreFakeIP = true return nil } func patchDns(cfg *config.RawConfig, _ string) error { if !cfg.DNS.Enable { cfg.DNS = config.RawDNS{ Enable: true, UseHosts: true, DefaultNameserver: defaultNameServers, NameServer: defaultNameServers, EnhancedMode: C.DNSFakeIP, FakeIPRange: defaultFakeIPRange, FakeIPFilter: defaultFakeIPFilter, } cfg.ClashForAndroid.AppendSystemDNS = true } if cfg.ClashForAndroid.AppendSystemDNS { cfg.DNS.NameServer = append(cfg.DNS.NameServer, "dhcp://"+dns.SystemDNSPlaceholder) } return nil } func patchProviders(cfg *config.RawConfig, profileDir string) error { forEachProviders(cfg, func(index int, total int, key string, provider map[string]any) { if path, ok := provider["path"].(string); ok { provider["path"] = profileDir + "/providers/" + common.ResolveAsRoot(path) } }) return nil } func validConfig(cfg *config.RawConfig, _ string) error { if len(cfg.Proxy) == 0 && len(cfg.ProxyProvider) == 0 { return errors.New("profile does not contain `proxies` or `proxy-providers`") } if _, err := regexp2.Compile(cfg.ClashForAndroid.UiSubtitlePattern, 0); err != nil { return fmt.Errorf("compile ui-subtitle-pattern: %s", err.Error()) } return nil } func process(cfg *config.RawConfig, profileDir string) error { for _, p := range processors { if err := p(cfg, profileDir); err != nil { return err } } return nil } ================================================ FILE: core/src/main/golang/native/config/process_open.go ================================================ //go:build !premium package config import "github.com/Dreamacro/clash/config" func patchTun(cfg *config.RawConfig, _ string) error { return nil } ================================================ FILE: core/src/main/golang/native/config/process_premium.go ================================================ //go:build premium package config import "github.com/Dreamacro/clash/config" func patchTun(cfg *config.RawConfig, _ string) error { cfg.Tun.Enable = false return nil } ================================================ FILE: core/src/main/golang/native/config/provider_open.go ================================================ //go:build !premium package config import ( "io" "github.com/Dreamacro/clash/config" ) func forEachProviders(rawCfg *config.RawConfig, fun func(index int, total int, key string, provider map[string]any)) { total := len(rawCfg.ProxyProvider) index := 0 for k, v := range rawCfg.ProxyProvider { fun(index, total, k, v) index++ } } func destroyProviders(cfg *config.Config) { for _, p := range cfg.Providers { _ = p.(io.Closer).Close() } } ================================================ FILE: core/src/main/golang/native/config/provider_premium.go ================================================ //go:build premium package config import ( "io" "github.com/Dreamacro/clash/config" ) func forEachProviders(rawCfg *config.RawConfig, fun func(index int, total int, key string, provider map[string]any)) { total := len(rawCfg.ProxyProvider) + len(rawCfg.RuleProvider) index := 0 for k, v := range rawCfg.ProxyProvider { fun(index, total, k, v) index++ } for k, v := range rawCfg.RuleProvider { fun(index, total, k, v) index++ } } func destroyProviders(cfg *config.Config) { for _, p := range cfg.ProxyProviders { _ = p.(io.Closer).Close() } for _, p := range cfg.RuleProviders { _ = p.(io.Closer).Close() } } ================================================ FILE: core/src/main/golang/native/config.go ================================================ package main //#include "bridge.h" import "C" import ( "runtime" "unsafe" "cfa/native/config" ) type remoteValidCallback struct { callback unsafe.Pointer } func (r *remoteValidCallback) reportStatus(json string) { C.fetch_report(r.callback, marshalString(json)) } //export fetchAndValid func fetchAndValid(callback unsafe.Pointer, path, url C.c_string, force C.int) { go func(path, url string, callback unsafe.Pointer) { cb := &remoteValidCallback{callback: callback} err := config.FetchAndValid(path, url, force != 0, cb.reportStatus) C.fetch_complete(callback, marshalString(err)) C.release_object(callback) runtime.GC() }(C.GoString(path), C.GoString(url), callback) } //export load func load(completable unsafe.Pointer, path C.c_string) { go func(path string) { C.complete(completable, marshalString(config.Load(path))) C.release_object(completable) runtime.GC() }(C.GoString(path)) } //export readOverride func readOverride(slot C.int) *C.char { return C.CString(config.ReadOverride(config.OverrideSlot(slot))) } //export writeOverride func writeOverride(slot C.int, content C.c_string) { c := C.GoString(content) config.WriteOverride(config.OverrideSlot(slot), c) } //export clearOverride func clearOverride(slot C.int) { config.ClearOverride(config.OverrideSlot(slot)) } ================================================ FILE: core/src/main/golang/native/debug.go ================================================ // +build debug package main import ( "net/http" _ "net/http/pprof" "github.com/Dreamacro/clash/log" ) func init() { go func() { log.Debugln("pprof service listen at: 0.0.0.0:8888") _ = http.ListenAndServe("0.0.0.0:8888", nil) }() } ================================================ FILE: core/src/main/golang/native/delegate/init.go ================================================ package delegate import ( "errors" "syscall" "cfa/blob" "github.com/Dreamacro/clash/component/process" "github.com/Dreamacro/clash/log" "cfa/native/app" "cfa/native/platform" "github.com/Dreamacro/clash/component/dialer" "github.com/Dreamacro/clash/component/mmdb" "github.com/Dreamacro/clash/constant" ) var errBlocked = errors.New("blocked") func Init(home, versionName string, platformVersion int) { mmdb.LoadFromBytes(blob.GeoipDatabase) constant.SetHomeDir(home) app.ApplyVersionName(versionName) app.ApplyPlatformVersion(platformVersion) process.DefaultPackageNameResolver = func(metadata *constant.Metadata) (string, error) { src, dst := metadata.RawSrcAddr, metadata.RawDstAddr if src == nil || dst == nil { return "", process.ErrInvalidNetwork } uid := app.QuerySocketUid(metadata.RawSrcAddr, metadata.RawDstAddr) pkg := app.QueryAppByUid(uid) log.Debugln("[PKG] %s --> %s by %d[%s]", metadata.SourceAddress(), metadata.RemoteAddress(), uid, pkg) return pkg, nil } dialer.DefaultSocketHook = func(network, address string, conn syscall.RawConn) error { if platform.ShouldBlockConnection() { return errBlocked } return conn.Control(func(fd uintptr) { app.MarkSocket(int(fd)) }) } } ================================================ FILE: core/src/main/golang/native/log_open.go ================================================ //go:build !premium package main //#include "bridge.h" import "C" import ( "strings" "time" "unsafe" "github.com/Dreamacro/clash/log" ) type message struct { Level string `json:"level"` Message string `json:"message"` Time int64 `json:"time"` } func init() { go func() { sub := log.Subscribe() defer log.UnSubscribe(sub) for item := range sub { msg := item.(log.Event) cPayload := C.CString(msg.Payload) switch msg.LogLevel { case log.INFO: C.log_info(cPayload) case log.ERROR: C.log_error(cPayload) case log.WARNING: C.log_warn(cPayload) case log.DEBUG: C.log_debug(cPayload) case log.SILENT: C.log_verbose(cPayload) } } }() } //export subscribeLogcat func subscribeLogcat(remote unsafe.Pointer) { go func(remote unsafe.Pointer) { sub := log.Subscribe() defer log.UnSubscribe(sub) for i := range sub { msg, ok := i.(log.Event) if !ok { continue } if msg.LogLevel < log.Level() && !strings.HasPrefix(msg.Payload, "[APP]") { continue } rMsg := &message{ Level: msg.LogLevel.String(), Message: msg.Payload, Time: time.Now().UnixNano() / 1000 / 1000, } if C.logcat_received(remote, marshalJson(rMsg)) != 0 { C.release_object(remote) log.Debugln("Logcat subscriber closed") break } } }(remote) log.Infoln("[APP] Logcat level: %s", log.Level().String()) } ================================================ FILE: core/src/main/golang/native/log_premium.go ================================================ //go:build premium package main //#include "bridge.h" import "C" import ( "strings" "time" "unsafe" "github.com/Dreamacro/clash/log" ) type message struct { Level string `json:"level"` Message string `json:"message"` Time int64 `json:"time"` } func init() { go func() { sub := log.Subscribe() defer log.UnSubscribe(sub) for msg := range sub { cPayload := C.CString(msg.Payload) switch msg.LogLevel { case log.INFO: C.log_info(cPayload) case log.ERROR: C.log_error(cPayload) case log.WARNING: C.log_warn(cPayload) case log.DEBUG: C.log_debug(cPayload) case log.SILENT: C.log_verbose(cPayload) } } }() } //export subscribeLogcat func subscribeLogcat(remote unsafe.Pointer) { go func(remote unsafe.Pointer) { sub := log.Subscribe() defer log.UnSubscribe(sub) for msg := range sub { if msg.LogLevel < log.Level() && !strings.HasPrefix(msg.Payload, "[APP]") { continue } rMsg := &message{ Level: msg.LogLevel.String(), Message: msg.Payload, Time: time.Now().UnixNano() / 1000 / 1000, } if C.logcat_received(remote, marshalJson(rMsg)) != 0 { C.release_object(remote) log.Debugln("Logcat subscriber closed") break } } }(remote) log.Infoln("[APP] Logcat level: %s", log.Level().String()) } ================================================ FILE: core/src/main/golang/native/main.go ================================================ package main /* #cgo LDFLAGS: -llog #include "bridge.h" */ import "C" import ( "runtime" "cfa/native/config" "cfa/native/delegate" "cfa/native/tunnel" "github.com/Dreamacro/clash/log" ) func main() { panic("Stub!") } //export coreInit func coreInit(home, versionName C.c_string, sdkVersion C.int) { h := C.GoString(home) v := C.GoString(versionName) s := int(sdkVersion) delegate.Init(h, v, s) reset() } //export reset func reset() { config.LoadDefault() tunnel.ResetStatistic() tunnel.CloseAllConnections() runtime.GC() } //export forceGc func forceGc() { go func() { log.Infoln("[APP] request force GC") runtime.GC() }() } ================================================ FILE: core/src/main/golang/native/platform/limit.go ================================================ // +build linux package platform import "syscall" var nullFd int var maxFdCount int func init() { fd, err := syscall.Open("/dev/null", syscall.O_WRONLY, 0644) if err != nil { panic(err.Error()) } nullFd = fd var limit syscall.Rlimit if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil { maxFdCount = 1024 } else { maxFdCount = int(limit.Cur) } maxFdCount = maxFdCount / 4 * 3 } func ShouldBlockConnection() bool { fd, err := syscall.Dup(nullFd) if err != nil { return true } _ = syscall.Close(fd) if fd > maxFdCount { return true } return false } ================================================ FILE: core/src/main/golang/native/platform/procfs.go ================================================ // +build linux package platform import ( "bufio" "encoding/binary" "encoding/hex" "fmt" "net" "os" "strconv" "strings" "unsafe" ) var netIndexOfLocal = -1 var netIndexOfUid = -1 var nativeEndian binary.ByteOrder func QuerySocketUidFromProcFs(source, _ net.Addr) int { if netIndexOfLocal < 0 || netIndexOfUid < 0 { return -1 } network := source.Network() if strings.HasSuffix(network, "4") || strings.HasSuffix(network, "6") { network = network[:len(network)-1] } path := "/proc/net/" + network var sIP net.IP var sPort int switch s := source.(type) { case *net.TCPAddr: sIP = s.IP sPort = s.Port case *net.UDPAddr: sIP = s.IP sPort = s.Port default: return -1 } sIP = sIP.To16() if sIP == nil { return -1 } uid := doQuery(path+"6", sIP, sPort) if uid == -1 { sIP = sIP.To4() if sIP == nil { return -1 } uid = doQuery(path, sIP, sPort) } return uid } func doQuery(path string, sIP net.IP, sPort int) int { file, err := os.Open(path) if err != nil { return -1 } defer file.Close() reader := bufio.NewReader(file) var bytes [2]byte binary.BigEndian.PutUint16(bytes[:], uint16(sPort)) local := fmt.Sprintf("%s:%s", hex.EncodeToString(nativeEndianIP(sIP)), hex.EncodeToString(bytes[:])) for { row, _, err := reader.ReadLine() if err != nil { return -1 } fields := strings.Fields(string(row)) if len(fields) <= netIndexOfLocal || len(fields) <= netIndexOfUid { continue } if strings.EqualFold(local, fields[netIndexOfLocal]) { uid, err := strconv.Atoi(fields[netIndexOfUid]) if err != nil { return -1 } return uid } } } func nativeEndianIP(ip net.IP) []byte { result := make([]byte, len(ip)) for i := 0; i < len(ip); i += 4 { value := binary.BigEndian.Uint32(ip[i:]) nativeEndian.PutUint32(result[i:], value) } return result } func init() { file, err := os.Open("/proc/net/tcp") if err != nil { return } defer file.Close() reader := bufio.NewReader(file) header, _, err := reader.ReadLine() if err != nil { return } columns := strings.Fields(string(header)) var txQueue, rxQueue, tr, tmWhen bool for idx, col := range columns { offset := 0 if txQueue && rxQueue { offset-- } if tr && tmWhen { offset-- } switch col { case "tx_queue": txQueue = true case "rx_queue": rxQueue = true case "tr": tr = true case "tm->when": tmWhen = true case "local_address": netIndexOfLocal = idx + offset case "uid": netIndexOfUid = idx + offset } } } func init() { var x uint32 = 0x01020304 if *(*byte)(unsafe.Pointer(&x)) == 0x01 { nativeEndian = binary.BigEndian } else { nativeEndian = binary.LittleEndian } } ================================================ FILE: core/src/main/golang/native/proxy/http.go ================================================ package proxy import ( "sync" "github.com/Dreamacro/clash/listener/http" "github.com/Dreamacro/clash/tunnel" ) var listener *http.Listener var lock sync.Mutex func Start(listen string) (listenAt string, err error) { lock.Lock() defer lock.Unlock() stopLocked() listener, err = http.NewWithAuthenticate(listen, tunnel.TCPIn(), false) if err == nil { listenAt = listener.Listener().Addr().String() } return } func Stop() { lock.Lock() defer lock.Unlock() stopLocked() } func stopLocked() { if listener != nil { listener.Close() } listener = nil } ================================================ FILE: core/src/main/golang/native/proxy.go ================================================ package main //#include "bridge.h" import "C" import ( "cfa/native/proxy" ) //export startHttp func startHttp(listenAt C.c_string) *C.char { l := C.GoString(listenAt) listen, err := proxy.Start(l) if err != nil { return nil } return C.CString(listen) } //export stopHttp func stopHttp() { proxy.Stop() } ================================================ FILE: core/src/main/golang/native/trace.c ================================================ #include "trace.h" #if ENABLE_TRACE void trace_method_exit(const char **name) { __android_log_print(ANDROID_LOG_VERBOSE, TAG, "TRACE-OUT %s", *name); } #endif ================================================ FILE: core/src/main/golang/native/trace.h ================================================ #pragma once #include "bridge.h" #include #define ENABLE_TRACE 0 #if ENABLE_TRACE extern void trace_method_exit(const char **name); #define TRACE_METHOD() __attribute__((cleanup(trace_method_exit))) const char *__method_name = __FUNCTION__; __android_log_print(ANDROID_LOG_VERBOSE, TAG, "TRACE-IN %s", __method_name) #else #define TRACE_METHOD() #endif ================================================ FILE: core/src/main/golang/native/tun/dns.go ================================================ package tun import ( "net" "github.com/Dreamacro/clash/dns" D "github.com/miekg/dns" ) func shouldHijackDns(dns net.IP, target net.IP, targetPort int) bool { if targetPort != 53 { return false } return net.IPv4zero.Equal(dns) || target.Equal(dns) } func relayDns(payload []byte) ([]byte, error) { msg := &D.Msg{} if err := msg.Unpack(payload); err != nil { return nil, err } r, err := dns.ServeDNSWithDefaultServer(msg) if err != nil { return nil, err } r.SetRcode(msg, r.Rcode) return r.Pack() } ================================================ FILE: core/src/main/golang/native/tun/metadata_open.go ================================================ //go:build !premium package tun import ( "net" "strconv" C "github.com/Dreamacro/clash/constant" ) func createMetadata(lAddr, rAddr *net.TCPAddr) *C.Metadata { return &C.Metadata{ NetWork: C.TCP, Type: C.SOCKS5, SrcIP: lAddr.IP, DstIP: rAddr.IP, SrcPort: strconv.Itoa(lAddr.Port), DstPort: strconv.Itoa(rAddr.Port), AddrType: C.AtypIPv4, Host: "", RawSrcAddr: lAddr, RawDstAddr: rAddr, } } ================================================ FILE: core/src/main/golang/native/tun/metadata_premium.go ================================================ //go:build premium package tun import ( "net" "net/netip" "strconv" C "github.com/Dreamacro/clash/constant" ) func createMetadata(lAddr, rAddr *net.TCPAddr) *C.Metadata { srcAddr, _ := netip.AddrFromSlice(lAddr.IP) dstAddr, _ := netip.AddrFromSlice(rAddr.IP) return &C.Metadata{ NetWork: C.TCP, Type: C.SOCKS5, SrcIP: srcAddr, DstIP: dstAddr, SrcPort: strconv.Itoa(lAddr.Port), DstPort: strconv.Itoa(rAddr.Port), AddrType: C.AtypIPv4, Host: "", RawSrcAddr: lAddr, RawDstAddr: rAddr, } } ================================================ FILE: core/src/main/golang/native/tun/tun.go ================================================ package tun import ( "encoding/binary" "io" "net" "os" "time" "github.com/Kr328/tun2socket" "github.com/Dreamacro/clash/adapter/inbound" "github.com/Dreamacro/clash/common/pool" C "github.com/Dreamacro/clash/constant" "github.com/Dreamacro/clash/context" "github.com/Dreamacro/clash/log" "github.com/Dreamacro/clash/transport/socks5" "github.com/Dreamacro/clash/tunnel" ) var _, ipv4LoopBack, _ = net.ParseCIDR("127.0.0.0/8") func Start(fd int, gateway, portal, dns string) (io.Closer, error) { log.Debugln("TUN: fd = %d, gateway = %s, portal = %s, dns = %s", fd, gateway, portal, dns) device := os.NewFile(uintptr(fd), "/dev/tun") ip, network, err := net.ParseCIDR(gateway) if err != nil { panic(err.Error()) } else { network.IP = ip } stack, err := tun2socket.StartTun2Socket(device, network, net.ParseIP(portal)) if err != nil { _ = device.Close() return nil, err } dnsAddr := net.ParseIP(dns) tcp := func() { defer stack.TCP().Close() defer log.Debugln("TCP: closed") for stack.TCP().SetDeadline(time.Time{}) == nil { conn, err := stack.TCP().Accept() if err != nil { log.Debugln("Accept connection: %v", err) continue } lAddr := conn.LocalAddr().(*net.TCPAddr) rAddr := conn.RemoteAddr().(*net.TCPAddr) if ipv4LoopBack.Contains(rAddr.IP) { conn.Close() continue } if shouldHijackDns(dnsAddr, rAddr.IP, rAddr.Port) { go func() { defer conn.Close() buf := pool.Get(pool.UDPBufferSize) defer pool.Put(buf) for { conn.SetReadDeadline(time.Now().Add(C.DefaultTCPTimeout)) length := uint16(0) if err := binary.Read(conn, binary.BigEndian, &length); err != nil { return } if int(length) > len(buf) { return } n, err := conn.Read(buf[:length]) if err != nil { return } msg, err := relayDns(buf[:n]) if err != nil { return } _, _ = conn.Write(msg) } }() continue } tunnel.TCPIn() <- context.NewConnContext(conn, createMetadata(lAddr, rAddr)) } } udp := func() { defer stack.UDP().Close() defer log.Debugln("UDP: closed") for { buf := pool.Get(pool.UDPBufferSize) n, lRAddr, rRAddr, err := stack.UDP().ReadFrom(buf) if err != nil { return } raw := buf[:n] lAddr := lRAddr.(*net.UDPAddr) rAddr := rRAddr.(*net.UDPAddr) if ipv4LoopBack.Contains(rAddr.IP) { pool.Put(buf) continue } if shouldHijackDns(dnsAddr, rAddr.IP, rAddr.Port) { go func() { defer pool.Put(buf) msg, err := relayDns(raw) if err != nil { return } _, _ = stack.UDP().WriteTo(msg, rAddr, lAddr) }() continue } pkt := &packet{ local: lAddr, data: raw, writeBack: func(b []byte, addr net.Addr) (int, error) { return stack.UDP().WriteTo(b, addr, lAddr) }, drop: func() { pool.Put(buf) }, } tunnel.UDPIn() <- inbound.NewPacket(socks5.ParseAddrToSocksAddr(rAddr), pkt, C.SOCKS5) } } go tcp() go udp() go udp() return stack, nil } ================================================ FILE: core/src/main/golang/native/tun/udp.go ================================================ package tun import ( "net" ) type packet struct { local *net.UDPAddr data []byte writeBack func(b []byte, addr net.Addr) (int, error) drop func() } func (pkt *packet) Data() []byte { return pkt.data } func (pkt *packet) WriteBack(b []byte, addr net.Addr) (n int, err error) { return pkt.writeBack(b, addr) } func (pkt *packet) Drop() { pkt.drop() } func (pkt *packet) LocalAddr() net.Addr { return pkt.local } ================================================ FILE: core/src/main/golang/native/tun.go ================================================ package main //#include "bridge.h" import "C" import ( "context" "io" "sync" "unsafe" "golang.org/x/sync/semaphore" "cfa/native/app" "cfa/native/tun" ) var rTunLock sync.Mutex var rTun *remoteTun type remoteTun struct { closer io.Closer callback unsafe.Pointer closed bool limit *semaphore.Weighted } func (t *remoteTun) markSocket(fd int) { _ = t.limit.Acquire(context.Background(), 1) defer t.limit.Release(1) if t.closed { return } C.mark_socket(t.callback, C.int(fd)) } func (t *remoteTun) querySocketUid(protocol int, source, target string) int { _ = t.limit.Acquire(context.Background(), 1) defer t.limit.Release(1) if t.closed { return -1 } return int(C.query_socket_uid(t.callback, C.int(protocol), C.CString(source), C.CString(target))) } func (t *remoteTun) close() { _ = t.limit.Acquire(context.TODO(), 4) defer t.limit.Release(4) t.closed = true if t.closer != nil { _ = t.closer.Close() } app.ApplyTunContext(nil, nil) C.release_object(t.callback) } //export startTun func startTun(fd C.int, gateway, portal, dns C.c_string, callback unsafe.Pointer) C.int { rTunLock.Lock() defer rTunLock.Unlock() if rTun != nil { rTun.close() rTun = nil } f := int(fd) g := C.GoString(gateway) p := C.GoString(portal) d := C.GoString(dns) remote := &remoteTun{callback: callback, closed: false, limit: semaphore.NewWeighted(4)} app.ApplyTunContext(remote.markSocket, remote.querySocketUid) closer, err := tun.Start(f, g, p, d) if err != nil { remote.close() return 1 } remote.closer = closer rTun = remote return 0 } //export stopTun func stopTun() { rTunLock.Lock() defer rTunLock.Unlock() if rTun != nil { rTun.close() rTun = nil } } ================================================ FILE: core/src/main/golang/native/tunnel/conn.go ================================================ package tunnel import ( C "github.com/Dreamacro/clash/constant" "github.com/Dreamacro/clash/tunnel/statistic" ) func CloseAllConnections() { for _, c := range statistic.DefaultManager.Snapshot().Connections { _ = c.Close() } } func closeMatch(filter func(conn C.Conn) bool) { for _, c := range statistic.DefaultManager.Snapshot().Connections { if cc, ok := c.(C.Conn); ok { if filter(cc) { _ = cc.Close() } } } } func closeConnByGroup(name string) { closeMatch(func(conn C.Conn) bool { for _, c := range conn.Chains() { if c == name { return true } } return false }) } ================================================ FILE: core/src/main/golang/native/tunnel/connectivity.go ================================================ package tunnel import ( "sync" "github.com/Dreamacro/clash/adapter" "github.com/Dreamacro/clash/adapter/outboundgroup" "github.com/Dreamacro/clash/constant/provider" "github.com/Dreamacro/clash/log" "github.com/Dreamacro/clash/tunnel" ) func HealthCheck(name string) { p := tunnel.Proxies()[name] if p == nil { log.Warnln("Request health check for `%s`: not found", name) return } g, ok := p.(*adapter.Proxy).ProxyAdapter.(outboundgroup.ProxyGroup) if !ok { log.Warnln("Request health check for `%s`: invalid type %s", name, p.Type().String()) return } wg := &sync.WaitGroup{} for _, pr := range g.Providers() { wg.Add(1) go func(provider provider.ProxyProvider) { provider.HealthCheck() wg.Done() }(pr) } wg.Wait() } func HealthCheckAll() { for _, g := range QueryProxyGroupNames(false) { go func(group string) { HealthCheck(group) }(g) } } ================================================ FILE: core/src/main/golang/native/tunnel/geoip.go ================================================ package tunnel import ( "fmt" "github.com/oschwald/geoip2-golang" "github.com/Dreamacro/clash/component/mmdb" ) func InstallSideloadGeoip(block []byte) error { if block == nil { mmdb.InstallOverride(nil) return nil } db, err := geoip2.FromBytes(block) if err != nil { return fmt.Errorf("load sideload geoip mmdb: %s", err.Error()) } mmdb.InstallOverride(db) return nil } ================================================ FILE: core/src/main/golang/native/tunnel/init.go ================================================ package tunnel import ( "context" "net" "strings" "github.com/Dreamacro/clash/component/dialer" C "github.com/Dreamacro/clash/constant" CTX "github.com/Dreamacro/clash/context" "github.com/Dreamacro/clash/tunnel" ) func init() { dialer.DefaultTunnelDialer = func(context context.Context, network, address string) (net.Conn, error) { if !strings.HasPrefix(network, "tcp") { return nil, net.UnknownNetworkError("unsupported network") } host, port, err := net.SplitHostPort(address) if err != nil { return nil, err } left, right := net.Pipe() metadata := &C.Metadata{ NetWork: C.TCP, Type: C.HTTPCONNECT, SrcIP: loopback, SrcPort: "65535", DstPort: port, AddrType: C.AtypDomainName, Host: host, RawSrcAddr: left.RemoteAddr(), RawDstAddr: left.LocalAddr(), } tunnel.TCPIn() <- CTX.NewConnContext(right, metadata) return left, nil } } ================================================ FILE: core/src/main/golang/native/tunnel/loopback_open.go ================================================ //go:build !premium package tunnel import "net" var loopback = net.ParseIP("127.0.0.1") ================================================ FILE: core/src/main/golang/native/tunnel/loopback_premium.go ================================================ //go:build premium package tunnel import "net/netip" var loopback = netip.MustParseAddr("127.0.0.1") ================================================ FILE: core/src/main/golang/native/tunnel/providers_open.go ================================================ //go:build !premium package tunnel import ( "fmt" "time" P "github.com/Dreamacro/clash/adapter/provider" "github.com/Dreamacro/clash/constant/provider" "github.com/Dreamacro/clash/tunnel" ) type Provider struct { Name string `json:"name"` VehicleType string `json:"vehicleType"` Type string `json:"type"` UpdatedAt int64 `json:"updatedAt"` } func QueryProviders() []*Provider { p := tunnel.Providers() providers := make([]provider.Provider, 0, len(p)) for _, proxy := range p { if proxy.VehicleType() == provider.Compatible { continue } providers = append(providers, proxy) } result := make([]*Provider, 0, len(providers)) for _, p := range providers { updatedAt := time.Time{} if s, ok := p.(P.UpdatableProvider); ok { updatedAt = s.UpdatedAt() } result = append(result, &Provider{ Name: p.Name(), VehicleType: p.VehicleType().String(), Type: p.Type().String(), UpdatedAt: updatedAt.UnixNano() / 1000 / 1000, }) } return result } func UpdateProvider(_ string, name string) error { p, ok := tunnel.Providers()[name] if !ok { return fmt.Errorf("%s not found", name) } return p.Update() } ================================================ FILE: core/src/main/golang/native/tunnel/providers_premium.go ================================================ //go:build premium package tunnel import ( "errors" "fmt" "time" P "github.com/Dreamacro/clash/adapter/provider" "github.com/Dreamacro/clash/constant/provider" "github.com/Dreamacro/clash/log" "github.com/Dreamacro/clash/tunnel" ) var ErrInvalidType = errors.New("invalid type") type Provider struct { Name string `json:"name"` VehicleType string `json:"vehicleType"` Type string `json:"type"` UpdatedAt int64 `json:"updatedAt"` } func QueryProviders() []*Provider { r := tunnel.RuleProviders() p := tunnel.ProxyProviders() providers := make([]provider.Provider, 0, len(r)+len(p)) for _, rule := range r { if rule.VehicleType() == provider.Compatible { continue } providers = append(providers, rule) } for _, proxy := range p { if proxy.VehicleType() == provider.Compatible { continue } providers = append(providers, proxy) } result := make([]*Provider, 0, len(providers)) for _, p := range providers { updatedAt := time.Time{} if s, ok := p.(P.UpdatableProvider[any]); ok { updatedAt = s.UpdatedAt() } result = append(result, &Provider{ Name: p.Name(), VehicleType: p.VehicleType().String(), Type: p.Type().String(), UpdatedAt: updatedAt.UnixNano() / 1000 / 1000, }) } return result } func UpdateProvider(t string, name string) error { err := ErrInvalidType switch t { case "Rule": p := tunnel.RuleProviders()[name] if p == nil { return fmt.Errorf("%s not found", name) } err = p.Update() case "Proxy": p := tunnel.ProxyProviders()[name] if p == nil { return fmt.Errorf("%s not found", name) } err = p.Update() } if err != nil { log.Warnln("Updating provider %s: %s", name, err.Error()) } return err } ================================================ FILE: core/src/main/golang/native/tunnel/proxies.go ================================================ package tunnel import ( "sort" "strings" "github.com/dlclark/regexp2" "github.com/Dreamacro/clash/adapter" "github.com/Dreamacro/clash/adapter/outboundgroup" C "github.com/Dreamacro/clash/constant" "github.com/Dreamacro/clash/constant/provider" "github.com/Dreamacro/clash/log" "github.com/Dreamacro/clash/tunnel" ) type SortMode int const ( Default SortMode = iota Title Delay ) type Proxy struct { Name string `json:"name"` Title string `json:"title"` Subtitle string `json:"subtitle"` Type string `json:"type"` Delay int `json:"delay"` } type ProxyGroup struct { Type string `json:"type"` Now string `json:"now"` Proxies []*Proxy `json:"proxies"` } type sortableProxyList struct { list []*Proxy less func(a, b *Proxy) bool } func (s *sortableProxyList) Len() int { return len(s.list) } func (s *sortableProxyList) Less(i, j int) bool { return s.less(s.list[i], s.list[j]) } func (s *sortableProxyList) Swap(i, j int) { s.list[i], s.list[j] = s.list[j], s.list[i] } func QueryProxyGroupNames(excludeNotSelectable bool) []string { mode := tunnel.Mode() if mode == tunnel.Direct { return []string{} } global := tunnel.Proxies()["GLOBAL"].(*adapter.Proxy).ProxyAdapter.(outboundgroup.ProxyGroup) proxies := global.Providers()[0].Proxies() result := make([]string, 0, len(proxies)+1) if mode == tunnel.Global { result = append(result, "GLOBAL") } for _, p := range proxies { if _, ok := p.(*adapter.Proxy).ProxyAdapter.(outboundgroup.ProxyGroup); ok { if !excludeNotSelectable || p.Type() == C.Selector { result = append(result, p.Name()) } } } return result } func QueryProxyGroup(name string, sortMode SortMode, uiSubtitlePattern *regexp2.Regexp) *ProxyGroup { p := tunnel.Proxies()[name] if p == nil { log.Warnln("Query group `%s`: not found", name) return nil } g, ok := p.(*adapter.Proxy).ProxyAdapter.(outboundgroup.ProxyGroup) if !ok { log.Warnln("Query group `%s`: invalid type %s", name, p.Type().String()) return nil } proxies := collectProviders(g.Providers(), uiSubtitlePattern) switch sortMode { case Title: wrapper := &sortableProxyList{ list: proxies, less: func(a, b *Proxy) bool { return strings.Compare(a.Title, b.Title) < 0 }, } sort.Sort(wrapper) case Delay: wrapper := &sortableProxyList{ list: proxies, less: func(a, b *Proxy) bool { return a.Delay < b.Delay }, } sort.Sort(wrapper) case Default: default: } return &ProxyGroup{ Type: g.Type().String(), Now: g.Now(), Proxies: proxies, } } func PatchSelector(selector, name string) bool { p := tunnel.Proxies()[selector] if p == nil { log.Warnln("Patch selector `%s`: not found", selector) return false } g, ok := p.(*adapter.Proxy).ProxyAdapter.(outboundgroup.ProxyGroup) if !ok { log.Warnln("Patch selector `%s`: invalid type %s", selector, p.Type().String()) return false } s, ok := g.(*outboundgroup.Selector) if !ok { log.Warnln("Patch selector `%s`: invalid type %s", selector, p.Type().String()) return false } if err := s.Set(name); err != nil { log.Warnln("Patch selector `%s`: %s", selector, err.Error()) } log.Infoln("Patch selector %s -> %s", selector, name) closeConnByGroup(selector) return true } func collectProviders(providers []provider.ProxyProvider, uiSubtitlePattern *regexp2.Regexp) []*Proxy { result := make([]*Proxy, 0, 128) for _, p := range providers { for _, px := range p.Proxies() { name := px.Name() title := name subtitle := px.Type().String() if uiSubtitlePattern != nil { if _, ok := px.(*adapter.Proxy).ProxyAdapter.(outboundgroup.ProxyGroup); !ok { runes := []rune(name) match, err := uiSubtitlePattern.FindRunesMatch(runes) if err == nil && match != nil { title = string(runes[:match.Index]) + string(runes[match.Index+match.Length:]) subtitle = string(runes[match.Index : match.Index+match.Length]) } } } result = append(result, &Proxy{ Name: name, Title: strings.TrimSpace(title), Subtitle: strings.TrimSpace(subtitle), Type: px.Type().String(), Delay: int(px.LastDelay()), }) } } return result } ================================================ FILE: core/src/main/golang/native/tunnel/state.go ================================================ package tunnel import ( "github.com/Dreamacro/clash/tunnel" ) func QueryMode() string { return tunnel.Mode().String() } ================================================ FILE: core/src/main/golang/native/tunnel/statistic.go ================================================ package tunnel import ( "github.com/Dreamacro/clash/tunnel/statistic" ) func ResetStatistic() { statistic.DefaultManager.ResetStatistic() } func Now() (up int64, down int64) { return statistic.DefaultManager.Now() } func Total() (up int64, down int64) { return statistic.DefaultManager.Total() } ================================================ FILE: core/src/main/golang/native/tunnel/suspend.go ================================================ package tunnel import "github.com/Dreamacro/clash/adapter/provider" func Suspend(s bool) { provider.Suspend(s) } ================================================ FILE: core/src/main/golang/native/tunnel.go ================================================ package main //#include "bridge.h" import "C" import ( "unsafe" "cfa/native/app" "cfa/native/tunnel" ) //export queryTunnelState func queryTunnelState() *C.char { mode := tunnel.QueryMode() response := &struct { Mode string `json:"mode"` }{mode} return marshalJson(response) } //export queryNow func queryNow(upload, download *C.uint64_t) { up, down := tunnel.Now() *upload = C.uint64_t(up) *download = C.uint64_t(down) } //export queryTotal func queryTotal(upload, download *C.uint64_t) { up, down := tunnel.Total() *upload = C.uint64_t(up) *download = C.uint64_t(down) } //export queryGroupNames func queryGroupNames(excludeNotSelectable C.int) *C.char { return marshalJson(tunnel.QueryProxyGroupNames(excludeNotSelectable != 0)) } //export queryGroup func queryGroup(name C.c_string, sortMode C.c_string) *C.char { n := C.GoString(name) s := C.GoString(sortMode) mode := tunnel.Default switch s { case "Title": mode = tunnel.Title case "Delay": mode = tunnel.Delay } response := tunnel.QueryProxyGroup(n, mode, app.SubtitlePattern()) if response == nil { return nil } return marshalJson(response) } //export healthCheck func healthCheck(completable unsafe.Pointer, name C.c_string) { go func(name string) { tunnel.HealthCheck(name) C.complete(completable, nil) }(C.GoString(name)) } //export healthCheckAll func healthCheckAll() { tunnel.HealthCheckAll() } //export patchSelector func patchSelector(selector, name C.c_string) C.int { s := C.GoString(selector) n := C.GoString(name) if tunnel.PatchSelector(s, n) { return 1 } return 0 } //export queryProviders func queryProviders() *C.char { return marshalJson(tunnel.QueryProviders()) } //export updateProvider func updateProvider(completable unsafe.Pointer, pType C.c_string, name C.c_string) { go func(pType, name string) { C.complete(completable, marshalString(tunnel.UpdateProvider(pType, name))) C.release_object(completable) }(C.GoString(pType), C.GoString(name)) } //export suspend func suspend(suspended C.int) { tunnel.Suspend(suspended != 0) } //export installSideloadGeoip func installSideloadGeoip(block unsafe.Pointer, blockSize C.int) *C.char { if block == nil { _ = tunnel.InstallSideloadGeoip(nil) return nil } bytes := C.GoBytes(block, blockSize) return marshalString(tunnel.InstallSideloadGeoip(bytes)) } ================================================ FILE: core/src/main/golang/native/utils.go ================================================ package main import "C" import ( "encoding/json" "reflect" ) func marshalJson(obj any) *C.char { res, err := json.Marshal(obj) if err != nil { panic(err.Error()) } return C.CString(string(res)) } func marshalString(obj any) *C.char { if obj == nil { return nil } switch o := obj.(type) { case error: return C.CString(o.Error()) case string: return C.CString(o) } panic("invalid marshal type " + reflect.TypeOf(obj).Name()) } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/Clash.kt ================================================ package com.github.kr328.clash.core import com.github.kr328.clash.core.bridge.Bridge import com.github.kr328.clash.core.bridge.ClashException import com.github.kr328.clash.core.bridge.FetchCallback import com.github.kr328.clash.core.bridge.LogcatInterface import com.github.kr328.clash.core.bridge.TunInterface import com.github.kr328.clash.core.model.ConfigurationOverride import com.github.kr328.clash.core.model.FetchStatus import com.github.kr328.clash.core.model.LogMessage import com.github.kr328.clash.core.model.Provider import com.github.kr328.clash.core.model.Proxy import com.github.kr328.clash.core.model.ProxyGroup import com.github.kr328.clash.core.model.ProxySort import com.github.kr328.clash.core.model.Traffic import com.github.kr328.clash.core.model.TunnelState import com.github.kr328.clash.core.model.UiConfiguration import com.github.kr328.clash.core.util.parseInetSocketAddress import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.jsonPrimitive import java.io.File import java.net.InetSocketAddress object Clash { enum class OverrideSlot { Persist, Session } private val ConfigurationOverrideJson = Json { ignoreUnknownKeys = true encodeDefaults = false } fun reset() { Bridge.nativeReset() } fun forceGc() { Bridge.nativeForceGc() } fun suspendCore(suspended: Boolean) { Bridge.nativeSuspend(suspended) } fun queryTunnelState(): TunnelState { val json = Bridge.nativeQueryTunnelState() return Json.decodeFromString(TunnelState.serializer(), json) } fun queryTrafficNow(): Traffic { return Bridge.nativeQueryTrafficNow() } fun queryTrafficTotal(): Traffic { return Bridge.nativeQueryTrafficTotal() } fun notifyDnsChanged(dns: List) { Bridge.nativeNotifyDnsChanged(dns.joinToString(separator = ",")) } fun notifyTimeZoneChanged(name: String, offset: Int) { Bridge.nativeNotifyTimeZoneChanged(name, offset) } fun notifyInstalledAppsChanged(uids: List>) { val uidList = uids.joinToString(separator = ",") { "${it.first}:${it.second}" } Bridge.nativeNotifyInstalledAppChanged(uidList) } fun startTun( fd: Int, gateway: String, portal: String, dns: String, markSocket: (Int) -> Boolean, querySocketUid: (protocol: Int, source: InetSocketAddress, target: InetSocketAddress) -> Int ) { Bridge.nativeStartTun(fd, gateway, portal, dns, object : TunInterface { override fun markSocket(fd: Int) { markSocket(fd) } override fun querySocketUid(protocol: Int, source: String, target: String): Int { return querySocketUid( protocol, parseInetSocketAddress(source), parseInetSocketAddress(target) ) } }) } fun stopTun() { Bridge.nativeStopTun() } fun startHttp(listenAt: String): String? { return Bridge.nativeStartHttp(listenAt) } fun stopHttp() { Bridge.nativeStopHttp() } fun queryGroupNames(excludeNotSelectable: Boolean): List { val names = Json.Default.decodeFromString( JsonArray.serializer(), Bridge.nativeQueryGroupNames(excludeNotSelectable) ) return names.map { require(it.jsonPrimitive.isString) it.jsonPrimitive.content } } fun queryGroup(name: String, sort: ProxySort): ProxyGroup { return Bridge.nativeQueryGroup(name, sort.name) ?.let { Json.Default.decodeFromString(ProxyGroup.serializer(), it) } ?: ProxyGroup(Proxy.Type.Unknown, emptyList(), "") } fun healthCheck(name: String): CompletableDeferred { return CompletableDeferred().apply { Bridge.nativeHealthCheck(this, name) } } fun healthCheckAll() { Bridge.nativeHealthCheckAll() } fun patchSelector(selector: String, name: String): Boolean { return Bridge.nativePatchSelector(selector, name) } fun fetchAndValid( path: File, url: String, force: Boolean, reportStatus: (FetchStatus) -> Unit ): CompletableDeferred { return CompletableDeferred().apply { Bridge.nativeFetchAndValid( object : FetchCallback { override fun report(statusJson: String) { reportStatus( Json.Default.decodeFromString( FetchStatus.serializer(), statusJson ) ) } override fun complete(error: String?) { if (error != null) completeExceptionally(ClashException(error)) else complete(Unit) } }, path.absolutePath, url, force ) } } fun load(path: File): CompletableDeferred { return CompletableDeferred().apply { Bridge.nativeLoad(this, path.absolutePath) } } fun queryProviders(): List { val providers = Json.Default.decodeFromString(JsonArray.serializer(), Bridge.nativeQueryProviders()) return List(providers.size) { Json.Default.decodeFromJsonElement(Provider.serializer(), providers[it]) } } fun updateProvider(type: Provider.Type, name: String): CompletableDeferred { return CompletableDeferred().apply { Bridge.nativeUpdateProvider(this, type.toString(), name) } } fun queryOverride(slot: OverrideSlot): ConfigurationOverride { return try { ConfigurationOverrideJson.decodeFromString( ConfigurationOverride.serializer(), Bridge.nativeReadOverride(slot.ordinal) ) } catch (e: Exception) { ConfigurationOverride() } } fun patchOverride(slot: OverrideSlot, configuration: ConfigurationOverride) { Bridge.nativeWriteOverride( slot.ordinal, ConfigurationOverrideJson.encodeToString( ConfigurationOverride.serializer(), configuration ) ) } fun clearOverride(slot: OverrideSlot) { Bridge.nativeClearOverride(slot.ordinal) } fun installSideloadGeoip(data: ByteArray?) { Bridge.nativeInstallSideloadGeoip(data) } fun queryConfiguration(): UiConfiguration { return Json.Default.decodeFromString( UiConfiguration.serializer(), Bridge.nativeQueryConfiguration() ) } fun subscribeLogcat(): ReceiveChannel { return Channel(32).apply { Bridge.nativeSubscribeLogcat(object : LogcatInterface { override fun received(jsonPayload: String) { trySend(Json.decodeFromString(LogMessage.serializer(), jsonPayload)) } }) } } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/bridge/Bridge.kt ================================================ package com.github.kr328.clash.core.bridge import android.os.Build import android.os.ParcelFileDescriptor import androidx.annotation.Keep import yos.clash.material.common.Global import yos.clash.material.common.log.Log import kotlinx.coroutines.CompletableDeferred import java.io.File @Keep object Bridge { external fun nativeReset() external fun nativeForceGc() external fun nativeSuspend(suspend: Boolean) external fun nativeQueryTunnelState(): String external fun nativeQueryTrafficNow(): Long external fun nativeQueryTrafficTotal(): Long external fun nativeNotifyDnsChanged(dnsList: String) external fun nativeNotifyTimeZoneChanged(name: String, offset: Int) external fun nativeNotifyInstalledAppChanged(uidList: String) external fun nativeStartTun(fd: Int, gateway: String, portal: String, dns: String, cb: TunInterface) external fun nativeStopTun() external fun nativeStartHttp(listenAt: String): String? external fun nativeStopHttp() external fun nativeQueryGroupNames(excludeNotSelectable: Boolean): String external fun nativeQueryGroup(name: String, sort: String): String? external fun nativeHealthCheck(completable: CompletableDeferred, name: String) external fun nativeHealthCheckAll() external fun nativePatchSelector(selector: String, name: String): Boolean external fun nativeFetchAndValid( completable: FetchCallback, path: String, url: String, force: Boolean ) external fun nativeLoad(completable: CompletableDeferred, path: String) external fun nativeQueryProviders(): String external fun nativeUpdateProvider( completable: CompletableDeferred, type: String, name: String ) external fun nativeReadOverride(slot: Int): String external fun nativeWriteOverride(slot: Int, content: String) external fun nativeClearOverride(slot: Int) external fun nativeInstallSideloadGeoip(data: ByteArray?) external fun nativeQueryConfiguration(): String external fun nativeSubscribeLogcat(callback: LogcatInterface) private external fun nativeInit(home: String, versionName: String, sdkVersion: Int) init { System.loadLibrary("bridge") val ctx = Global.application ParcelFileDescriptor.open(File(ctx.packageCodePath), ParcelFileDescriptor.MODE_READ_ONLY) .detachFd() val home = ctx.filesDir.resolve("clash").apply { mkdirs() }.absolutePath val versionName = ctx.packageManager.getPackageInfo(ctx.packageName, 0).versionName val sdkVersion = Build.VERSION.SDK_INT Log.d("Home = $home") nativeInit(home, versionName, sdkVersion) } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/bridge/ClashException.kt ================================================ package com.github.kr328.clash.core.bridge import androidx.annotation.Keep @Keep class ClashException(msg: String) : IllegalArgumentException(msg) ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/bridge/Content.kt ================================================ package com.github.kr328.clash.core.bridge import android.net.Uri import androidx.annotation.Keep import yos.clash.material.common.Global import java.io.FileNotFoundException @Keep object Content { @JvmStatic fun open(url: String): Int { val uri = Uri.parse(url) if (uri.scheme != "content") { throw UnsupportedOperationException("Unsupported scheme ${uri.scheme}") } return Global.application.contentResolver.openFileDescriptor(uri, "r")?.detachFd() ?: throw FileNotFoundException("$uri not found") } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/bridge/FetchCallback.kt ================================================ package com.github.kr328.clash.core.bridge import androidx.annotation.Keep @Keep interface FetchCallback { fun report(statusJson: String) fun complete(error: String?) } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/bridge/LogcatInterface.kt ================================================ package com.github.kr328.clash.core.bridge import androidx.annotation.Keep @Keep interface LogcatInterface { fun received(jsonPayload: String) } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/bridge/TunInterface.kt ================================================ package com.github.kr328.clash.core.bridge import androidx.annotation.Keep @Keep interface TunInterface { fun markSocket(fd: Int) fun querySocketUid(protocol: Int, source: String, target: String): Int } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/model/ConfigurationOverride.kt ================================================ package com.github.kr328.clash.core.model import android.os.Parcel import android.os.Parcelable import com.github.kr328.clash.core.util.Parcelizer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class ConfigurationOverride( @SerialName("port") var httpPort: Int? = null, @SerialName("socks-port") var socksPort: Int? = null, @SerialName("redir-port") var redirectPort: Int? = null, @SerialName("tproxy-port") var tproxyPort: Int? = null, @SerialName("mixed-port") var mixedPort: Int? = null, @SerialName("authentication") var authentication: List? = null, @SerialName("allow-lan") var allowLan: Boolean? = null, @SerialName("bind-address") var bindAddress: String? = null, @SerialName("mode") var mode: TunnelState.Mode? = null, @SerialName("log-level") var logLevel: LogMessage.Level? = null, @SerialName("ipv6") var ipv6: Boolean? = null, @SerialName("hosts") var hosts: Map? = null, @SerialName("dns") val dns: Dns = Dns(), @SerialName("clash-for-android") val app: App = App(), @SerialName("experimental") val experimental: Experimental = Experimental() ) : Parcelable { @Serializable data class Dns( @SerialName("enable") var enable: Boolean? = null, @SerialName("listen") var listen: String? = null, @SerialName("ipv6") var ipv6: Boolean? = null, @SerialName("use-hosts") var useHosts: Boolean? = null, @SerialName("enhanced-mode") var enhancedMode: DnsEnhancedMode? = null, @SerialName("nameserver") var nameServer: List? = null, @SerialName("fallback") var fallback: List? = null, @SerialName("default-nameserver") var defaultServer: List? = null, @SerialName("fake-ip-filter") var fakeIpFilter: List? = null, @SerialName("fallback-filter") val fallbackFilter: DnsFallbackFilter = DnsFallbackFilter(), @SerialName("nameserver-policy") var nameserverPolicy: Map? = null, ) @Serializable data class DnsFallbackFilter( @SerialName("geoip") var geoIp: Boolean? = null, @SerialName("geoip-code") var geoIpCode: String? = null, @SerialName("ipcidr") var ipcidr: List? = null, @SerialName("domain") var domain: List? = null, ) @Serializable data class App( @SerialName("append-system-dns") var appendSystemDns: Boolean? = null ) @Serializable data class Experimental( @SerialName("sniff-tls-sni") var sniffTLSSNI: Boolean? = null, ) @Serializable enum class DnsEnhancedMode { @SerialName("normal") None, @SerialName("redir-host") Mapping, @SerialName("fake-ip") FakeIp, } override fun writeToParcel(parcel: Parcel, flags: Int) { Parcelizer.encodeToParcel(serializer(), parcel, this) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): ConfigurationOverride { return Parcelizer.decodeFromParcel(serializer(), parcel) } override fun newArray(size: Int): Array { return arrayOfNulls(size) } } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/model/FetchStatus.kt ================================================ package com.github.kr328.clash.core.model import android.os.Parcel import android.os.Parcelable import com.github.kr328.clash.core.util.Parcelizer import kotlinx.serialization.Serializable @Serializable data class FetchStatus( val action: Action, val args: List, val progress: Int, val max: Int ) : Parcelable { enum class Action { FetchConfiguration, FetchProviders, Verifying, } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { Parcelizer.encodeToParcel(serializer(), dest, this) } companion object CREATOR : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): FetchStatus { return Parcelizer.decodeFromParcel(serializer(), parcel) } override fun newArray(size: Int): Array { return arrayOfNulls(size) } } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/model/LogMessage.kt ================================================ @file:UseSerializers(DateSerializer::class) package com.github.kr328.clash.core.model import android.os.Parcel import android.os.Parcelable import com.github.kr328.clash.core.util.DateSerializer import com.github.kr328.clash.core.util.Parcelizer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.UseSerializers import java.util.* @Serializable data class LogMessage( val level: Level, val message: String, val time: Date, ) : Parcelable { @Serializable enum class Level { @SerialName("debug") Debug, @SerialName("info") Info, @SerialName("warning") Warning, @SerialName("error") Error, @SerialName("silent") Silent, @SerialName("unknown") Unknown, } override fun writeToParcel(parcel: Parcel, flags: Int) { Parcelizer.encodeToParcel(serializer(), parcel, this) } override fun describeContents(): Int { return 0 } companion object { @JvmField val CREATOR = object : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): LogMessage { return Parcelizer.decodeFromParcel(serializer(), parcel) } override fun newArray(size: Int): Array { return arrayOfNulls(size) } } } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/model/Provider.kt ================================================ package com.github.kr328.clash.core.model import android.os.Parcel import android.os.Parcelable import com.github.kr328.clash.core.util.Parcelizer import kotlinx.serialization.Serializable @Serializable data class Provider( val name: String, val type: Type, val vehicleType: VehicleType, val updatedAt: Long ) : Parcelable, Comparable { enum class Type { Proxy, Rule } enum class VehicleType { HTTP, File, Compatible } override fun writeToParcel(parcel: Parcel, flags: Int) { Parcelizer.encodeToParcel(serializer(), parcel, this) } override fun describeContents(): Int { return 0 } override fun compareTo(other: Provider): Int { return compareValuesBy(this, other, Provider::type, Provider::name) } companion object CREATOR : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): Provider { return Parcelizer.decodeFromParcel(serializer(), parcel) } override fun newArray(size: Int): Array { return arrayOfNulls(size) } } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/model/ProviderList.kt ================================================ package com.github.kr328.clash.core.model import android.os.Parcel import android.os.Parcelable import yos.clash.material.common.util.createListFromParcelSlice import yos.clash.material.common.util.writeToParcelSlice class ProviderList(data: List) : List by data, Parcelable { constructor(parcel: Parcel) : this(Provider.createListFromParcelSlice(parcel, 0, 20)) override fun describeContents(): Int { return 0 } override fun writeToParcel(parcel: Parcel, flags: Int) { return writeToParcelSlice(parcel, flags) } companion object CREATOR : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): ProviderList { return ProviderList(parcel) } override fun newArray(size: Int): Array { return arrayOfNulls(size) } } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/model/Proxy.kt ================================================ package com.github.kr328.clash.core.model import android.os.Parcel import android.os.Parcelable import com.github.kr328.clash.core.util.Parcelizer import kotlinx.serialization.Serializable @Serializable data class Proxy( val name: String, val title: String, val subtitle: String, val type: Type, val delay: Int, ) : Parcelable { @Suppress("unused") enum class Type(val group: Boolean) { Direct(false), Reject(false), Shadowsocks(false), ShadowsocksR(false), Snell(false), Socks5(false), Http(false), Vmess(false), Trojan(false), Relay(true), Selector(true), Fallback(true), URLTest(true), LoadBalance(true), Unknown(false); } override fun writeToParcel(parcel: Parcel, flags: Int) { Parcelizer.encodeToParcel(serializer(), parcel, this) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): Proxy { return Parcelizer.decodeFromParcel(serializer(), parcel) } override fun newArray(size: Int): Array { return arrayOfNulls(size) } } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/model/ProxyGroup.kt ================================================ package com.github.kr328.clash.core.model import android.os.Parcel import android.os.Parcelable import yos.clash.material.common.util.createListFromParcelSlice import yos.clash.material.common.util.writeToParcelSlice import kotlinx.serialization.Serializable @Serializable data class ProxyGroup( val type: Proxy.Type, val proxies: List, val now: String, ) : Parcelable { class SliceProxyList(data: List) : List by data, Parcelable { constructor(parcel: Parcel) : this(Proxy.createListFromParcelSlice(parcel, 0, 50)) override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { writeToParcelSlice(dest, flags) } companion object CREATOR : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): SliceProxyList { return SliceProxyList(parcel) } override fun newArray(size: Int): Array { return arrayOfNulls(size) } } } constructor(parcel: Parcel) : this( Proxy.Type.values()[parcel.readInt()], SliceProxyList(parcel), parcel.readString()!!, ) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeInt(type.ordinal) SliceProxyList(proxies).writeToParcel(parcel, 0) parcel.writeString(now) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): ProxyGroup { return ProxyGroup(parcel) } override fun newArray(size: Int): Array { return arrayOfNulls(size) } } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/model/ProxySort.kt ================================================ package com.github.kr328.clash.core.model enum class ProxySort { Default, Title, Delay } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/model/Traffic.kt ================================================ package com.github.kr328.clash.core.model typealias Traffic = Long ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/model/TunnelState.kt ================================================ package com.github.kr328.clash.core.model import android.os.Parcel import android.os.Parcelable import com.github.kr328.clash.core.util.Parcelizer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class TunnelState( val mode: Mode, ) : Parcelable { @Serializable enum class Mode { @SerialName("direct") Direct, @SerialName("global") Global, @SerialName("rule") Rule, @SerialName("script") Script, } override fun writeToParcel(parcel: Parcel, flags: Int) { Parcelizer.encodeToParcel(serializer(), parcel, this) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): TunnelState { return Parcelizer.decodeFromParcel(serializer(), parcel) } override fun newArray(size: Int): Array { return arrayOfNulls(size) } } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/model/UiConfiguration.kt ================================================ package com.github.kr328.clash.core.model import android.os.Parcel import android.os.Parcelable import com.github.kr328.clash.core.util.Parcelizer import kotlinx.serialization.Serializable @Serializable class UiConfiguration : Parcelable { override fun writeToParcel(parcel: Parcel, flags: Int) { Parcelizer.encodeToParcel(serializer(), parcel, this) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): UiConfiguration { return Parcelizer.decodeFromParcel(serializer(), parcel) } override fun newArray(size: Int): Array { return arrayOfNulls(size) } } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/util/Net.kt ================================================ package com.github.kr328.clash.core.util import java.net.InetAddress import java.net.InetSocketAddress import java.net.URL fun parseInetSocketAddress(address: String): InetSocketAddress { val url = URL("https://$address") return InetSocketAddress(InetAddress.getByName(url.host), url.port) } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/util/Parcelizer.kt ================================================ package com.github.kr328.clash.core.util import android.os.Parcel import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.SerializationStrategy import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.CompositeDecoder import kotlinx.serialization.encoding.CompositeEncoder import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.modules.SerializersModule object Parcelizer { private class ParcelDecoder(private val parcel: Parcel) : Decoder, CompositeDecoder { override val serializersModule: SerializersModule = SerializersModule {} @ExperimentalSerializationApi override fun decodeSequentially(): Boolean = true override fun decodeByteElement(descriptor: SerialDescriptor, index: Int) = decodeByte() override fun decodeCharElement(descriptor: SerialDescriptor, index: Int) = decodeChar() override fun decodeDoubleElement(descriptor: SerialDescriptor, index: Int) = decodeDouble() override fun decodeElementIndex(descriptor: SerialDescriptor) = decodeInt() override fun decodeFloatElement(descriptor: SerialDescriptor, index: Int) = decodeFloat() override fun decodeBooleanElement(descriptor: SerialDescriptor, index: Int) = decodeBoolean() @ExperimentalSerializationApi override fun decodeInlineElement(descriptor: SerialDescriptor, index: Int): Decoder { return this } override fun decodeIntElement(descriptor: SerialDescriptor, index: Int) = decodeInt() override fun decodeLongElement(descriptor: SerialDescriptor, index: Int) = decodeLong() override fun decodeShortElement(descriptor: SerialDescriptor, index: Int) = decodeShort() override fun decodeStringElement(descriptor: SerialDescriptor, index: Int) = decodeString() @ExperimentalSerializationApi override fun decodeNullableSerializableElement( descriptor: SerialDescriptor, index: Int, deserializer: DeserializationStrategy, previousValue: T? ): T? = decodeNullableSerializableValue(deserializer) override fun decodeSerializableElement( descriptor: SerialDescriptor, index: Int, deserializer: DeserializationStrategy, previousValue: T? ): T = decodeSerializableValue(deserializer) override fun endStructure(descriptor: SerialDescriptor) { } override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder { return this } override fun decodeCollectionSize(descriptor: SerialDescriptor): Int { return decodeInt() } override fun decodeBoolean(): Boolean { return decodeByte() != (0.toByte()) } override fun decodeByte(): Byte { return parcel.readByte() } override fun decodeChar(): Char { return decodeInt().toChar() } override fun decodeDouble(): Double { return parcel.readDouble() } override fun decodeEnum(enumDescriptor: SerialDescriptor): Int { return decodeInt() } override fun decodeFloat(): Float { return parcel.readFloat() } @ExperimentalSerializationApi override fun decodeInline(inlineDescriptor: SerialDescriptor): Decoder { return this } override fun decodeInt(): Int { return parcel.readInt() } override fun decodeLong(): Long { return parcel.readLong() } @ExperimentalSerializationApi override fun decodeNotNullMark(): Boolean { return decodeBoolean() } @ExperimentalSerializationApi override fun decodeNull(): Nothing? { return null } override fun decodeShort(): Short { return decodeInt().toShort() } override fun decodeString(): String { return parcel.readString()!! } } private class ParcelEncoder(private val parcel: Parcel) : Encoder, CompositeEncoder { override val serializersModule: SerializersModule = SerializersModule {} override fun encodeBooleanElement( descriptor: SerialDescriptor, index: Int, value: Boolean ) = encodeBoolean(value) override fun encodeByteElement(descriptor: SerialDescriptor, index: Int, value: Byte) = encodeByte(value) override fun encodeCharElement(descriptor: SerialDescriptor, index: Int, value: Char) = encodeChar(value) override fun encodeDoubleElement(descriptor: SerialDescriptor, index: Int, value: Double) = encodeDouble(value) override fun encodeFloatElement(descriptor: SerialDescriptor, index: Int, value: Float) = encodeFloat(value) @ExperimentalSerializationApi override fun encodeInlineElement(descriptor: SerialDescriptor, index: Int): Encoder { return this } override fun encodeIntElement(descriptor: SerialDescriptor, index: Int, value: Int) = encodeInt(value) override fun encodeLongElement(descriptor: SerialDescriptor, index: Int, value: Long) = encodeLong(value) override fun encodeShortElement(descriptor: SerialDescriptor, index: Int, value: Short) = encodeShort(value) override fun encodeStringElement(descriptor: SerialDescriptor, index: Int, value: String) = encodeString(value) @ExperimentalSerializationApi override fun encodeNullableSerializableElement( descriptor: SerialDescriptor, index: Int, serializer: SerializationStrategy, value: T? ) = encodeNullableSerializableValue(serializer, value) override fun encodeSerializableElement( descriptor: SerialDescriptor, index: Int, serializer: SerializationStrategy, value: T ) = encodeSerializableValue(serializer, value) override fun endStructure(descriptor: SerialDescriptor) { } override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder { return this } override fun beginCollection( descriptor: SerialDescriptor, collectionSize: Int ): CompositeEncoder { encodeInt(collectionSize) return super.beginCollection(descriptor, collectionSize) } override fun encodeBoolean(value: Boolean) { encodeByte(if (value) 1 else 0) } override fun encodeByte(value: Byte) { parcel.writeByte(value) } override fun encodeChar(value: Char) { encodeInt(value.code) } override fun encodeDouble(value: Double) { parcel.writeDouble(value) } override fun encodeEnum(enumDescriptor: SerialDescriptor, index: Int) { encodeInt(index) } override fun encodeFloat(value: Float) { parcel.writeFloat(value) } @ExperimentalSerializationApi override fun encodeInline(inlineDescriptor: SerialDescriptor): Encoder { return this } override fun encodeInt(value: Int) { parcel.writeInt(value) } override fun encodeLong(value: Long) { parcel.writeLong(value) } @ExperimentalSerializationApi override fun encodeNull() { encodeBoolean(false) } override fun encodeShort(value: Short) { encodeInt(value.toInt()) } override fun encodeString(value: String) { parcel.writeString(value) } @ExperimentalSerializationApi override fun encodeNotNullMark() { encodeBoolean(true) } } fun decodeFromParcel(deserializer: DeserializationStrategy, parcel: Parcel): T { return deserializer.deserialize(ParcelDecoder(parcel)) } fun encodeToParcel(serializer: SerializationStrategy, parcel: Parcel, value: T) { serializer.serialize(ParcelEncoder(parcel), value) } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/util/Serializers.kt ================================================ package com.github.kr328.clash.core.util import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import java.util.* object DateSerializer : KSerializer { override val descriptor: SerialDescriptor get() = PrimitiveSerialDescriptor("Date", PrimitiveKind.LONG) override fun deserialize(decoder: Decoder): Date { return Date(decoder.decodeLong()) } override fun serialize(encoder: Encoder, value: Date) { encoder.encodeLong(value.time) } } ================================================ FILE: core/src/main/java/com/github/kr328/clash/core/util/Traffic.kt ================================================ package com.github.kr328.clash.core.util import com.github.kr328.clash.core.model.Traffic fun Traffic.trafficUpload(): String { return trafficString(scaleTraffic(this ushr 32)) } fun Traffic.trafficDownload(): String { return trafficString(scaleTraffic(this and 0xFFFFFFFF)) } fun Traffic.trafficTotal(): String { val upload = scaleTraffic(this ushr 32) val download = scaleTraffic(this and 0xFFFFFFFF) return trafficString(upload + download) } private fun trafficString(scaled: Long): String { return when { scaled > 1024 * 1024 * 1024 * 100L -> { val data = scaled / 1024 / 1024 / 1024 String.format("%.2f GiB", data.toFloat() / 100) } scaled > 1024 * 1024 * 100L -> { val data = scaled / 1024 / 1024 String.format("%.2f MiB", data.toFloat() / 100) } scaled > 1024 * 100L -> { val data = scaled / 1024 String.format("%.2f KiB", data.toFloat() / 100) } else -> { "$scaled Bytes" } } } private fun scaleTraffic(value: Long): Long { val type = (value ushr 30) and 0x3 val data = value and 0x3FFFFFFF return when (type) { 0L -> data 1L -> data * 1024 2L -> data * 1024 * 1024 3L -> data * 1024 * 1024 * 1024 else -> throw IllegalArgumentException("invalid value type") } } ================================================ FILE: core/src/premium/golang/go.mod ================================================ module premium go 1.18 require cfa v0.0.0 require ( cfa/blob v0.0.0 // indirect github.com/Dreamacro/clash v1.7.1 // indirect github.com/Kr328/tun2socket v0.0.0-20220414050025-d07c78d06d34 // indirect github.com/avast/apkparser v0.0.0-20210223100516-186f320f9bfc // indirect github.com/avast/apkverifier v0.0.0-20210916093748-2146ff7c4b7f // indirect github.com/cilium/ebpf v0.9.0 // indirect github.com/dlclark/regexp2 v1.4.0 // indirect github.com/florianl/go-tc v0.4.1 // indirect github.com/gofrs/uuid v4.2.0+incompatible // indirect github.com/google/btree v1.0.1 // indirect github.com/google/go-cmp v0.5.7 // indirect github.com/google/nftables v0.0.0-20220611213346-a346d51f53b3 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/insomniacslk/dhcp v0.0.0-20220504074936-1ca156eafb9f // indirect github.com/josharian/native v1.0.0 // indirect github.com/klauspost/compress v1.11.13 // indirect github.com/mdlayher/netlink v1.6.0 // indirect github.com/mdlayher/socket v0.1.1 // indirect github.com/miekg/dns v1.1.49 // indirect github.com/openacid/low v0.1.21 // indirect github.com/oschwald/geoip2-golang v1.7.0 // indirect github.com/oschwald/maxminddb-golang v1.9.0 // indirect github.com/samber/lo v1.21.0 // indirect github.com/sirupsen/logrus v1.8.1 // indirect github.com/u-root/uio v0.0.0-20210528114334-82958018845c // indirect github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 // indirect go.etcd.io/bbolt v1.3.6 // indirect go.starlark.net v0.0.0-20220328144851-d1966c6b9fcd // indirect go.uber.org/atomic v1.9.0 // indirect go4.org/intern v0.0.0-20211027215823-ae77deb06f29 // indirect go4.org/unsafe/assume-no-moving-gc v0.0.0-20220617031537-928513b29760 // indirect golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e // indirect golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 // indirect golang.org/x/mod v0.6.0-dev.0.20211013180041-c96bc1413d57 // indirect golang.org/x/net v0.0.0-20220617184016-355a448f1bc9 // indirect golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f // indirect golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/time v0.0.0-20191024005414-555d28b269f0 // indirect golang.org/x/tools v0.1.9 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect gvisor.dev/gvisor v0.0.0-20220428010907-8082b77961ba // indirect inet.af/netaddr v0.0.0-20220617031823-097006376321 // indirect ) replace cfa => ../../main/golang replace github.com/Dreamacro/clash => ./clash replace cfa/blob => ../../../build/intermediates/golang_blob ================================================ FILE: core/src/premium/golang/go.sum ================================================ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/Kr328/tun2socket v0.0.0-20220414050025-d07c78d06d34 h1:USCTqih5d1bUXUxWNS9ZD5Tx/lb0jXHEtRIIx/F9dMc= github.com/Kr328/tun2socket v0.0.0-20220414050025-d07c78d06d34/go.mod h1:YR9wK13TgI5ww8iKWm91MHiSoHC7Oz0U4beCCmtXqLw= github.com/avast/apkparser v0.0.0-20190516101250-3b8c5efcb6a9/go.mod h1:c0733VBXm1we9M1zCtoOspplSwOYebS3hpDkJyMORRU= github.com/avast/apkparser v0.0.0-20200102113521-69bcdd9c2403/go.mod h1:eZzHNfZWA1eeKPQE3LVmfRw32lhrH351jDCsma9qxOc= github.com/avast/apkparser v0.0.0-20200402131724-9fd46d5c4749/go.mod h1:CSBdDZNEsGRYPiDt9QcGrIy8iWQ9YzB1rcuxn44+0jc= github.com/avast/apkparser v0.0.0-20200924103028-30471fa5618f/go.mod h1:SKNzWGFyNJji/Z+iXjPCpmpFPvenFuhLjrSLCwCM/cM= github.com/avast/apkparser v0.0.0-20210223100516-186f320f9bfc h1:hiohrweJOE4vk79Wm6JWCBBZBnDmpa55DxSIcyxE0Jw= github.com/avast/apkparser v0.0.0-20210223100516-186f320f9bfc/go.mod h1:98WPhH/r8MbKpffuuDCAGtPyzSI2IVwXBcWAlXhMVC4= github.com/avast/apkverifier v0.0.0-20190808142831-dbbe53a24744/go.mod h1:mhWRoMg0KhvWt8SX7B2v2E3VfWt5jWfHfD9PtWAN+qM= github.com/avast/apkverifier v0.0.0-20200217135742-aa28c80b82ae/go.mod h1:SV58cyAAN+SzX8GIBhizatMJNGcDyfQUj/xZUlKRW+I= github.com/avast/apkverifier v0.0.0-20200416105355-97c5338f32f0/go.mod h1:HskRSJJJbP3poUkDRAyRAdDVSsh5J1mz8cRc2/B4kbc= github.com/avast/apkverifier v0.0.0-20210219091843-33631264c352/go.mod h1:uhY/I/3Vh3V6ZFgLm/EFX/j5//MdoXpvcULTtzRW3YA= github.com/avast/apkverifier v0.0.0-20210916093748-2146ff7c4b7f h1:FMalgGNj/85WMWgR5TJ8OseRSyy/s5QBrRmxOZ8aNAo= github.com/avast/apkverifier v0.0.0-20210916093748-2146ff7c4b7f/go.mod h1:APQFx11UQTdbLKlZVJQFddZcJZxoHl6NnJfHN7foLD8= github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/cilium/ebpf v0.5.0/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs= github.com/cilium/ebpf v0.7.0/go.mod h1:/oI2+1shJiTGAMgl6/RgJr36Eo1jzrRcAWbcXO2usCA= github.com/cilium/ebpf v0.8.1/go.mod h1:f5zLIM0FSNuAkSyLAN7X+Hy6yznlF1mNiWUMfxMtrgk= github.com/cilium/ebpf v0.9.0 h1:ldiV+FscPCQ/p3mNEV4O02EPbUZJFsoEtHvIr9xLTvk= github.com/cilium/ebpf v0.9.0/go.mod h1:+OhNOIXx/Fnu1IE8bJz2dzOA+VSfyTfdNUVdlQnxUFY= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E= github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/dvyukov/go-fuzz v0.0.0-20210103155950-6a8e9d1f2415/go.mod h1:11Gm+ccJnvAhCNLlf5+cS9KjtbaD5I5zaZpFMsTHWTw= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fanliao/go-promise v0.0.0-20141029170127-1890db352a72/go.mod h1:PjfxuH4FZdUyfMdtBio2lsRr1AKEaVPwelzuHuh8Lqc= github.com/florianl/go-tc v0.4.1 h1:hVx6soOY/wbznLZ5yCNL5Fzc8+fiDr5dQPSIYDQnLV8= github.com/florianl/go-tc v0.4.1/go.mod h1:kCCrW0ppJu2XcrUYS2utigmcMtEf9qZpAlIg5zdRqXk= github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k= github.com/frankban/quicktest v1.14.0 h1:+cqqvzZV87b4adx/5ayVOaYZ2CrvM4ejQvUdBzPPUss= github.com/frankban/quicktest v1.14.0/go.mod h1:NeW+ay9A/U67EYXNFA1nPE8e/tnQv/09mUdL/ijj8og= github.com/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0= github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/google/btree v1.0.1 h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4= github.com/google/btree v1.0.1/go.mod h1:xXMiIv4Fb/0kKde4SpL7qlzvu5cMJDRkFDxJfI9uaxA= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/nftables v0.0.0-20220611213346-a346d51f53b3 h1:Fq+jS60rvgwyi9zFyGUXwsdNViYcw1tr3CA8ZoYQVEk= github.com/google/nftables v0.0.0-20220611213346-a346d51f53b3/go.mod h1:b97ulCCFipUC+kSin+zygkvUVpx0vyIAwxXFdY3PlNc= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/hugelgupf/socketpair v0.0.0-20190730060125-05d35a94e714/go.mod h1:2Goc3h8EklBH5mspfHFxBnEoURQCGzQQH1ga9Myjvis= github.com/insomniacslk/dhcp v0.0.0-20220504074936-1ca156eafb9f h1:l1QCwn715k8nYkj4Ql50rzEog3WnMdrd4YYMMwemxEo= github.com/insomniacslk/dhcp v0.0.0-20220504074936-1ca156eafb9f/go.mod h1:h+MxyHxRg9NH3terB1nfRIUaQEcI0XOVkdR9LNBlp8E= github.com/josharian/native v0.0.0-20200817173448-b6b71def0850/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= github.com/josharian/native v1.0.0 h1:Ts/E8zCSEsG17dUqv7joXJFybuMLjQfWE04tsBODTxk= github.com/josharian/native v1.0.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= github.com/jsimonetti/rtnetlink v0.0.0-20190606172950-9527aa82566a/go.mod h1:Oz+70psSo5OFh8DBl0Zv2ACw7Esh6pPUphlvZG9x7uw= github.com/jsimonetti/rtnetlink v0.0.0-20200117123717-f846d4f6c1f4/go.mod h1:WGuG/smIU4J/54PblvSbh+xvCZmpJnFgr3ds6Z55XMQ= github.com/jsimonetti/rtnetlink v0.0.0-20201009170750-9c6f07d100c1/go.mod h1:hqoO/u39cqLeBLebZ8fWdE96O7FxrAsRYhnVOdgHxok= github.com/jsimonetti/rtnetlink v0.0.0-20201110080708-d2c240429e6c/go.mod h1:huN4d1phzjhlOsNIjFsw2SVRbwIHj3fJDMEU2SDPTmg= github.com/jsimonetti/rtnetlink v0.0.0-20201216134343-bde56ed16391/go.mod h1:cR77jAZG3Y3bsb8hF6fHJbFoyFukLFOkQ98S0pQz3xw= github.com/jsimonetti/rtnetlink v0.0.0-20201220180245-69540ac93943/go.mod h1:z4c53zj6Eex712ROyh8WI0ihysb5j2ROyV42iNogmAs= github.com/jsimonetti/rtnetlink v0.0.0-20210122163228-8d122574c736/go.mod h1:ZXpIyOK59ZnN7J0BV99cZUPmsqDRZ3eq5X+st7u/oSA= github.com/jsimonetti/rtnetlink v0.0.0-20210212075122-66c871082f2b/go.mod h1:8w9Rh8m+aHZIG69YPGGem1i5VzoyRC8nw2kA8B+ik5U= github.com/jsimonetti/rtnetlink v0.0.0-20210525051524-4cc836578190/go.mod h1:NmKSdU4VGSiv1bMsdqNALI4RSvvjtz65tTMCnD05qLo= github.com/jsimonetti/rtnetlink v0.0.0-20211022192332-93da33804786 h1:N527AHMa793TP5z5GNAn/VLPzlc0ewzWdeP/25gDfgQ= github.com/jsimonetti/rtnetlink v0.0.0-20211022192332-93da33804786/go.mod h1:v4hqbTdfQngbVSZJVWUhGE/lbTFf9jb+ygmNUDQMuOs= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/klauspost/compress v1.11.0/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.13 h1:eSvu8Tmq6j2psUJqJrLcWH6K3w5Dwc+qipbaA6eVEN4= github.com/klauspost/compress v1.11.13/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/mdlayher/ethernet v0.0.0-20190606142754-0394541c37b7/go.mod h1:U6ZQobyTjI/tJyq2HG+i/dfSoFUt8/aZCM+GKtmFk/Y= github.com/mdlayher/ethtool v0.0.0-20210210192532-2b88debcdd43/go.mod h1:+t7E0lkKfbBsebllff1xdTmyJt8lH37niI6kwFk9OTo= github.com/mdlayher/genetlink v1.0.0/go.mod h1:0rJ0h4itni50A86M2kHcgS85ttZazNt7a8H2a2cw0Gc= github.com/mdlayher/netlink v0.0.0-20190409211403-11939a169225/go.mod h1:eQB3mZE4aiYnlUsyGGCOpPETfdQq4Jhsgf1fk3cwQaA= github.com/mdlayher/netlink v1.0.0/go.mod h1:KxeJAFOFLG6AjpyDkQ/iIhxygIUKD+vcwqcnu43w/+M= github.com/mdlayher/netlink v1.1.0/go.mod h1:H4WCitaheIsdF9yOYu8CFmCgQthAPIWZmcKp9uZHgmY= github.com/mdlayher/netlink v1.1.1/go.mod h1:WTYpFb/WTvlRJAyKhZL5/uy69TDDpHHu2VZmb2XgV7o= github.com/mdlayher/netlink v1.2.0/go.mod h1:kwVW1io0AZy9A1E2YYgaD4Cj+C+GPkU6klXCMzIJ9p8= github.com/mdlayher/netlink v1.2.1/go.mod h1:bacnNlfhqHqqLo4WsYeXSqfyXkInQ9JneWI68v1KwSU= github.com/mdlayher/netlink v1.2.2-0.20210123213345-5cc92139ae3e/go.mod h1:bacnNlfhqHqqLo4WsYeXSqfyXkInQ9JneWI68v1KwSU= github.com/mdlayher/netlink v1.3.0/go.mod h1:xK/BssKuwcRXHrtN04UBkwQ6dY9VviGGuriDdoPSWys= github.com/mdlayher/netlink v1.4.0/go.mod h1:dRJi5IABcZpBD2A3D0Mv/AiX8I9uDEu5oGkAVrekmf8= github.com/mdlayher/netlink v1.4.1/go.mod h1:e4/KuJ+s8UhfUpO9z00/fDZZmhSrs+oxyqAS9cNgn6Q= github.com/mdlayher/netlink v1.6.0 h1:rOHX5yl7qnlpiVkFWoqccueppMtXzeziFjWAjLg6sz0= github.com/mdlayher/netlink v1.6.0/go.mod h1:0o3PlBmGst1xve7wQ7j/hwpNaFaH4qCRyWCdcZk8/vA= github.com/mdlayher/raw v0.0.0-20190606142536-fef19f00fc18/go.mod h1:7EpbotpCmVZcu+KCX4g9WaRNuu11uyhiW7+Le1dKawg= github.com/mdlayher/raw v0.0.0-20191009151244-50f2db8cc065/go.mod h1:7EpbotpCmVZcu+KCX4g9WaRNuu11uyhiW7+Le1dKawg= github.com/mdlayher/socket v0.0.0-20210307095302-262dc9984e00/go.mod h1:GAFlyu4/XV68LkQKYzKhIo/WW7j3Zi0YRAz/BOoanUc= github.com/mdlayher/socket v0.1.1 h1:q3uOGirUPfAV2MUoaC7BavjQ154J7+JOkTWyiV+intI= github.com/mdlayher/socket v0.1.1/go.mod h1:mYV5YIZAfHh4dzDVzI8x8tWLWCliuX8Mon5Awbj+qDs= github.com/miekg/dns v1.1.49 h1:qe0mQU3Z/XpFeE+AEBo2rqaS1IPBJ3anmqZ4XiZJVG8= github.com/miekg/dns v1.1.49/go.mod h1:e3IlAVfNqAllflbibAZEWOXOQ+Ynzk/dDozDxY7XnME= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/openacid/errors v0.8.1/go.mod h1:GUQEJJOJE3W9skHm8E8Y4phdl2LLEN8iD7c5gcGgdx0= github.com/openacid/low v0.1.21 h1:Tr2GNu4N/+rGRYdOsEHOE89cxUIaDViZbVmKz29uKGo= github.com/openacid/low v0.1.21/go.mod h1:q+MsKI6Pz2xsCkzV4BLj7NR5M4EX0sGz5AqotpZDVh0= github.com/openacid/must v0.1.3/go.mod h1:luPiXCuJlEo3UUFQngVQokV0MPGryeYvtCbQPs3U1+I= github.com/openacid/testkeys v0.1.6/go.mod h1:MfA7cACzBpbiwekivj8StqX0WIRmqlMsci1c37CA3Do= github.com/oschwald/geoip2-golang v1.7.0 h1:JW1r5AKi+vv2ujSxjKthySK3jo8w8oKWPyXsw+Qs/S8= github.com/oschwald/geoip2-golang v1.7.0/go.mod h1:mdI/C7iK7NVMcIDDtf4bCKMJ7r0o7UwGeCo9eiitCMQ= github.com/oschwald/maxminddb-golang v1.9.0 h1:tIk4nv6VT9OiPyrnDAfJS1s1xKDQMZOsGojab6EjC1Y= github.com/oschwald/maxminddb-golang v1.9.0/go.mod h1:TK+s/Z2oZq0rSl4PSeAEoP0bgm82Cp5HyvYbt8K3zLY= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/samber/lo v1.21.0 h1:FSby8pJQtX4KmyddTCCGhc3JvnnIVrDA+NW37rG+7G8= github.com/samber/lo v1.21.0/go.mod h1:2I7tgIv8Q1SG2xEIkRq0F2i2zgxVpnyPOP0d3Gj2r+A= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= github.com/thoas/go-funk v0.9.1 h1:O549iLZqPpTUQ10ykd26sZhzD+rmR5pWhuElrhbC20M= github.com/u-root/uio v0.0.0-20210528114334-82958018845c h1:BFvcl34IGnw8yvJi8hlqLFo9EshRInwWBs2M5fGWzQA= github.com/u-root/uio v0.0.0-20210528114334-82958018845c/go.mod h1:LpEX5FO/cB+WF4TYGY1V5qktpaZLkKkSegbr0V4eYXA= github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 h1:gga7acRE695APm9hlsSMoOoE65U4/TcqNj90mc69Rlg= github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.etcd.io/bbolt v1.3.6 h1:/ecaJf0sk1l4l6V4awd65v2C3ILy7MSj+s/x1ADCIMU= go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= go.starlark.net v0.0.0-20220328144851-d1966c6b9fcd h1:Uo/x0Ir5vQJ+683GXB9Ug+4fcjsbp7z7Ul8UaZbhsRM= go.starlark.net v0.0.0-20220328144851-d1966c6b9fcd/go.mod h1:t3mmBBPzAVvK0L0n1drDmrQsJ8FoIx4INCqVMTr/Zo0= go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go4.org/intern v0.0.0-20211027215823-ae77deb06f29 h1:UXLjNohABv4S58tHmeuIZDO6e3mHpW2Dx33gaNt03LE= go4.org/intern v0.0.0-20211027215823-ae77deb06f29/go.mod h1:cS2ma+47FKrLPdXFpr7CuxiTW3eyJbWew4qx0qtQWDA= go4.org/unsafe/assume-no-moving-gc v0.0.0-20211027215541-db492cf91b37/go.mod h1:FftLjUGFEDu5k8lt0ddY+HcrH/qU/0qk+H8j9/nTl3E= go4.org/unsafe/assume-no-moving-gc v0.0.0-20220617031537-928513b29760 h1:FyBZqvoA/jbNzuAWLQE2kG820zMAkcilx6BMjGbL/E4= go4.org/unsafe/assume-no-moving-gc v0.0.0-20220617031537-928513b29760/go.mod h1:FftLjUGFEDu5k8lt0ddY+HcrH/qU/0qk+H8j9/nTl3E= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e h1:T8NU3HyQ8ClP4SEE+KbFlg6n0NhuTsN4MyznaarGsZM= golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 h1:3MTrJm4PyNL9NBqvYDSj3DHl46qQakyfqfWo4jgfaEM= golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20211013180041-c96bc1413d57 h1:LQmS1nU0twXLA96Kt7U9qtHJEbBk3z6Q0V4UXjZkpr4= golang.org/x/mod v0.6.0-dev.0.20211013180041-c96bc1413d57/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190419010253-1f3472d942ba/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191007182048-72f939374954/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201216054612-986b41b23924/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220617184016-355a448f1bc9 h1:Yqz/iviulwKwAREEeUd3nbBFn0XuyJqkoft2IlrvOhc= golang.org/x/net v0.0.0-20220617184016-355a448f1bc9/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f h1:Ax0t5p6N38Ga0dThY21weqDEyz2oklo4IvDkpigvkD8= golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190411185658-b44545bcd369/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190418153312-f0ce4c0180be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606122018-79a91cf218c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200923182605-d9f96fdee20d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201009025420-dfb3f7c4e634/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201101102859-da207088b7d1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201118182958-a01c418693c7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201218084310-7d0127a74742/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210110051926-789bb1bd4061/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210123111255-9b0068b26619/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210216163648-f7da38b97c65/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210525143221-35b2ab0089ea/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210906170528-6f6e22806c34/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c h1:aFV+BgZ4svzjfabn8ERpuB4JI4N6/rdy1iusx77G3oU= golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0 h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.9 h1:j9KsMiaP1c3B0OTQGth0/k+miLGTgLsAFUCrF2vLcF8= golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gvisor.dev/gvisor v0.0.0-20220428010907-8082b77961ba h1:qJ6jWSTl9q+/y4l8QCNpkNnasX/sHzhVnPRysee8PzY= gvisor.dev/gvisor v0.0.0-20220428010907-8082b77961ba/go.mod h1:tWwEcFvJavs154OdjFCw78axNrsDlz4Zh8jvPqwcpGI= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= inet.af/netaddr v0.0.0-20220617031823-097006376321 h1:B4dC8ySKTQXasnjDTMsoCMf1sQG4WsMej0WXaHxunmU= inet.af/netaddr v0.0.0-20220617031823-097006376321/go.mod h1:OIezDfdzOgFhuw4HuWapWq2e9l0H9tK4F1j+ETRtF3k= ================================================ FILE: core/src/premium/golang/main.go ================================================ package main import _ "cfa/native/all" ================================================ FILE: design/build.gradle.kts ================================================ plugins { kotlin("android") kotlin("kapt") id("com.android.library") } dependencies { repositories { mavenLocal() mavenCentral() gradlePluginPortal() google() maven("https://jitpack.io") maven("https://oss.sonatype.org/content/repositories/snapshots/") maven("https://maven.kr328.app/releases") } implementation(project(":common")) implementation(project(":core")) implementation(project(":service")) implementation(libs.kotlin.coroutine) implementation(libs.androidx.core) implementation(libs.androidx.appcompat) implementation(libs.androidx.activity) implementation(libs.androidx.coordinator) implementation(libs.androidx.recyclerview) implementation(libs.androidx.fragment) implementation(libs.androidx.viewpager) implementation(libs.google.material) implementation(libs.getactivity.xxpermission) implementation(libs.androidx.splashscreen) } ================================================ FILE: design/consumer-rules.pro ================================================ ================================================ FILE: design/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: design/src/main/AndroidManifest.xml ================================================ ================================================ FILE: design/src/main/java/yos/clash/material/design/AccessControlDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.view.View import androidx.core.widget.addTextChangedListener import yos.clash.material.design.adapter.AppAdapter import yos.clash.material.design.component.AccessControlMenu import yos.clash.material.design.databinding.DesignAccessControlBinding import yos.clash.material.design.databinding.DialogSearchBinding import yos.clash.material.design.dialog.FullScreenDialog import yos.clash.material.design.model.AppInfo import yos.clash.material.design.store.UiStore import yos.clash.material.design.util.* import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel class AccessControlDesign( context: Context, uiStore: UiStore, private val selected: MutableSet, ) : Design(context) { enum class Request { ReloadApps, SelectAll, SelectNone, SelectInvert, Import, Export, } private val binding = DesignAccessControlBinding .inflate(context.layoutInflater, context.root, false) private val adapter = AppAdapter(context, selected) private val menu: AccessControlMenu by lazy { AccessControlMenu(context, binding.menuView, uiStore, requests) } val apps: List get() = adapter.apps override val root: View get() = binding.root suspend fun patchApps(apps: List) { adapter.swapDataSet(adapter::apps, apps, false) } suspend fun rebindAll() { withContext(Dispatchers.Main) { adapter.rebindAll() } } init { binding.self = this binding.activityBarLayout.applyFrom(context) binding.mainList.recyclerList.also { it.bindAppBarElevation(binding.activityBarLayout) it.applyLinearAdapter(context, adapter) } binding.menuView.setOnClickListener { menu.show() } binding.searchView.setOnClickListener { launch { try { requestSearch() } finally { withContext(NonCancellable) { rebindAll() } } } } } private suspend fun requestSearch() { coroutineScope { val binding = DialogSearchBinding .inflate(context.layoutInflater, context.root, false) val adapter = AppAdapter(context, selected) val dialog = FullScreenDialog(context) val filter = Channel(Channel.CONFLATED) dialog.setContentView(binding.root) binding.surface = dialog.surface binding.mainList.applyLinearAdapter(context, adapter) binding.keywordView.addTextChangedListener { filter.trySend(Unit) } binding.closeView.setOnClickListener { dialog.dismiss() } dialog.setOnDismissListener { cancel() } dialog.setOnShowListener { binding.keywordView.requestTextInput() } dialog.show() while (isActive) { filter.receive() val keyword = binding.keywordView.text?.toString() ?: "" val apps: List = if (keyword.isEmpty()) { emptyList() } else { withContext(Dispatchers.Default) { apps.filter { it.label.contains(keyword, ignoreCase = true) || it.packageName.contains(keyword, ignoreCase = true) } } } adapter.patchDataSet(adapter::apps, apps, false, AppInfo::packageName) delay(200) } } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/ApkBrokenDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.view.View import yos.clash.material.design.databinding.DesignSettingsCommonBinding import yos.clash.material.design.preference.category import yos.clash.material.design.preference.clickable import yos.clash.material.design.preference.preferenceScreen import yos.clash.material.design.preference.tips import yos.clash.material.design.util.applyFrom import yos.clash.material.design.util.bindAppBarElevation import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.root class ApkBrokenDesign(context: Context) : Design(context) { data class Request(val url: String) private val binding = DesignSettingsCommonBinding .inflate(context.layoutInflater, context.root, false) override val root: View get() = binding.root init { binding.surface = surface binding.activityBarLayout.applyFrom(context) binding.scrollRoot.bindAppBarElevation(binding.activityBarLayout) val screen = preferenceScreen(context) { tips(R.string.application_broken_tips) category(R.string.reinstall) clickable( title = R.string.google_play, summary = R.string.google_play_url ) { clicked { requests.trySend(Request(context.getString(R.string.google_play_url))) } } clickable( title = R.string.github_releases, summary = R.string.github_releases_url ) { clicked { requests.trySend(Request(context.getString(R.string.github_releases_url))) } } } binding.content.addView(screen.root) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/AppCrashedDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.view.View import yos.clash.material.design.databinding.DesignAppCrashedBinding import yos.clash.material.design.util.applyFrom import yos.clash.material.design.util.bindAppBarElevation import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.root class AppCrashedDesign(context: Context) : Design(context) { private val binding = DesignAppCrashedBinding .inflate(context.layoutInflater, context.root, false) override val root: View get() = binding.root fun setAppLogs(logs: String) { binding.logsView.text = logs } init { binding.self = this binding.activityBarLayout.applyFrom(context) binding.scrollRoot.bindAppBarElevation(binding.activityBarLayout) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/AppSettingsDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.view.View import com.hjq.permissions.Permission import com.hjq.permissions.XXPermissions import kotlinx.coroutines.withContext import yos.clash.material.design.databinding.DesignSettingsCommonBinding import yos.clash.material.design.model.Behavior import yos.clash.material.design.model.DarkMode import yos.clash.material.design.preference.* import yos.clash.material.design.store.UiStore import yos.clash.material.design.util.applyFrom import yos.clash.material.design.util.bindAppBarElevation import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.root import yos.clash.material.service.store.ServiceStore class AppSettingsDesign( context: Context, uiStore: UiStore, srvStore: ServiceStore, behavior: Behavior, running: Boolean, ) : Design(context) { enum class Request { ReCreateAllActivities } private val binding = DesignSettingsCommonBinding .inflate(context.layoutInflater, context.root, false) override val root: View get() = binding.root init { binding.surface = surface binding.activityBarLayout.applyFrom(context) binding.scrollRoot.bindAppBarElevation(binding.activityBarLayout) val screen = preferenceScreen(context) { category(R.string.behavior) switch( value = behavior::autoRestart, icon = R.drawable.ic_baseline_restore, title = R.string.auto_restart, summary = R.string.allow_clash_auto_restart, ) category(R.string.interface_) selectableList( value = uiStore::darkMode, values = DarkMode.values(), valuesText = arrayOf( R.string.follow_system_android_10, R.string.always_light, R.string.always_dark ), icon = R.drawable.ic_baseline_brightness_4, title = R.string.dark_mode ) { listener = OnChangedListener { requests.trySend(Request.ReCreateAllActivities) } } category(R.string.service) val permission = XXPermissions.isGranted(context, Permission.POST_NOTIFICATIONS) switch( value = srvStore::dynamicNotification, icon = R.drawable.ic_baseline_domain, title = R.string.show_traffic, summary = if (permission) R.string.show_traffic_summary else R.string.permission_notification_desc ) { enabled = (!running && permission) } } binding.content.addView(screen.root) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/Design.kt ================================================ package yos.clash.material.design import android.content.Context import android.view.View import androidx.appcompat.app.AppCompatActivity import yos.clash.material.design.ui.Surface import yos.clash.material.design.ui.ToastDuration import yos.clash.material.design.util.setOnInsertsChangedListener import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.withContext abstract class Design(val context: Context) : CoroutineScope by CoroutineScope(Dispatchers.Unconfined) { abstract val root: View val surface = Surface() val requests: Channel = Channel(Channel.UNLIMITED) suspend fun showToast( resId: Int, duration: ToastDuration, configure: Snackbar.() -> Unit = {} ) { return showToast(context.getString(resId), duration, configure) } suspend fun showToast( message: CharSequence, duration: ToastDuration, configure: Snackbar.() -> Unit = {} ) { withContext(Dispatchers.Main) { Snackbar.make( root, message, when (duration) { ToastDuration.Short -> Snackbar.LENGTH_SHORT ToastDuration.Long -> Snackbar.LENGTH_LONG ToastDuration.Indefinite -> Snackbar.LENGTH_INDEFINITE } ).apply(configure).show() } } init { when (context) { is AppCompatActivity -> { context.window.decorView.setOnInsertsChangedListener { if (surface.insets != it) { surface.insets = it } } } } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/FilesDesign.kt ================================================ package yos.clash.material.design import android.app.Dialog import android.content.Context import android.view.View import yos.clash.material.design.adapter.FileAdapter import yos.clash.material.design.databinding.DesignFilesBinding import yos.clash.material.design.databinding.DialogFilesMenuBinding import yos.clash.material.design.dialog.AppBottomSheetDialog import yos.clash.material.design.dialog.requestModelTextInput import yos.clash.material.design.model.File import yos.clash.material.design.util.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class FilesDesign(context: Context) : Design(context) { sealed class Request { data class OpenFile(val file: File) : Request() data class OpenDirectory(val file: File) : Request() data class RenameFile(val file: File) : Request() data class DeleteFile(val file: File) : Request() data class ImportFile(val file: File?) : Request() data class ExportFile(val file: File) : Request() object PopStack : Request() } private val binding = DesignFilesBinding .inflate(context.layoutInflater, context.root, false) private val adapter: FileAdapter = FileAdapter(context, this::requestOpen, this::requestMore) override val root: View get() = binding.root var configurationEditable: Boolean get() = binding.configurationEditable set(value) { binding.configurationEditable = value } suspend fun swapFiles(files: List, currentInBaseDir: Boolean) { withContext(Dispatchers.Main) { adapter.swapDataSet(adapter::files, files) binding.currentInBaseDir = currentInBaseDir } } fun updateElapsed() { adapter.updateElapsed() } suspend fun requestFileName(name: String): String { return context.requestModelTextInput( initial = name, title = context.getText(R.string.file_name), hint = context.getText(R.string.file_name), error = context.getText(R.string.invalid_file_name), validator = ValidatorFileName, ) } init { binding.self = this binding.activityBarLayout.applyFrom(context) binding.mainList.recyclerList.also { it.applyLinearAdapter(context, adapter) it.bindAppBarElevation(binding.activityBarLayout) } } private fun requestOpen(file: File) { if (file.isDirectory) { requests.trySend(Request.OpenDirectory(file)) } else { requests.trySend(Request.OpenFile(file)) } } fun requestRename(dialog: Dialog, file: File) { requests.trySend(Request.RenameFile(file)) dialog.dismiss() } fun requestImport(dialog: Dialog, file: File) { requests.trySend(Request.ImportFile(file)) dialog.dismiss() } fun requestExport(dialog: Dialog, file: File) { requests.trySend(Request.ExportFile(file)) dialog.dismiss() } fun requestDelete(dialog: Dialog, file: File) { requests.trySend(Request.DeleteFile(file)) dialog.dismiss() } fun requestNew() { requests.trySend(Request.ImportFile(null)) } private fun requestMore(file: File) { val dialog = AppBottomSheetDialog(context) val binding = DialogFilesMenuBinding.inflate(context.layoutInflater) binding.master = this binding.self = dialog binding.file = file binding.currentInBase = this.binding.currentInBaseDir binding.configurationEditable = this.binding.configurationEditable dialog.setContentView(binding.root) dialog.show() } } ================================================ FILE: design/src/main/java/yos/clash/material/design/HelpDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.net.Uri import android.view.View import yos.clash.material.common.compat.preferredLocale import yos.clash.material.design.databinding.DesignSettingsCommonBinding import yos.clash.material.design.preference.category import yos.clash.material.design.preference.clickable import yos.clash.material.design.preference.preferenceScreen import yos.clash.material.design.preference.tips import yos.clash.material.design.util.applyFrom import yos.clash.material.design.util.bindAppBarElevation import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.root class HelpDesign( context: Context, openLink: (Uri) -> Unit, ) : Design(context) { private val binding = DesignSettingsCommonBinding .inflate(context.layoutInflater, context.root, false) override val root: View get() = binding.root init { binding.surface = surface binding.activityBarLayout.applyFrom(context) binding.scrollRoot.bindAppBarElevation(binding.activityBarLayout) val screen = preferenceScreen(context) { tips(R.string.tips_help) clickable( title = R.string.application_name, summary = R.string.github_url_now ) { clicked { openLink(Uri.parse(context.getString(R.string.github_url_now))) } } category(R.string.document) clickable( title = R.string.clash_wiki, summary = R.string.clash_wiki_url ) { clicked { openLink(Uri.parse(context.getString(R.string.clash_wiki_url))) } } category(R.string.feedback) /*if (YosConfigAchieve.getIfPremium()) { clickable( title = R.string.google_play, summary = R.string.google_play_url ) { clicked { openLink(Uri.parse(context.getString(R.string.google_play_url))) } } }*/ clickable( title = R.string.github_issues, summary = R.string.github_issues_url ) { clicked { openLink(Uri.parse(context.getString(R.string.github_issues_url))) } } category(R.string.sources) clickable( title = R.string.clash_for_android_show, summary = R.string.github_url ) { clicked { openLink(Uri.parse(context.getString(R.string.github_url))) } } clickable( title = R.string.clash_core, summary = R.string.clash_core_url ) { clicked { openLink(Uri.parse(context.getString(R.string.clash_core_url))) } } category(R.string.donate) clickable( title = R.string.developer_now, summary = R.string.donate_url_now ) { clicked { openLink(Uri.parse(context.getString(R.string.donate_url_now))) } } if (context.resources.configuration.preferredLocale.language == "zh") { clickable( title = R.string.developer_before, summary = R.string.donate_url ) { clicked { openLink(Uri.parse(context.getString(R.string.donate_url))) } } } } binding.content.addView(screen.root) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/LogcatDesign.kt ================================================ package yos.clash.material.design import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.view.View import androidx.core.content.getSystemService import androidx.recyclerview.widget.LinearLayoutManager import com.github.kr328.clash.core.model.LogMessage import yos.clash.material.design.adapter.LogMessageAdapter import yos.clash.material.design.databinding.DesignLogcatBinding import yos.clash.material.design.ui.ToastDuration import yos.clash.material.design.util.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class LogcatDesign( context: Context, private val streaming: Boolean, ) : Design(context) { enum class Request { Close, Delete, Export } private val binding = DesignLogcatBinding .inflate(context.layoutInflater, context.root, false) private val adapter = LogMessageAdapter(context) { launch { val data = ClipData.newPlainText("log_message", it.message) context.getSystemService()?.setPrimaryClip(data) showToast(R.string.copied, ToastDuration.Short) } } suspend fun patchMessages(messages: List, removed: Int, appended: Int) { withContext(Dispatchers.Main) { adapter.messages = messages adapter.notifyItemRangeInserted(adapter.messages.size, appended) adapter.notifyItemRangeRemoved(0, removed) if (streaming && binding.recyclerList.isTop) { binding.recyclerList.scrollToPosition(messages.size - 1) } } } override val root: View get() = binding.root init { binding.self = this binding.streaming = streaming binding.activityBarLayout.applyFrom(context) binding.recyclerList.bindAppBarElevation(binding.activityBarLayout) binding.recyclerList.layoutManager = LinearLayoutManager(context).apply { if (streaming) { reverseLayout = true stackFromEnd = true } } binding.recyclerList.adapter = adapter } } ================================================ FILE: design/src/main/java/yos/clash/material/design/LogsDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.view.View import yos.clash.material.design.adapter.LogFileAdapter import yos.clash.material.design.databinding.DesignLogsBinding import yos.clash.material.design.model.LogFile import yos.clash.material.design.util.* import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import kotlin.coroutines.resume class LogsDesign(context: Context) : Design(context) { sealed class Request { object StartLogcat : Request() object DeleteAll : Request() data class OpenFile(val file: LogFile) : Request() } private val binding = DesignLogsBinding .inflate(context.layoutInflater, context.root, false) private val adapter = LogFileAdapter(context) { requests.trySend(Request.OpenFile(it)) } override val root: View get() = binding.root suspend fun patchLogs(logs: List) { adapter.patchDataSet(adapter::logs, logs, false, LogFile::fileName) } suspend fun requestDeleteAll(): Boolean { return withContext(Dispatchers.Main) { suspendCancellableCoroutine { ctx -> MaterialAlertDialogBuilder(context) .setTitle(R.string.delete_all_logs) .setMessage(R.string.delete_all_logs_warn) .setPositiveButton(R.string.ok) { _, _ -> ctx.resume(true) } .setNegativeButton(R.string.cancel) { _, _ -> } .show() .setOnDismissListener { if (!ctx.isCompleted) ctx.resume(false) } } } } init { binding.self = this binding.activityBarLayout.applyFrom(context) binding.recyclerList.applyLinearAdapter(context, adapter) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/MainDesign.kt ================================================ package yos.clash.material.design import android.app.ProgressDialog.show import android.content.Context import android.graphics.drawable.BitmapDrawable import android.view.View import android.view.WindowManager import androidx.appcompat.app.AlertDialog import com.github.kr328.clash.core.model.TunnelState import com.github.kr328.clash.core.util.trafficTotal import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.hjq.permissions.XXPermissions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import yos.clash.material.design.databinding.DesignAboutBinding import yos.clash.material.design.databinding.DesignMainBinding import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.resolveThemedColor import yos.clash.material.design.util.root import java.security.Permission class MainDesign(context: Context) : Design(context) { enum class Request { ToggleStatus, OpenProxy, OpenProfiles, OpenProviders, OpenLogs, OpenSettings, OpenHelp, OpenAbout, } private val binding = DesignMainBinding .inflate(context.layoutInflater, context.root, false) override val root: View get() = binding.root suspend fun setProfileName(name: String?) { withContext(Dispatchers.Main) { binding.profileName = name } } suspend fun setClashRunning(running: Boolean) { withContext(Dispatchers.Main) { binding.clashRunning = running } } suspend fun setForwarded(value: Long) { withContext(Dispatchers.Main) { binding.forwarded = value.trafficTotal() } } suspend fun setMode(mode: TunnelState.Mode) { withContext(Dispatchers.Main) { binding.mode = when (mode) { TunnelState.Mode.Direct -> context.getString(R.string.direct_mode) TunnelState.Mode.Global -> context.getString(R.string.global_mode) TunnelState.Mode.Rule -> context.getString(R.string.rule_mode) TunnelState.Mode.Script -> context.getString(R.string.script_mode) } } } suspend fun setHasProviders(has: Boolean) { withContext(Dispatchers.Main) { binding.hasProviders = has } } suspend fun showAbout(versionName: String) { withContext(Dispatchers.Main) { val binding = DesignAboutBinding.inflate(context.layoutInflater).apply { this.versionName = versionName } val alertDialog = AlertDialog.Builder(context).create() val window = alertDialog.window window!!.setBackgroundDrawable(BitmapDrawable()) window.decorView.setPadding(25, 0, 25, 0); alertDialog.setView(binding.root) alertDialog.show() } } suspend fun showUpdatedTips() { withContext(Dispatchers.Main) { MaterialAlertDialogBuilder(context) .setTitle(R.string.version_updated) .setMessage(R.string.version_updated_tips) .setPositiveButton(R.string.ok) { _, _ -> } .show() } } suspend fun showPermissionRequest() { withContext(Dispatchers.Main) { MaterialAlertDialogBuilder(context) .setTitle(R.string.permission_request_title) .setMessage(R.string.permission_notification_desc) .setPositiveButton(R.string.permission_request_positive) { _, _ -> XXPermissions.startPermissionActivity( context, com.hjq.permissions.Permission.POST_NOTIFICATIONS ) } .setNegativeButton(R.string.permission_request_negative) { _, _ -> } .show() } } init { binding.self = this binding.colorClashStarted = context.resolveThemedColor(R.attr.colorPrimary) binding.colorClashStopped = context.resolveThemedColor(R.attr.colorClashStopped) } fun request(request: Request) { requests.trySend(request) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/NetworkSettingsDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.os.Build import android.view.View import yos.clash.material.design.databinding.DesignSettingsCommonBinding import yos.clash.material.design.preference.* import yos.clash.material.design.store.UiStore import yos.clash.material.design.ui.ToastDuration import yos.clash.material.design.util.applyFrom import yos.clash.material.design.util.bindAppBarElevation import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.root import yos.clash.material.service.model.AccessControlMode import yos.clash.material.service.store.ServiceStore import kotlinx.coroutines.launch class NetworkSettingsDesign( context: Context, uiStore: UiStore, srvStore: ServiceStore, running: Boolean, ) : Design(context) { enum class Request { StartAccessControlList } private val binding = DesignSettingsCommonBinding .inflate(context.layoutInflater, context.root, false) override val root: View get() = binding.root init { binding.surface = surface binding.activityBarLayout.applyFrom(context) binding.scrollRoot.bindAppBarElevation(binding.activityBarLayout) val screen = preferenceScreen(context) { val vpnDependencies: MutableList = mutableListOf() val vpn = switch( value = uiStore::enableVpn, icon = R.drawable.ic_baseline_vpn_lock, title = R.string.route_system_traffic, summary = R.string.routing_via_vpn_service ) { listener = OnChangedListener { vpnDependencies.forEach { it.enabled = uiStore.enableVpn } } } category(R.string.vpn_service_options) switch( value = srvStore::bypassPrivateNetwork, title = R.string.bypass_private_network, summary = R.string.bypass_private_network_summary, configure = vpnDependencies::add, ) switch( value = srvStore::dnsHijacking, title = R.string.dns_hijacking, summary = R.string.dns_hijacking_summary, configure = vpnDependencies::add, ) switch( value = srvStore::allowBypass, title = R.string.allow_bypass, summary = R.string.allow_bypass_summary, configure = vpnDependencies::add, ) if (Build.VERSION.SDK_INT >= 29) { switch( value = srvStore::systemProxy, title = R.string.system_proxy, summary = R.string.system_proxy_summary, configure = vpnDependencies::add, ) } selectableList( value = srvStore::accessControlMode, values = AccessControlMode.values(), valuesText = arrayOf( R.string.allow_all_apps, R.string.allow_selected_apps, R.string.deny_selected_apps ), title = R.string.access_control_mode, configure = vpnDependencies::add, ) clickable( title = R.string.access_control_packages, summary = R.string.access_control_packages_summary, ) { clicked { requests.trySend(Request.StartAccessControlList) } vpnDependencies.add(this) } if (running) { vpn.enabled = false vpnDependencies.forEach { it.enabled = false } } else { vpn.listener?.onChanged() } } binding.content.addView(screen.root) if (running) { launch { showToast(R.string.options_unavailable, ToastDuration.Indefinite) } } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/NewProfileDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.view.View import yos.clash.material.design.adapter.ProfileProviderAdapter import yos.clash.material.design.databinding.DesignNewProfileBinding import yos.clash.material.design.model.ProfileProvider import yos.clash.material.design.util.* class NewProfileDesign(context: Context) : Design(context) { sealed class Request { data class Create(val provider: ProfileProvider) : Request() data class OpenDetail(val provider: ProfileProvider.External) : Request() } private val binding = DesignNewProfileBinding .inflate(context.layoutInflater, context.root, false) private val adapter = ProfileProviderAdapter(context, this::requestCreate, this::requestDetail) override val root: View get() = binding.root suspend fun patchProviders(providers: List) { adapter.apply { patchDataSet(this::providers, providers) } } init { binding.self = this binding.activityBarLayout.applyFrom(context) binding.mainList.recyclerList.also { it.bindAppBarElevation(binding.activityBarLayout) it.applyLinearAdapter(context, adapter) } } private fun requestCreate(provider: ProfileProvider) { requests.trySend(Request.Create(provider)) } private fun requestDetail(provider: ProfileProvider): Boolean { if (provider !is ProfileProvider.External) return false requests.trySend(Request.OpenDetail(provider)) return true } } ================================================ FILE: design/src/main/java/yos/clash/material/design/OverrideSettingsDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.view.View import com.github.kr328.clash.core.model.ConfigurationOverride import com.github.kr328.clash.core.model.LogMessage import com.github.kr328.clash.core.model.TunnelState import yos.clash.material.design.adapter.SideloadProviderAdapter import yos.clash.material.design.databinding.DesignSettingsOverideBinding import yos.clash.material.design.databinding.DialogPreferenceListBinding import yos.clash.material.design.dialog.FullScreenDialog import yos.clash.material.design.model.AppInfo import yos.clash.material.design.preference.* import yos.clash.material.design.util.* import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import kotlin.coroutines.resume class OverrideSettingsDesign( context: Context, configuration: ConfigurationOverride ) : Design(context) { enum class Request { ResetOverride, EditSideloadGeoip } private val binding = DesignSettingsOverideBinding .inflate(context.layoutInflater, context.root, false) override val root: View get() = binding.root suspend fun requestResetConfirm(): Boolean { return suspendCancellableCoroutine { ctx -> val dialog = MaterialAlertDialogBuilder(context) .setTitle(R.string.reset_override_settings) .setMessage(R.string.reset_override_settings_message) .setPositiveButton(R.string.ok) { _, _ -> ctx.resume(true) } .setNegativeButton(R.string.cancel) { _, _ -> } .show() dialog.setOnDismissListener { if (!ctx.isCompleted) ctx.resume(false) } ctx.invokeOnCancellation { dialog.dismiss() } } } suspend fun requestSelectSideload(initial: String, apps: List): String = withContext(Dispatchers.Main) { suspendCancellableCoroutine { ctx -> val binding = DialogPreferenceListBinding .inflate(context.layoutInflater, context.root, false) val adapter = SideloadProviderAdapter(context, apps, initial) val dialog = FullScreenDialog(context) dialog.setContentView(binding.root) binding.surface = dialog.surface binding.titleView.text = context.getString(R.string.sideload_geoip) binding.newView.visibility = View.INVISIBLE binding.mainList.applyLinearAdapter(context, adapter) binding.resetView.setOnClickListener { ctx.resume("") dialog.dismiss() } binding.cancelView.setOnClickListener { dialog.dismiss() } binding.okView.setOnClickListener { ctx.resume(adapter.selectedPackageName) dialog.dismiss() } dialog.setOnDismissListener { if (!ctx.isCompleted) ctx.resume(initial) } dialog.show() } } init { binding.self = this binding.activityBarLayout.applyFrom(context) binding.scrollRoot.bindAppBarElevation(binding.activityBarLayout) val booleanValues: Array = arrayOf( null, true, false ) val booleanValuesText: Array = arrayOf( R.string.dont_modify, R.string.enabled, R.string.disabled ) val screen = preferenceScreen(context) { category(R.string.general) editableText( value = configuration::httpPort, adapter = NullableTextAdapter.Port, title = R.string.http_port, placeholder = R.string.dont_modify, empty = R.string.disabled, ) editableText( value = configuration::socksPort, adapter = NullableTextAdapter.Port, title = R.string.socks_port, placeholder = R.string.dont_modify, empty = R.string.disabled, ) editableText( value = configuration::redirectPort, adapter = NullableTextAdapter.Port, title = R.string.redirect_port, placeholder = R.string.dont_modify, empty = R.string.disabled, ) editableText( value = configuration::tproxyPort, adapter = NullableTextAdapter.Port, title = R.string.tproxy_port, placeholder = R.string.dont_modify, empty = R.string.disabled, ) editableText( value = configuration::mixedPort, adapter = NullableTextAdapter.Port, title = R.string.mixed_port, placeholder = R.string.dont_modify, empty = R.string.disabled, ) editableTextList( value = configuration::authentication, adapter = TextAdapter.String, title = R.string.authentication, placeholder = R.string.dont_modify, ) selectableList( value = configuration::allowLan, values = booleanValues, valuesText = booleanValuesText, title = R.string.allow_lan, ) selectableList( value = configuration::ipv6, values = booleanValues, valuesText = booleanValuesText, title = R.string.ipv6, ) editableText( value = configuration::bindAddress, adapter = NullableTextAdapter.String, title = R.string.bind_address, placeholder = R.string.dont_modify, empty = R.string.default_ ) if (YosConfigAchieve.getIfPremium()) { selectableList( value = configuration::mode, values = arrayOf( null, TunnelState.Mode.Direct, TunnelState.Mode.Global, TunnelState.Mode.Rule, TunnelState.Mode.Script ), valuesText = arrayOf( R.string.dont_modify, R.string.direct_mode, R.string.global_mode, R.string.rule_mode, R.string.script_mode ), title = R.string.mode ) } else { selectableList( value = configuration::mode, values = arrayOf( null, TunnelState.Mode.Direct, TunnelState.Mode.Global, TunnelState.Mode.Rule ), valuesText = arrayOf( R.string.dont_modify, R.string.direct_mode, R.string.global_mode, R.string.rule_mode ), title = R.string.mode ) } if (YosConfigAchieve.getIfPremium()) { selectableList( value = configuration.experimental::sniffTLSSNI, values = booleanValues, valuesText = booleanValuesText, title = R.string.sniff_tls_sni, ) } selectableList( value = configuration::logLevel, values = arrayOf( null, LogMessage.Level.Info, LogMessage.Level.Warning, LogMessage.Level.Error, LogMessage.Level.Debug, LogMessage.Level.Silent, ), valuesText = arrayOf( R.string.dont_modify, R.string.info, R.string.warning, R.string.error, R.string.debug, R.string.silent, ), title = R.string.log_level, ) editableTextMap( value = configuration::hosts, keyAdapter = TextAdapter.String, valueAdapter = TextAdapter.String, title = R.string.hosts, placeholder = R.string.dont_modify, ) clickable( title = R.string.sideload_geoip, summary = R.string.sideload_geoip_summary ) { clicked { requests.trySend(Request.EditSideloadGeoip) } } category(R.string.dns) val dnsDependencies: MutableList = mutableListOf() val dns = selectableList( value = configuration.dns::enable, values = arrayOf( null, true, false ), valuesText = arrayOf( R.string.dont_modify, R.string.force_enable, R.string.use_built_in, ), title = R.string.strategy ) { listener = OnChangedListener { if (configuration.dns.enable == false) { dnsDependencies.forEach { it.enabled = false } } else { dnsDependencies.forEach { it.enabled = true } } } } editableText( value = configuration.dns::listen, adapter = NullableTextAdapter.String, title = R.string.listen, placeholder = R.string.dont_modify, empty = R.string.disabled, configure = dnsDependencies::add, ) selectableList( value = configuration.app::appendSystemDns, values = booleanValues, valuesText = booleanValuesText, title = R.string.append_system_dns, configure = dnsDependencies::add, ) selectableList( value = configuration.dns::ipv6, values = booleanValues, valuesText = booleanValuesText, title = R.string.ipv6, configure = dnsDependencies::add, ) selectableList( value = configuration.dns::useHosts, values = booleanValues, valuesText = booleanValuesText, title = R.string.use_hosts, configure = dnsDependencies::add, ) selectableList( value = configuration.dns::enhancedMode, values = arrayOf( null, ConfigurationOverride.DnsEnhancedMode.None, ConfigurationOverride.DnsEnhancedMode.FakeIp, ConfigurationOverride.DnsEnhancedMode.Mapping ), valuesText = arrayOf( R.string.dont_modify, R.string.disabled, R.string.fakeip, R.string.mapping ), title = R.string.enhanced_mode, configure = dnsDependencies::add, ) editableTextList( value = configuration.dns::nameServer, adapter = TextAdapter.String, title = R.string.name_server, placeholder = R.string.dont_modify, configure = dnsDependencies::add, ) editableTextList( value = configuration.dns::fallback, adapter = TextAdapter.String, title = R.string.fallback, placeholder = R.string.dont_modify, configure = dnsDependencies::add, ) editableTextList( value = configuration.dns::defaultServer, adapter = TextAdapter.String, title = R.string.default_name_server, placeholder = R.string.dont_modify, configure = dnsDependencies::add, ) editableTextList( value = configuration.dns::fakeIpFilter, adapter = TextAdapter.String, title = R.string.fakeip_filter, placeholder = R.string.dont_modify, configure = dnsDependencies::add, ) selectableList( value = configuration.dns.fallbackFilter::geoIp, values = booleanValues, valuesText = booleanValuesText, title = R.string.geoip_fallback, configure = dnsDependencies::add, ) editableText( value = configuration.dns.fallbackFilter::geoIpCode, adapter = NullableTextAdapter.String, title = R.string.geoip_fallback_code, placeholder = R.string.dont_modify, empty = R.string.raw_cn, configure = dnsDependencies::add, ) editableTextList( value = configuration.dns.fallbackFilter::domain, adapter = TextAdapter.String, title = R.string.domain_fallback, placeholder = R.string.dont_modify, configure = dnsDependencies::add, ) editableTextList( value = configuration.dns.fallbackFilter::ipcidr, adapter = TextAdapter.String, title = R.string.ipcidr_fallback, placeholder = R.string.dont_modify, configure = dnsDependencies::add, ) editableTextMap( value = configuration.dns::nameserverPolicy, keyAdapter = TextAdapter.String, valueAdapter = TextAdapter.String, title = R.string.name_server_policy, placeholder = R.string.dont_modify, configure = dnsDependencies::add, ) dns.listener?.onChanged() } binding.content.addView(screen.root) } fun requestClear() { requests.trySend(Request.ResetOverride) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/ProfilesDesign.kt ================================================ package yos.clash.material.design import android.app.Dialog import android.content.Context import android.view.View import android.view.ViewGroup import yos.clash.material.design.adapter.ProfileAdapter import yos.clash.material.design.databinding.DesignProfilesBinding import yos.clash.material.design.databinding.DialogProfilesMenuBinding import yos.clash.material.design.dialog.AppBottomSheetDialog import yos.clash.material.design.ui.ToastDuration import yos.clash.material.design.util.* import yos.clash.material.service.model.Profile import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class ProfilesDesign(context: Context) : Design(context) { sealed class Request { object UpdateAll : Request() object Create : Request() data class Active(val profile: Profile) : Request() data class Update(val profile: Profile) : Request() data class Edit(val profile: Profile) : Request() data class Duplicate(val profile: Profile) : Request() data class Delete(val profile: Profile) : Request() } private val binding = DesignProfilesBinding .inflate(context.layoutInflater, context.root, false) private val adapter = ProfileAdapter(context, this::requestActive, this::showMenu) override val root: View get() = binding.root suspend fun patchProfiles(profiles: List) { adapter.apply { patchDataSet(this::profiles, profiles, id = { it.uuid }) } val updatable = withContext(Dispatchers.Default) { profiles.any { it.imported && it.type != Profile.Type.File } } withContext(Dispatchers.Main) { binding.updateView.visibility = if (updatable) View.VISIBLE else View.GONE } } suspend fun requestSave(profile: Profile) { showToast(R.string.active_unsaved_tips, ToastDuration.Long) { setAction(R.string.edit) { requests.trySend(Request.Edit(profile)) } } } fun updateElapsed() { adapter.updateElapsed() } init { binding.self = this binding.activityBarLayout.applyFrom(context) binding.mainList.recyclerList.also { it.bindAppBarElevation(binding.activityBarLayout) it.applyLinearAdapter(context, adapter) } } private fun showMenu(profile: Profile) { val dialog = AppBottomSheetDialog(context) val binding = DialogProfilesMenuBinding .inflate(context.layoutInflater, dialog.window?.decorView as ViewGroup?, false) binding.master = this binding.self = dialog binding.profile = profile dialog.setContentView(binding.root) dialog.show() } fun requestUpdateAll() { requests.trySend(Request.UpdateAll) } fun requestCreate() { requests.trySend(Request.Create) } private fun requestActive(profile: Profile) { requests.trySend(Request.Active(profile)) } fun requestUpdate(dialog: Dialog, profile: Profile) { requests.trySend(Request.Update(profile)) dialog.dismiss() } fun requestEdit(dialog: Dialog, profile: Profile) { requests.trySend(Request.Edit(profile)) dialog.dismiss() } fun requestDuplicate(dialog: Dialog, profile: Profile) { requests.trySend(Request.Duplicate(profile)) dialog.dismiss() } fun requestDelete(dialog: Dialog, profile: Profile) { requests.trySend(Request.Delete(profile)) dialog.dismiss() } } ================================================ FILE: design/src/main/java/yos/clash/material/design/PropertiesDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.view.View import com.github.kr328.clash.core.model.FetchStatus import yos.clash.material.design.databinding.DesignPropertiesBinding import yos.clash.material.design.dialog.ModelProgressBarConfigure import yos.clash.material.design.dialog.requestModelTextInput import yos.clash.material.design.dialog.withModelProgressBar import yos.clash.material.design.util.* import yos.clash.material.service.model.Profile import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import java.util.concurrent.TimeUnit import kotlin.coroutines.resume class PropertiesDesign(context: Context) : Design(context) { sealed class Request { object Commit : Request() object BrowseFiles : Request() } private val binding = DesignPropertiesBinding .inflate(context.layoutInflater, context.root, false) override val root: View get() = binding.root var profile: Profile get() = binding.profile!! set(value) { binding.profile = value } val progressing: Boolean get() = binding.processing suspend fun withProcessing(executeTask: suspend (suspend (FetchStatus) -> Unit) -> Unit) { try { binding.processing = true context.withModelProgressBar { configure { isIndeterminate = true text = context.getString(R.string.initializing) } executeTask { configure { applyFrom(it) } } } } finally { binding.processing = false } } suspend fun requestExitWithoutSaving(): Boolean { return withContext(Dispatchers.Main) { suspendCancellableCoroutine { ctx -> val dialog = MaterialAlertDialogBuilder(context) .setTitle(R.string.exit_without_save) .setMessage(R.string.exit_without_save_warning) .setCancelable(true) .setPositiveButton(R.string.ok) { _, _ -> ctx.resume(true) } .setNegativeButton(R.string.cancel) { _, _ -> } .setOnDismissListener { if (!ctx.isCompleted) ctx.resume(false) } .show() ctx.invokeOnCancellation { dialog.dismiss() } } } } init { binding.self = this binding.activityBarLayout.applyFrom(context) binding.tips.text = context.getHtml(R.string.tips_properties) binding.scrollRoot.bindAppBarElevation(binding.activityBarLayout) } fun inputName() { launch { val name = context.requestModelTextInput( initial = profile.name, title = context.getText(R.string.name), hint = context.getText(R.string.properties), error = context.getText(R.string.should_not_be_blank), validator = ValidatorNotBlank ) if (name != profile.name) { profile = profile.copy(name = name) } } } fun inputUrl() { if (profile.type == Profile.Type.External) return launch { val url = context.requestModelTextInput( initial = profile.source, title = context.getText(R.string.url), hint = context.getText(R.string.profile_url), error = context.getText(R.string.accept_http_content), validator = ValidatorHttpUrl ) if (url != profile.source) { profile = profile.copy(source = url) } } } fun inputInterval() { launch { var minutes = TimeUnit.MILLISECONDS.toMinutes(profile.interval) minutes = context.requestModelTextInput( initial = if (minutes == 0L) "" else minutes.toString(), title = context.getText(R.string.auto_update), hint = context.getText(R.string.auto_update_minutes), error = context.getText(R.string.at_least_15_minutes), validator = ValidatorAutoUpdateInterval ).toLongOrNull() ?: 0 val interval = TimeUnit.MINUTES.toMillis(minutes) if (interval != profile.interval) { profile = profile.copy(interval = interval) } } } fun requestCommit() { requests.trySend(Request.Commit) } fun requestBrowseFiles() { requests.trySend(Request.BrowseFiles) } private fun ModelProgressBarConfigure.applyFrom(status: FetchStatus) { when (status.action) { FetchStatus.Action.FetchConfiguration -> { text = context.getString(R.string.format_fetching_configuration, status.args[0]) isIndeterminate = true } FetchStatus.Action.FetchProviders -> { text = context.getString(R.string.format_fetching_provider, status.args[0]) isIndeterminate = false max = status.max progress = status.progress } FetchStatus.Action.Verifying -> { text = context.getString(R.string.verifying) isIndeterminate = false max = status.max progress = status.progress } } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/ProvidersDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.view.View import com.github.kr328.clash.core.model.Provider import yos.clash.material.design.adapter.ProviderAdapter import yos.clash.material.design.databinding.DesignProvidersBinding import yos.clash.material.design.util.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class ProvidersDesign( context: Context, providers: List, ) : Design(context) { sealed class Request { data class Update(val index: Int, val provider: Provider) : Request() } private val binding = DesignProvidersBinding .inflate(context.layoutInflater, context.root, false) override val root: View get() = binding.root private val adapter = ProviderAdapter(context, providers) { index, provider -> requests.trySend(Request.Update(index, provider)) } fun updateElapsed() { adapter.updateElapsed() } suspend fun notifyUpdated(index: Int) { withContext(Dispatchers.Main) { adapter.notifyUpdated(index) } } suspend fun notifyChanged(index: Int) { withContext(Dispatchers.Main) { adapter.notifyChanged(index) } } init { binding.self = this binding.activityBarLayout.applyFrom(context) binding.mainList.recyclerList.bindAppBarElevation(binding.activityBarLayout) binding.mainList.recyclerList.applyLinearAdapter(context, adapter) } fun requestUpdateAll() { adapter.states.filter { !it.updating }.forEachIndexed { index, state -> state.updating = true requests.trySend(Request.Update(index, state.provider)) } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/ProxyDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.content.res.ColorStateList import android.view.View import android.widget.Toast import androidx.viewpager2.widget.ViewPager2 import com.github.kr328.clash.core.model.Proxy import com.github.kr328.clash.core.model.TunnelState import yos.clash.material.design.adapter.ProxyAdapter import yos.clash.material.design.adapter.ProxyPageAdapter import yos.clash.material.design.component.ProxyMenu import yos.clash.material.design.component.ProxyViewConfig import yos.clash.material.design.databinding.DesignProxyBinding import yos.clash.material.design.model.ProxyState import yos.clash.material.design.store.UiStore import yos.clash.material.design.util.applyFrom import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.resolveThemedColor import yos.clash.material.design.util.root import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.tabs.TabLayoutMediator import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class ProxyDesign( context: Context, overrideMode: TunnelState.Mode?, groupNames: List, uiStore: UiStore, ) : Design(context) { sealed class Request { object ReloadAll : Request() object ReLaunch : Request() data class PatchMode(val mode: TunnelState.Mode?) : Request() data class Reload(val index: Int) : Request() data class Select(val index: Int, val name: String) : Request() data class UrlTest(val index: Int) : Request() } private val binding = DesignProxyBinding .inflate(context.layoutInflater, context.root, false) private val config = ProxyViewConfig(context, uiStore.proxySingleLine) private val menu: ProxyMenu by lazy { ProxyMenu(context, binding.menuView, overrideMode, uiStore, requests) { config.singleLine = uiStore.proxySingleLine } } private val adapter: ProxyPageAdapter get() = binding.pagesView.adapter!! as ProxyPageAdapter private var horizontalScrolling = false private val verticalBottomScrolled: Boolean get() = adapter.states[binding.pagesView.currentItem].bottom private var urlTesting: Boolean get() = adapter.states[binding.pagesView.currentItem].urlTesting set(value) { adapter.states[binding.pagesView.currentItem].urlTesting = value } override val root: View = binding.root suspend fun updateGroup( position: Int, proxies: List, selectable: Boolean, parent: ProxyState, links: Map ) { adapter.updateAdapter(position, proxies, selectable, parent, links) adapter.states[position].urlTesting = false updateUrlTestButtonStatus() } suspend fun requestRedrawVisible() { withContext(Dispatchers.Main) { adapter.requestRedrawVisible() } } suspend fun requestDonate() { withContext(Dispatchers.Main) { val title = context.getText(R.string.request_donate) val message = context.getText(R.string.request_donate_tips) if (title.isNotEmpty() && message.isNotEmpty()) { MaterialAlertDialogBuilder(context) .setTitle(R.string.request_donate) .setMessage(R.string.request_donate_tips) .setPositiveButton(R.string.ok) { _, _ -> } .setCancelable(true) .show() } } } suspend fun showModeSwitchTips() { withContext(Dispatchers.Main) { Toast.makeText(context, R.string.mode_switch_tips, Toast.LENGTH_LONG).show() } } init { binding.self = this binding.activityBarLayout.applyFrom(context) binding.menuView.setOnClickListener { menu.show() } if (groupNames.isEmpty()) { binding.emptyView.visibility = View.VISIBLE binding.urlTestView.visibility = View.GONE binding.tabLayoutView.visibility = View.GONE binding.elevationView.visibility = View.GONE binding.pagesView.visibility = View.GONE binding.urlTestFloatView.visibility = View.GONE } else { binding.urlTestFloatView.supportImageTintList = ColorStateList.valueOf( context.resolveThemedColor(R.attr.colorOnPrimary) ) binding.pagesView.apply { adapter = ProxyPageAdapter( surface, config, List(groupNames.size) { index -> ProxyAdapter(config) { name -> requests.trySend(Request.Select(index, name)) } } ) { if (it == currentItem) updateUrlTestButtonStatus() } registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageScrollStateChanged(state: Int) { horizontalScrolling = state != ViewPager2.SCROLL_STATE_IDLE updateUrlTestButtonStatus() } override fun onPageSelected(position: Int) { uiStore.proxyLastGroup = groupNames[position] } }) } TabLayoutMediator(binding.tabLayoutView, binding.pagesView) { tab, index -> tab.text = groupNames[index] }.attach() val initialPosition = groupNames.indexOf(uiStore.proxyLastGroup) binding.pagesView.post { if (initialPosition > 0) binding.pagesView.setCurrentItem(initialPosition, false) } } } fun requestUrlTesting() { urlTesting = true requests.trySend(Request.UrlTest(binding.pagesView.currentItem)) updateUrlTestButtonStatus() } private fun updateUrlTestButtonStatus() { if (verticalBottomScrolled || horizontalScrolling || urlTesting) { binding.urlTestFloatView.hide() } else { binding.urlTestFloatView.show() } if (urlTesting) { binding.urlTestView.visibility = View.GONE binding.urlTestProgressView.visibility = View.VISIBLE } else { binding.urlTestView.visibility = View.VISIBLE binding.urlTestProgressView.visibility = View.GONE } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/SettingsDesign.kt ================================================ package yos.clash.material.design import android.content.Context import android.view.View import yos.clash.material.design.databinding.DesignSettingsBinding import yos.clash.material.design.util.applyFrom import yos.clash.material.design.util.bindAppBarElevation import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.root class SettingsDesign(context: Context) : Design(context) { enum class Request { StartApp, StartNetwork, StartOverride, } private val binding = DesignSettingsBinding .inflate(context.layoutInflater, context.root, false) override val root: View get() = binding.root init { binding.self = this binding.activityBarLayout.applyFrom(context) binding.scrollRoot.bindAppBarElevation(binding.activityBarLayout) } fun request(request: Request) { requests.trySend(request) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/YosConfigAchieve.kt ================================================ package yos.clash.material.design open class YosConfigAchieve { companion object { fun getIfPremium(): Boolean { return true } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/AppAdapter.kt ================================================ package yos.clash.material.design.adapter import android.content.Context import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.databinding.AdapterAppBinding import yos.clash.material.design.model.AppInfo import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.root class AppAdapter( private val context: Context, private val selected: MutableSet, ) : RecyclerView.Adapter() { class Holder(val binding: AdapterAppBinding) : RecyclerView.ViewHolder(binding.root) var apps: List = emptyList() fun rebindAll() { notifyItemRangeChanged(0, itemCount) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { return Holder( AdapterAppBinding .inflate(context.layoutInflater, context.root, false) ) } override fun onBindViewHolder(holder: Holder, position: Int) { val current = apps[position] holder.binding.app = current holder.binding.selected = current.packageName in selected holder.binding.root.setOnClickListener { if (holder.binding.selected) { selected.remove(current.packageName) holder.binding.selected = false } else { selected.add(current.packageName) holder.binding.selected = true } } } override fun getItemCount(): Int { return apps.size } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/EditableTextListAdapter.kt ================================================ package yos.clash.material.design.adapter import android.content.Context import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.databinding.AdapterEditableTextListBinding import yos.clash.material.design.preference.TextAdapter import yos.clash.material.design.util.layoutInflater class EditableTextListAdapter( private val context: Context, val values: MutableList, private val adapter: TextAdapter, ) : RecyclerView.Adapter() { class Holder(val binding: AdapterEditableTextListBinding) : RecyclerView.ViewHolder(binding.root) fun addElement(text: String) { val value = adapter.to(text) notifyItemInserted(values.size) values.add(value) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { return Holder( AdapterEditableTextListBinding .inflate(context.layoutInflater, parent, false) ) } override fun onBindViewHolder(holder: Holder, position: Int) { val current = values[position] holder.binding.textView.text = adapter.from(current) holder.binding.deleteView.setOnClickListener { val index = values.indexOf(current) if (index >= 0) { values.removeAt(index) notifyItemRemoved(index) } } } override fun getItemCount(): Int { return values.size } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/EditableTextMapAdapter.kt ================================================ package yos.clash.material.design.adapter import android.content.Context import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.databinding.AdapterEditableTextMapBinding import yos.clash.material.design.preference.TextAdapter import yos.clash.material.design.util.layoutInflater class EditableTextMapAdapter( private val context: Context, val values: MutableList>, private val keyAdapter: TextAdapter, private val valueAdapter: TextAdapter, ) : RecyclerView.Adapter() { class Holder(val binding: AdapterEditableTextMapBinding) : RecyclerView.ViewHolder(binding.root) fun addElement(key: String, value: String) { val keyValue = keyAdapter.to(key) val valueValue = valueAdapter.to(value) notifyItemInserted(values.size) values.add(keyValue to valueValue) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { return Holder( AdapterEditableTextMapBinding .inflate(context.layoutInflater, parent, false) ) } override fun onBindViewHolder(holder: Holder, position: Int) { val current = values[position] holder.binding.keyView.text = keyAdapter.from(current.first) holder.binding.valueView.text = valueAdapter.from(current.second) holder.binding.deleteView.setOnClickListener { val index = values.indexOf(current) if (index >= 0) { values.removeAt(index) notifyItemRemoved(index) } } } override fun getItemCount(): Int { return values.size } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/FileAdapter.kt ================================================ package yos.clash.material.design.adapter import android.content.Context import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.databinding.AdapterFileBinding import yos.clash.material.design.model.File import yos.clash.material.design.ui.ObservableCurrentTime import yos.clash.material.design.util.layoutInflater class FileAdapter( private val context: Context, private val open: (File) -> Unit, private val more: (File) -> Unit, ) : RecyclerView.Adapter() { class Holder(val binding: AdapterFileBinding) : RecyclerView.ViewHolder(binding.root) private val currentTime = ObservableCurrentTime() var files: List = emptyList() fun updateElapsed() { currentTime.update() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { return Holder( AdapterFileBinding .inflate(context.layoutInflater, parent, false) .also { it.currentTime = currentTime } ) } override fun onBindViewHolder(holder: Holder, position: Int) { val current = files[position] holder.binding.apply { file = current setOpen { open(current) } setMore { more(current) } } } override fun getItemCount(): Int { return files.size } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/LogFileAdapter.kt ================================================ package yos.clash.material.design.adapter import android.content.Context import android.view.ViewGroup import android.view.ViewGroup.LayoutParams import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.model.LogFile import yos.clash.material.design.util.format import yos.clash.material.design.view.ActionLabel class LogFileAdapter( private val context: Context, private val open: (LogFile) -> Unit, ) : RecyclerView.Adapter() { class Holder(val label: ActionLabel) : RecyclerView.ViewHolder(label) var logs: List = emptyList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { return Holder(ActionLabel(context).apply { layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT) }) } override fun onBindViewHolder(holder: Holder, position: Int) { val current = logs[position] holder.label.text = current.fileName holder.label.subtext = current.date.format(context) holder.label.setOnClickListener { open(current) } holder.label.icon = null } override fun getItemCount(): Int { return logs.size } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/LogMessageAdapter.kt ================================================ package yos.clash.material.design.adapter import android.content.Context import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.github.kr328.clash.core.model.LogMessage import yos.clash.material.design.databinding.AdapterLogMessageBinding import yos.clash.material.design.util.layoutInflater class LogMessageAdapter( private val context: Context, private val copy: (LogMessage) -> Unit, ) : RecyclerView.Adapter() { class Holder(val binding: AdapterLogMessageBinding) : RecyclerView.ViewHolder(binding.root) var messages: List = emptyList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { return Holder( AdapterLogMessageBinding .inflate(context.layoutInflater, parent, false) ) } override fun onBindViewHolder(holder: Holder, position: Int) { val current = messages[position] holder.binding.message = current holder.binding.root.setOnLongClickListener { copy(current) true } } override fun getItemCount(): Int { return messages.size } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/PopupListAdapter.kt ================================================ package yos.clash.material.design.adapter import android.content.Context import android.graphics.Color import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import yos.clash.material.design.R import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.resolveThemedColor class PopupListAdapter( private val context: Context, private val texts: List, private val selected: Int, ) : BaseAdapter() { private val colorPrimary = context.resolveThemedColor(R.attr.colorPrimary) private val colorOnPrimary = context.resolveThemedColor(R.attr.colorOnPrimary) private val colorControlNormal = context.resolveThemedColor(R.attr.colorControlNormal) override fun getCount(): Int { return texts.size } override fun getItem(position: Int): Any { return texts[position] } override fun getItemId(position: Int): Long { return texts[position].hashCode().toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val view = convertView ?: context.layoutInflater .inflate(android.R.layout.simple_list_item_1, parent, false) val text: TextView = view.findViewById(android.R.id.text1) text.text = texts[position] if (position == selected) { text.setBackgroundColor( Color.argb( 200, Color.red(colorPrimary), Color.green(colorPrimary), Color.blue(colorPrimary) ) ) text.setTextColor(colorOnPrimary) } else { text.setBackgroundColor(Color.TRANSPARENT) text.setTextColor(colorControlNormal) } return view } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/ProfileAdapter.kt ================================================ package yos.clash.material.design.adapter import android.content.Context import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.databinding.AdapterProfileBinding import yos.clash.material.design.ui.ObservableCurrentTime import yos.clash.material.design.util.layoutInflater import yos.clash.material.service.model.Profile class ProfileAdapter( private val context: Context, private val onClicked: (Profile) -> Unit, private val onMenuClicked: (Profile) -> Unit, ) : RecyclerView.Adapter() { class Holder(val binding: AdapterProfileBinding) : RecyclerView.ViewHolder(binding.root) private val currentTime = ObservableCurrentTime() var profiles: List = emptyList() fun updateElapsed() { currentTime.update() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { return Holder( AdapterProfileBinding .inflate(context.layoutInflater, parent, false) .also { it.currentTime = currentTime } ) } override fun onBindViewHolder(holder: Holder, position: Int) { val current = profiles[position] val binding = holder.binding if (current === binding.profile) return binding.profile = current binding.setClicked { onClicked(current) } binding.setMenu { onMenuClicked(current) } } override fun getItemCount(): Int { return profiles.size } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/ProfileProviderAdapter.kt ================================================ package yos.clash.material.design.adapter import android.content.Context import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.databinding.AdapterProfileProviderBinding import yos.clash.material.design.model.ProfileProvider import yos.clash.material.design.util.layoutInflater class ProfileProviderAdapter( private val context: Context, private val select: (ProfileProvider) -> Unit, private val detail: (ProfileProvider) -> Boolean, ) : RecyclerView.Adapter() { class Holder(val binding: AdapterProfileProviderBinding) : RecyclerView.ViewHolder(binding.root) var providers: List = emptyList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { return Holder( AdapterProfileProviderBinding.inflate( context.layoutInflater, parent, false ) ) } override fun onBindViewHolder(holder: Holder, position: Int) { val current = providers[position] val binding = holder.binding binding.provider = current binding.root.apply { setOnClickListener { select(current) } setOnLongClickListener { detail(current) } } } override fun getItemCount(): Int { return providers.size } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/ProviderAdapter.kt ================================================ package yos.clash.material.design.adapter import android.content.Context import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.github.kr328.clash.core.model.Provider import yos.clash.material.design.databinding.AdapterProviderBinding import yos.clash.material.design.model.ProviderState import yos.clash.material.design.ui.ObservableCurrentTime import yos.clash.material.design.util.layoutInflater class ProviderAdapter( private val context: Context, providers: List, private val requestUpdate: (Int, Provider) -> Unit, ) : RecyclerView.Adapter() { class Holder(val binding: AdapterProviderBinding) : RecyclerView.ViewHolder(binding.root) private val currentTime = ObservableCurrentTime() val states = providers.map { ProviderState(it, it.updatedAt, false) } fun updateElapsed() { currentTime.update() } fun notifyUpdated(index: Int) { states[index].apply { updating = false } notifyItemChanged(index) } fun notifyChanged(index: Int) { states[index].apply { updating = false updatedAt = System.currentTimeMillis() } notifyItemChanged(index) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { return Holder( AdapterProviderBinding .inflate(context.layoutInflater, parent, false) .also { it.currentTime = currentTime } ) } override fun onBindViewHolder(holder: Holder, position: Int) { val state = states[position] holder.binding.provider = state.provider holder.binding.state = state holder.binding.update = View.OnClickListener { state.updating = true requestUpdate(position, state.provider) } } override fun getItemCount(): Int { return states.size } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/ProxyAdapter.kt ================================================ package yos.clash.material.design.adapter import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.component.ProxyView import yos.clash.material.design.component.ProxyViewConfig import yos.clash.material.design.component.ProxyViewState class ProxyAdapter( private val config: ProxyViewConfig, private val clicked: (String) -> Unit, ) : RecyclerView.Adapter() { class Holder(val view: ProxyView) : RecyclerView.ViewHolder(view) var selectable: Boolean = false var states: List = emptyList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { return Holder(ProxyView(config.context, config)) } override fun onBindViewHolder(holder: Holder, position: Int) { val current = states[position] holder.view.apply { state = current setOnClickListener { clicked(current.proxy.name) } val isSelector = selectable isFocusable = isSelector isClickable = isSelector current.update(true) } } override fun getItemCount(): Int { return states.size } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/ProxyPageAdapter.kt ================================================ package yos.clash.material.design.adapter import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.github.kr328.clash.core.model.Proxy import yos.clash.material.design.R import yos.clash.material.design.component.ProxyPageFactory import yos.clash.material.design.component.ProxyViewConfig import yos.clash.material.design.component.ProxyViewState import yos.clash.material.design.model.ProxyPageState import yos.clash.material.design.model.ProxyState import yos.clash.material.design.ui.Surface import yos.clash.material.design.util.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class ProxyPageAdapter( private val surface: Surface, private val config: ProxyViewConfig, private val adapters: List, private val stateChanged: (Int) -> Unit, ) : RecyclerView.Adapter() { private val factory = ProxyPageFactory(config) private var parent: RecyclerView? = null val states = List(adapters.size) { ProxyPageState() } suspend fun updateAdapter( position: Int, proxies: List, selectable: Boolean, parent: ProxyState, links: Map ) { val states = withContext(Dispatchers.Default) { proxies.map { val link = if (it.type.group) links[it.name] else null ProxyViewState(config, it, parent, link) } } withContext(Dispatchers.Main) { adapters[position].apply { this.selectable = selectable this.swapDataSet(this::states, states, false) } requestRedrawVisible() } } fun requestRedrawVisible() { factory.fromRoot(parent?.firstVisibleView ?: return) .recyclerView.invalidateChildren() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProxyPageFactory.Holder { val holder = factory.newInstance() val toolbarHeight = config.context.getPixels(R.dimen.toolbar_height) val tabHeight = config.context.getPixels(R.dimen.tab_layout_height) holder.recyclerView.bindInsets(surface, toolbarHeight + tabHeight) holder.recyclerView.addScrolledToBottomObserver { view, bottom -> val position = view.position val state = states[position] if (state.bottom != bottom) { state.bottom = bottom stateChanged(position) } } return holder } override fun onBindViewHolder(holder: ProxyPageFactory.Holder, position: Int) { val adapter = adapters[position] states[position].bottom = false holder.recyclerView.apply { this.position = position this.swapAdapter(adapter, false) } } override fun getItemCount(): Int { return adapters.size } override fun onAttachedToRecyclerView(recyclerView: RecyclerView) { this.parent = recyclerView recyclerView.isFocusable = false } override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) { this.parent = null } private var RecyclerView.position: Int get() { return tag as? Int ?: -1 } set(value) { tag = value } } ================================================ FILE: design/src/main/java/yos/clash/material/design/adapter/SideloadProviderAdapter.kt ================================================ package yos.clash.material.design.adapter import android.content.Context import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.databinding.AdapterSideloadProviderBinding import yos.clash.material.design.model.AppInfo import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.root class SideloadProviderAdapter( private val context: Context, private val apps: List, var selectedPackageName: String ) : RecyclerView.Adapter() { class Holder(val binding: AdapterSideloadProviderBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { return Holder( AdapterSideloadProviderBinding .inflate(context.layoutInflater, context.root, false) ) } override fun onBindViewHolder(holder: Holder, position: Int) { val current = apps[position] holder.binding.appInfo = current holder.binding.selected = selectedPackageName == current.packageName holder.binding.root.setOnClickListener { val index = apps.indexOfFirst { it.packageName == selectedPackageName } selectedPackageName = current.packageName if (index >= 0) notifyItemChanged(index) notifyItemChanged(position) } } override fun getItemCount(): Int { return apps.size } } ================================================ FILE: design/src/main/java/yos/clash/material/design/component/AccessControlMenu.kt ================================================ package yos.clash.material.design.component import android.content.Context import android.view.MenuItem import android.view.View import androidx.appcompat.widget.PopupMenu import yos.clash.material.design.AccessControlDesign.Request import yos.clash.material.design.R import yos.clash.material.design.model.AppInfoSort import yos.clash.material.design.store.UiStore import kotlinx.coroutines.channels.Channel class AccessControlMenu( context: Context, menuView: View, private val uiStore: UiStore, private val requests: Channel, ) : PopupMenu.OnMenuItemClickListener { private val menu = PopupMenu(context, menuView) fun show() { menu.show() } override fun onMenuItemClick(item: MenuItem): Boolean { if (item.isCheckable) item.isChecked = !item.isChecked when (item.itemId) { R.id.select_all -> requests.trySend(Request.SelectAll) R.id.select_none -> requests.trySend(Request.SelectNone) R.id.select_invert -> requests.trySend(Request.SelectInvert) R.id.system_apps -> { uiStore.accessControlSystemApp = !item.isChecked requests.trySend(Request.ReloadApps) } R.id.name -> { uiStore.accessControlSort = AppInfoSort.Label requests.trySend(Request.ReloadApps) } R.id.package_name -> { uiStore.accessControlSort = AppInfoSort.PackageName requests.trySend(Request.ReloadApps) } R.id.install_time -> { uiStore.accessControlSort = AppInfoSort.InstallTime requests.trySend(Request.ReloadApps) } R.id.update_time -> { uiStore.accessControlSort = AppInfoSort.UpdateTime requests.trySend(Request.ReloadApps) } R.id.reverse -> { uiStore.accessControlReverse = item.isChecked requests.trySend(Request.ReloadApps) } R.id.import_from_clipboard -> { requests.trySend(Request.Import) } R.id.export_to_clipboard -> { requests.trySend(Request.Export) } else -> return false } return true } init { menu.menuInflater.inflate(R.menu.menu_access_control, menu.menu) when (uiStore.accessControlSort) { AppInfoSort.Label -> menu.menu.findItem(R.id.name).isChecked = true AppInfoSort.PackageName -> menu.menu.findItem(R.id.package_name).isChecked = true AppInfoSort.InstallTime -> menu.menu.findItem(R.id.install_time).isChecked = true AppInfoSort.UpdateTime -> menu.menu.findItem(R.id.update_time).isChecked = true } menu.menu.findItem(R.id.system_apps).isChecked = !uiStore.accessControlSystemApp menu.menu.findItem(R.id.reverse).isChecked = uiStore.accessControlReverse menu.setOnMenuItemClickListener(this) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/component/ProxyMenu.kt ================================================ package yos.clash.material.design.component import android.content.Context import android.view.MenuItem import android.view.View import androidx.appcompat.widget.PopupMenu import com.github.kr328.clash.core.model.ProxySort import com.github.kr328.clash.core.model.TunnelState import yos.clash.material.design.ProxyDesign import yos.clash.material.design.R import yos.clash.material.design.store.UiStore import kotlinx.coroutines.channels.Channel import yos.clash.material.design.YosConfigAchieve class ProxyMenu( context: Context, menuView: View, mode: TunnelState.Mode?, private val uiStore: UiStore, private val requests: Channel, private val updateConfig: () -> Unit, ) : PopupMenu.OnMenuItemClickListener { private val menu = PopupMenu(context, menuView) fun show() { menu.show() } override fun onMenuItemClick(item: MenuItem): Boolean { item.isChecked = !item.isChecked when (item.itemId) { R.id.not_selectable -> { uiStore.proxyExcludeNotSelectable = item.isChecked requests.trySend(ProxyDesign.Request.ReLaunch) } R.id.single -> { uiStore.proxySingleLine = true updateConfig() requests.trySend(ProxyDesign.Request.ReloadAll) } R.id.multiple -> { uiStore.proxySingleLine = false updateConfig() requests.trySend(ProxyDesign.Request.ReloadAll) } R.id.default_ -> { uiStore.proxySort = ProxySort.Default requests.trySend(ProxyDesign.Request.ReloadAll) } R.id.name -> { uiStore.proxySort = ProxySort.Title requests.trySend(ProxyDesign.Request.ReloadAll) } R.id.delay -> { uiStore.proxySort = ProxySort.Delay requests.trySend(ProxyDesign.Request.ReloadAll) } R.id.dont_modify -> { requests.trySend(ProxyDesign.Request.PatchMode(null)) } R.id.direct_mode -> { requests.trySend(ProxyDesign.Request.PatchMode(TunnelState.Mode.Direct)) } R.id.global_mode -> { requests.trySend(ProxyDesign.Request.PatchMode(TunnelState.Mode.Global)) } R.id.rule_mode -> { requests.trySend(ProxyDesign.Request.PatchMode(TunnelState.Mode.Rule)) } R.id.script_mode -> { requests.trySend(ProxyDesign.Request.PatchMode(TunnelState.Mode.Script)) } else -> return false } return true } init { menu.menuInflater.inflate(R.menu.menu_proxy, menu.menu) menu.menu.apply { findItem(R.id.script_mode).isVisible = YosConfigAchieve.getIfPremium() findItem(R.id.not_selectable).isChecked = uiStore.proxyExcludeNotSelectable if (uiStore.proxySingleLine) { findItem(R.id.single).isChecked = true } else { findItem(R.id.multiple).isChecked = true } when (uiStore.proxySort) { ProxySort.Default -> findItem(R.id.default_).isChecked = true ProxySort.Title -> findItem(R.id.name).isChecked = true ProxySort.Delay -> findItem(R.id.delay).isChecked = true } when (mode) { null -> findItem(R.id.dont_modify).isChecked = true TunnelState.Mode.Direct -> findItem(R.id.direct_mode).isChecked = true TunnelState.Mode.Global -> findItem(R.id.global_mode).isChecked = true TunnelState.Mode.Rule -> findItem(R.id.rule_mode).isChecked = true TunnelState.Mode.Script -> findItem(R.id.script_mode).isChecked = true } } menu.setOnMenuItemClickListener(this) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/component/ProxyPageFactory.kt ================================================ package yos.clash.material.design.component import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.view.VerticalScrollableHost class ProxyPageFactory(private val config: ProxyViewConfig) { class Holder( val recyclerView: RecyclerView, val root: View, ) : RecyclerView.ViewHolder(root) private val childrenPool = RecyclerView.RecycledViewPool() fun newInstance(): Holder { val root = VerticalScrollableHost(config.context).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) } val recyclerView = RecyclerView(config.context).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) } root.addView(recyclerView) recyclerView.apply { layoutManager = GridLayoutManager(config.context, 2).apply { spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { return if (config.singleLine) 2 else 1 } } } setRecycledViewPool(childrenPool) clipToPadding = false } return Holder(recyclerView, root).apply { root.tag = this } } fun fromRoot(root: View): Holder { return root.tag!! as Holder } } ================================================ FILE: design/src/main/java/yos/clash/material/design/component/ProxyView.kt ================================================ package yos.clash.material.design.component import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import android.view.View import yos.clash.material.common.compat.getDrawableCompat class ProxyView( context: Context, config: ProxyViewConfig, ) : View(context) { constructor(context: Context) : this(context, ProxyViewConfig(context, false)) init { background = context.getDrawableCompat(config.clickableBackground) } var state: ProxyViewState? = null override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val state = state ?: return super.onMeasure(widthMeasureSpec, heightMeasureSpec) val width = when (MeasureSpec.getMode(widthMeasureSpec)) { MeasureSpec.UNSPECIFIED -> resources.displayMetrics.widthPixels MeasureSpec.AT_MOST, MeasureSpec.EXACTLY -> MeasureSpec.getSize(widthMeasureSpec) else -> throw IllegalArgumentException("invalid measure spec") } state.paint.apply { reset() textSize = state.config.textSize getTextBounds("Stub!", 0, 1, state.rect) } val textHeight = state.rect.height() val exceptHeight = (state.config.layoutPadding * 2 + state.config.contentPadding * 2 + textHeight * 2 + state.config.textMargin).toInt() val height = when (MeasureSpec.getMode(heightMeasureSpec)) { MeasureSpec.UNSPECIFIED -> exceptHeight MeasureSpec.AT_MOST, MeasureSpec.EXACTLY -> exceptHeight.coerceAtMost(MeasureSpec.getSize(heightMeasureSpec)) else -> throw IllegalArgumentException("invalid measure spec") } setMeasuredDimension(width, height) } override fun draw(canvas: Canvas) { val state = state ?: return super.draw(canvas) if (state.update(false)) postInvalidate() val width = width.toFloat() val height = height.toFloat() val paint = state.paint paint.reset() paint.color = state.background paint.style = Paint.Style.FILL // draw background canvas.apply { if (state.config.singleLine) { drawRect(0f, 0f, width, height, paint) } else { val path = state.path path.reset() path.addRoundRect( state.config.layoutPadding, state.config.layoutPadding, width - state.config.layoutPadding, height - state.config.layoutPadding, state.config.cardRadius, state.config.cardRadius, Path.Direction.CW, ) paint.setShadowLayer( state.config.cardRadius, state.config.cardOffset, state.config.cardOffset, state.config.shadow ) drawPath(path, paint) clipPath(path) } } super.draw(canvas) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val state = state ?: return val paint = state.paint val width = width.toFloat() val height = height.toFloat() paint.textSize = state.config.textSize // measure delay text bounds val delayCount = paint.breakText( state.delayText, false, (width - state.config.layoutPadding * 2 - state.config.contentPadding * 2) .coerceAtLeast(0f), null ) state.paint.getTextBounds(state.delayText, 0, delayCount, state.rect) val delayWidth = state.rect.width() val mainTextWidth = (width - state.config.layoutPadding * 2 - state.config.contentPadding * 2 - delayWidth - state.config.textMargin * 2 ) .coerceAtLeast(0f) // measure title text bounds val titleCount = paint.breakText( state.title, false, mainTextWidth, null, ) // measure subtitle text bounds val subtitleCount = paint.breakText( state.subtitle, false, mainTextWidth, null, ) // text draw measure val textOffset = (paint.descent() + paint.ascent()) / 2 paint.reset() paint.textSize = state.config.textSize paint.isAntiAlias = true paint.color = state.controls // draw delay canvas.apply { val x = width - state.config.layoutPadding - state.config.contentPadding - delayWidth val y = height / 2f - textOffset drawText(state.delayText, 0, delayCount, x, y, paint) } // draw title canvas.apply { val x = state.config.layoutPadding + state.config.contentPadding val y = state.config.layoutPadding + (height - state.config.layoutPadding * 2) / 3f - textOffset drawText(state.title, 0, titleCount, x, y, paint) } // draw subtitle canvas.apply { val x = state.config.layoutPadding + state.config.contentPadding val y = state.config.layoutPadding + (height - state.config.layoutPadding * 2) / 3f * 2 - textOffset drawText(state.subtitle, 0, subtitleCount, x, y, paint) } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/component/ProxyViewConfig.kt ================================================ package yos.clash.material.design.component import android.content.Context import android.graphics.Color import yos.clash.material.design.R import yos.clash.material.design.util.getPixels import yos.clash.material.design.util.resolveThemedColor import yos.clash.material.design.util.resolveThemedResourceId class ProxyViewConfig(val context: Context, var singleLine: Boolean) { private val colorSurface = context.resolveThemedColor(R.attr.colorSurface) val clickableBackground = context.resolveThemedResourceId(android.R.attr.selectableItemBackground) val selectedControl = context.resolveThemedColor(R.attr.colorOnPrimary) val selectedBackground = context.resolveThemedColor(R.attr.colorPrimary) val unselectedControl = context.resolveThemedColor(R.attr.colorOnSurface) val unselectedBackground: Int get() = if (singleLine) Color.TRANSPARENT else colorSurface val layoutPadding = context.getPixels(R.dimen.proxy_layout_padding).toFloat() val contentPadding = context.getPixels(R.dimen.proxy_content_padding).toFloat() val textMargin = context.getPixels(R.dimen.proxy_text_margin) val textSize = context.getPixels(R.dimen.proxy_text_size).toFloat() val shadow = Color.argb( 0x15, Color.red(Color.DKGRAY), Color.green(Color.DKGRAY), Color.blue(Color.DKGRAY), ) val cardRadius = context.getPixels(R.dimen.proxy_card_radius).toFloat() var cardOffset = context.getPixels(R.dimen.proxy_card_offset).toFloat() } ================================================ FILE: design/src/main/java/yos/clash/material/design/component/ProxyViewState.kt ================================================ package yos.clash.material.design.component import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.graphics.Rect import com.github.kr328.clash.core.model.Proxy import yos.clash.material.design.model.ProxyState import kotlin.math.absoluteValue import kotlin.math.max class ProxyViewState( val config: ProxyViewConfig, val proxy: Proxy, private val parent: ProxyState, private val link: ProxyState? ) { val paint = Paint() val rect = Rect() val path = Path() var title: String = "" var subtitle: String = "" var delayText: String = "" var background: Int = config.unselectedBackground var controls: Int = config.unselectedControl private var delay: Int = 0 private var selected: Boolean = false private var parentNow: String = "" private var linkNow: String? = null private var lastFrameTime = System.currentTimeMillis() fun update(snap: Boolean): Boolean { val frameTime = System.currentTimeMillis() var invalidate = false if (proxy.type.group) { title = proxy.name if (link == null) { subtitle = proxy.type.name } else { if (linkNow !== link.now) { linkNow = link.now subtitle = "%s(%s)".format( proxy.type.name, link.now.ifEmpty { "*" } ) } } } else { title = proxy.title subtitle = proxy.subtitle } if (delay != proxy.delay) { delay = proxy.delay delayText = if (proxy.delay in 0..Short.MAX_VALUE) proxy.delay.toString() else "" } if (parentNow !== parent.now) { parentNow = parent.now selected = proxy.name == parent.now } controls = if (selected) config.selectedControl else config.unselectedControl if (snap) { background = if (selected) config.selectedBackground else config.unselectedBackground } else { val target = if (selected) config.selectedBackground else config.unselectedBackground if (background != target) { val sa = Color.alpha(background) val sr = Color.red(background) val sg = Color.green(background) val sb = Color.blue(background) val ta = Color.alpha(target) val tr = Color.red(target) val tg = Color.green(target) val tb = Color.blue(target) val da = ta - sa val dr = tr - sr val dg = tg - sg val db = tb - sb val max = max( da.absoluteValue, max( dr.absoluteValue, max( dg.absoluteValue, db.absoluteValue ) ) ) val frameOffset = frameTime - lastFrameTime val colorOffset = (frameOffset / max.toFloat().coerceAtLeast(0.001f)) .coerceIn(0.0f, 1.0f) background = if (colorOffset > 0.999f) { target } else { Color.argb( (sa + da * colorOffset).toInt(), (sr + dr * colorOffset).toInt(), (sg + dg * colorOffset).toInt(), (sb + db * colorOffset).toInt() ) } invalidate = true } } lastFrameTime = frameTime return invalidate } } ================================================ FILE: design/src/main/java/yos/clash/material/design/dialog/Dialogs.kt ================================================ package yos.clash.material.design.dialog import android.app.Dialog import android.content.Context import android.os.Bundle import android.view.ViewGroup import android.view.WindowManager import android.widget.FrameLayout import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.ViewCompat import yos.clash.material.common.compat.isAllowForceDarkCompat import yos.clash.material.common.compat.isSystemBarsTranslucentCompat import yos.clash.material.design.R import yos.clash.material.design.ui.Insets import yos.clash.material.design.ui.Surface import yos.clash.material.design.util.getPixels import yos.clash.material.design.util.resolveThemedResourceId import yos.clash.material.design.util.setOnInsertsChangedListener import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog class AppBottomSheetDialog(context: Context) : BottomSheetDialog(context) { private var insets: Insets = Insets.EMPTY override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setCancelable(true) window!!.apply { isSystemBarsTranslucentCompat = true isAllowForceDarkCompat = false } findViewById(com.google.android.material.R.id.container)?.apply { fitsSystemWindows = false } findViewById(com.google.android.material.R.id.design_bottom_sheet)?.apply { setOnInsertsChangedListener { if (insets != it) { insets = it (layoutParams as CoordinatorLayout.LayoutParams).also { params -> if (ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_LTR) { params.setMargins(it.start, 0, it.end, 0) } else { params.setMargins(it.end, 0, it.start, 0) } val top = context.getPixels(R.dimen.bottom_sheet_background_padding_top) val height = context.getPixels(R.dimen.bottom_sheet_header_height) setPaddingRelative( 0, top * 2 + height, 0, it.bottom ) } } } } setOnShowListener { behavior.halfExpandedRatio = 0.99f behavior.state = BottomSheetBehavior.STATE_EXPANDED } } } class FullScreenDialog( context: Context ) : Dialog(context, context.resolveThemedResourceId(R.attr.fullScreenDialogTheme)) { val surface = Surface() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window!!.apply { isSystemBarsTranslucentCompat = true setLayout( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT ) decorView.setOnInsertsChangedListener { if (surface.insets != it) surface.insets = it } } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/dialog/Input.kt ================================================ package yos.clash.material.design.dialog import android.content.Context import androidx.appcompat.app.AlertDialog import androidx.core.widget.doOnTextChanged import yos.clash.material.design.R import yos.clash.material.design.databinding.DialogTextFieldBinding import yos.clash.material.design.util.* import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume suspend fun Context.requestModelTextInput( initial: String, title: CharSequence, hint: CharSequence? = null, error: CharSequence? = null, validator: Validator = ValidatorAcceptAll, ): String { return this.requestModelTextInput(initial, title, null, hint, error, validator)!! } suspend fun Context.requestModelTextInput( initial: String?, title: CharSequence, reset: CharSequence?, hint: CharSequence? = null, error: CharSequence? = null, validator: Validator = ValidatorAcceptAll, ): String? { return suspendCancellableCoroutine { val binding = DialogTextFieldBinding .inflate(layoutInflater, this.root, false) val builder = MaterialAlertDialogBuilder(this) .setTitle(title) .setView(binding.root) .setCancelable(true) .setPositiveButton(R.string.ok) { _, _ -> val text = binding.textField.text?.toString() ?: "" if (validator(text)) it.resume(text) else it.resume(initial) } .setNegativeButton(R.string.cancel) { _, _ -> } .setOnDismissListener { _ -> if (!it.isCompleted) it.resume(initial) } if (reset != null) { builder.setNeutralButton(reset) { _, _ -> it.resume(null) } } val dialog = builder.create() it.invokeOnCancellation { dialog.dismiss() } dialog.setOnShowListener { if (hint != null) binding.textLayout.hint = hint binding.textField.apply { binding.textLayout.isErrorEnabled = error != null doOnTextChanged { text, _, _, _ -> if (!validator(text?.toString() ?: "")) { if (error != null) binding.textLayout.error = error dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false } else { if (error != null) binding.textLayout.error = null dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = true } } setText(initial) setSelection(0, initial?.length ?: 0) requestTextInput() } } dialog.show() } } ================================================ FILE: design/src/main/java/yos/clash/material/design/dialog/Progress.kt ================================================ package yos.clash.material.design.dialog import android.content.Context import yos.clash.material.design.databinding.DialogFetchStatusBinding import yos.clash.material.design.util.layoutInflater import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext interface ModelProgressBarConfigure { var isIndeterminate: Boolean var text: String? var progress: Int var max: Int } interface ModelProgressBarScope { suspend fun configure(block: suspend ModelProgressBarConfigure.() -> Unit) } suspend fun Context.withModelProgressBar(block: suspend ModelProgressBarScope.() -> Unit) { val view = DialogFetchStatusBinding.inflate(this.layoutInflater) val dialog = MaterialAlertDialogBuilder(this) .setCancelable(false) .setView(view.root) .show() val configureImpl = object : ModelProgressBarConfigure { override var isIndeterminate: Boolean get() = view.progressIndicator.isIndeterminate set(value) { view.progressIndicator.isIndeterminate = value } override var text: String? get() = view.text.text?.toString() set(value) { view.text.text = value } override var progress: Int get() = view.progressIndicator.progress set(value) { view.progressIndicator.setProgressCompat(value, true) } override var max: Int get() = view.progressIndicator.max set(value) { view.progressIndicator.max = value } } val scopeImpl = object : ModelProgressBarScope { override suspend fun configure(block: suspend ModelProgressBarConfigure.() -> Unit) { withContext(Dispatchers.Main) { configureImpl.block() } } } try { scopeImpl.block() } finally { dialog.dismiss() } } ================================================ FILE: design/src/main/java/yos/clash/material/design/model/AppInfo.kt ================================================ package yos.clash.material.design.model import android.graphics.drawable.Drawable data class AppInfo( val packageName: String, val label: String, val icon: Drawable, val installTime: Long, val updateDate: Long, ) ================================================ FILE: design/src/main/java/yos/clash/material/design/model/AppInfoSort.kt ================================================ package yos.clash.material.design.model enum class AppInfoSort(comparator: Comparator) : Comparator by comparator { Label(compareBy(AppInfo::label)), PackageName(compareBy(AppInfo::packageName)), InstallTime(compareBy(AppInfo::installTime)), UpdateTime(compareBy(AppInfo::updateDate)), } ================================================ FILE: design/src/main/java/yos/clash/material/design/model/Behavior.kt ================================================ package yos.clash.material.design.model interface Behavior { var autoRestart: Boolean } ================================================ FILE: design/src/main/java/yos/clash/material/design/model/DarkMode.kt ================================================ package yos.clash.material.design.model enum class DarkMode { Auto, ForceLight, ForceDark } ================================================ FILE: design/src/main/java/yos/clash/material/design/model/File.kt ================================================ package yos.clash.material.design.model data class File( val id: String, val name: String, val size: Long, val lastModified: Long, val isDirectory: Boolean ) ================================================ FILE: design/src/main/java/yos/clash/material/design/model/LogFile.kt ================================================ package yos.clash.material.design.model import java.util.* data class LogFile(val fileName: String, val date: Date) { companion object { private val REGEX_FILE = Regex("clash-(\\d+).log") private const val FORMAT_FILE_NAME = "clash-%d.log" fun parseFromFileName(fileName: String): LogFile? { return REGEX_FILE.matchEntire(fileName)?.run { LogFile(fileName, Date(groupValues[1].toLong())) } } fun generate(): LogFile { val current = Date() val fileName = FORMAT_FILE_NAME.format(current.time) return LogFile(fileName, current) } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/model/ProfileProvider.kt ================================================ package yos.clash.material.design.model import android.content.Context import android.content.Intent import android.graphics.drawable.Drawable import yos.clash.material.common.compat.getDrawableCompat import yos.clash.material.design.R sealed class ProfileProvider { class File(private val context: Context) : ProfileProvider() { override val name: String get() = context.getString(R.string.file) override val summary: String get() = context.getString(R.string.import_from_file) override val icon: Drawable? get() = context.getDrawableCompat(R.drawable.ic_baseline_attach_file) } class Url(private val context: Context) : ProfileProvider() { override val name: String get() = context.getString(R.string.url) override val summary: String get() = context.getString(R.string.import_from_url) override val icon: Drawable? get() = context.getDrawableCompat(R.drawable.ic_baseline_cloud_download) } class External( override val name: String, override val summary: String, override val icon: Drawable?, val intent: Intent, ) : ProfileProvider() abstract val name: String abstract val summary: String abstract val icon: Drawable? } ================================================ FILE: design/src/main/java/yos/clash/material/design/model/ProviderState.kt ================================================ package yos.clash.material.design.model import androidx.databinding.BaseObservable import androidx.databinding.Bindable import com.github.kr328.clash.core.model.Provider import yos.clash.material.design.BR class ProviderState( val provider: Provider, updatedAt: Long, updating: Boolean, ) : BaseObservable() { var updatedAt: Long = updatedAt @Bindable get set(value) { field = value notifyPropertyChanged(BR.updatedAt) } var updating: Boolean = updating @Bindable get set(value) { field = value notifyPropertyChanged(BR.updating) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/model/ProxyPageState.kt ================================================ package yos.clash.material.design.model class ProxyPageState { var bottom = false var urlTesting = false } ================================================ FILE: design/src/main/java/yos/clash/material/design/model/ProxyState.kt ================================================ package yos.clash.material.design.model data class ProxyState(var now: String) ================================================ FILE: design/src/main/java/yos/clash/material/design/preference/Category.kt ================================================ package yos.clash.material.design.preference import android.view.View import androidx.annotation.StringRes import yos.clash.material.design.databinding.PreferenceCategoryBinding import yos.clash.material.design.util.layoutInflater fun PreferenceScreen.category( @StringRes text: Int, ) { val binding = PreferenceCategoryBinding .inflate(context.layoutInflater, root, false) binding.textView.text = context.getString(text) addElement(object : Preference { override val view: View get() = binding.root override var enabled: Boolean get() = binding.root.isEnabled set(value) { binding.root.isEnabled = value } }) } ================================================ FILE: design/src/main/java/yos/clash/material/design/preference/Clickable.kt ================================================ package yos.clash.material.design.preference import android.graphics.drawable.Drawable import android.view.View import androidx.annotation.DrawableRes import androidx.annotation.StringRes import yos.clash.material.common.compat.getDrawableCompat import yos.clash.material.design.databinding.PreferenceClickableBinding import yos.clash.material.design.util.layoutInflater interface ClickablePreference : Preference { var title: CharSequence var icon: Drawable? var summary: CharSequence? fun clicked(clicked: () -> Unit) } fun PreferenceScreen.clickable( @StringRes title: Int, @DrawableRes icon: Int? = null, @StringRes summary: Int? = null, configure: ClickablePreference.() -> Unit = {} ): ClickablePreference { val binding = PreferenceClickableBinding .inflate(context.layoutInflater, root, false) val impl = object : ClickablePreference { override var icon: Drawable? get() = binding.iconView.background set(value) { binding.iconView.background = value binding.iconView.visibility = if (value == null) View.GONE else View.VISIBLE } override var title: CharSequence get() = binding.titleView.text set(value) { binding.titleView.text = value } override var summary: CharSequence? get() = binding.summaryView.text set(value) { binding.summaryView.text = value binding.summaryView.visibility = if (value == null) View.GONE else View.VISIBLE } override val view: View get() = binding.root override fun clicked(clicked: () -> Unit) { binding.root.setOnClickListener { clicked() } } } impl.title = context.getText(title) if (icon != null) { impl.icon = context.getDrawableCompat(icon) } else { impl.icon = null } if (summary != null) { impl.summary = context.getText(summary) } else { impl.summary = null } impl.configure() addElement(impl) return impl } ================================================ FILE: design/src/main/java/yos/clash/material/design/preference/EditableText.kt ================================================ package yos.clash.material.design.preference import androidx.annotation.DrawableRes import androidx.annotation.StringRes import yos.clash.material.design.R import yos.clash.material.design.dialog.requestModelTextInput import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.reflect.KMutableProperty0 interface EditableTextPreference : ClickablePreference { var placeholder: CharSequence? var empty: CharSequence? var text: String? } fun PreferenceScreen.editableText( value: KMutableProperty0, adapter: NullableTextAdapter, @StringRes title: Int, @DrawableRes icon: Int? = null, @StringRes placeholder: Int? = null, @StringRes empty: Int? = null, configure: EditableTextPreference.() -> Unit = {}, ): EditableTextPreference { val impl = object : EditableTextPreference, ClickablePreference by clickable(title, icon) { override var placeholder: CharSequence? = null override var empty: CharSequence? = null override var text: String? = null set(value) { field = value when { value == null -> { this.summary = this.placeholder } value.isEmpty() -> { this.summary = this.empty } else -> { this.summary = value } } } } if (placeholder != null) { impl.placeholder = context.getText(placeholder) } if (empty != null) { impl.empty = context.getText(empty) } impl.configure() launch(Dispatchers.Main) { impl.text = withContext(Dispatchers.IO) { adapter.from(value.get()) } impl.clicked { this@editableText.launch(Dispatchers.Main) { val text = context.requestModelTextInput( initial = impl.text, title = impl.title, reset = context.getText(R.string.reset), hint = impl.title, ) val newValue = withContext(Dispatchers.IO) { adapter.to(text).apply(value::set) } impl.text = adapter.from(newValue) } } } return impl } ================================================ FILE: design/src/main/java/yos/clash/material/design/preference/EditableTextList.kt ================================================ package yos.clash.material.design.preference import android.content.Context import androidx.annotation.DrawableRes import androidx.annotation.StringRes import yos.clash.material.design.R import yos.clash.material.design.adapter.EditableTextListAdapter import yos.clash.material.design.dialog.requestModelTextInput import kotlinx.coroutines.* import kotlin.reflect.KMutableProperty0 interface EditableTextListPreference : ClickablePreference { var placeholder: CharSequence? var list: List? } fun PreferenceScreen.editableTextList( value: KMutableProperty0?>, adapter: TextAdapter, @StringRes title: Int, @DrawableRes icon: Int? = null, @StringRes placeholder: Int? = null, configure: EditableTextListPreference.() -> Unit = {}, ): EditableTextListPreference { val impl = object : EditableTextListPreference, ClickablePreference by clickable(title, icon) { override var list: List? = null set(value) { field = value when { value == null -> { this.summary = this.placeholder } value.isEmpty() -> { this.summary = context.getString(R.string.empty) } else -> { this.summary = context.getString(R.string.format_elements, value.size) } } } override var placeholder: CharSequence? = null } if (placeholder != null) { impl.placeholder = context.getText(placeholder) } impl.configure() launch(Dispatchers.Main) { val v = withContext(Dispatchers.IO) { value.get() } impl.list = v impl.clicked { this@editableTextList.launch(Dispatchers.Main) { val newList = requestEditTextList( impl.list, context, adapter, impl.title ) withContext(Dispatchers.IO) { value.set(newList) } impl.list = newList } } } return impl } private suspend fun requestEditTextList( initialValue: List?, context: Context, adapter: TextAdapter, title: CharSequence, ): List? { val recyclerAdapter = EditableTextListAdapter( context, initialValue?.toMutableList() ?: mutableListOf(), adapter ) val result = requestEditableListOverlay(context, recyclerAdapter, title) { val text = context.requestModelTextInput( initial = "", title = title, hint = title ) if (text.isNotBlank()) { recyclerAdapter.addElement(text) } } return when (result) { EditableListOverlayResult.Cancel -> initialValue EditableListOverlayResult.Apply -> recyclerAdapter.values EditableListOverlayResult.Reset -> null } } ================================================ FILE: design/src/main/java/yos/clash/material/design/preference/EditableTextMap.kt ================================================ package yos.clash.material.design.preference import android.content.Context import androidx.annotation.DrawableRes import androidx.annotation.StringRes import yos.clash.material.design.R import yos.clash.material.design.adapter.EditableTextMapAdapter import yos.clash.material.design.databinding.DialogEditableMapTextFieldBinding import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.root import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.* import kotlin.coroutines.resume import kotlin.reflect.KMutableProperty0 interface EditableTextMapPreference : ClickablePreference { var placeholder: CharSequence? var map: Map? } fun PreferenceScreen.editableTextMap( value: KMutableProperty0?>, keyAdapter: TextAdapter, valueAdapter: TextAdapter, @StringRes title: Int, @DrawableRes icon: Int? = null, @StringRes placeholder: Int? = null, configure: EditableTextMapPreference.() -> Unit = {} ): EditableTextMapPreference { val impl = object : EditableTextMapPreference, ClickablePreference by clickable(title, icon) { override var placeholder: CharSequence? = null override var map: Map? = null set(value) { field = value when { value == null -> { this.summary = this.placeholder } value.isEmpty() -> { this.summary = context.getString(R.string.empty) } else -> { this.summary = context.getString(R.string.format_elements, value.size) } } } } if (placeholder != null) { impl.placeholder = context.getText(placeholder) } impl.configure() launch(Dispatchers.Main) { val v = withContext(Dispatchers.IO) { value.get() } impl.map = v impl.clicked { this@editableTextMap.launch(Dispatchers.Main) { val newMap = requestEditTextMap( impl.map, context, keyAdapter, valueAdapter, impl.title ) withContext(Dispatchers.IO) { value.set(newMap) } impl.map = newMap } } } return impl } private suspend fun requestEditTextMap( initialValue: Map?, context: Context, keyAdapter: TextAdapter, valueAdapter: TextAdapter, title: CharSequence ): Map? { val editableValue = withContext(Dispatchers.Default) { initialValue?.map { it.key to it.value }?.toMutableList() ?: mutableListOf() } val recyclerAdapter = EditableTextMapAdapter( context, editableValue, keyAdapter, valueAdapter, ) val result = requestEditableListOverlay(context, recyclerAdapter, title) { val newItem = requestModelInputEntry(context, title) if (newItem != null) { recyclerAdapter.addElement(newItem.first, newItem.second) } } return when (result) { EditableListOverlayResult.Cancel -> initialValue EditableListOverlayResult.Apply -> recyclerAdapter.values.toMap() EditableListOverlayResult.Reset -> null } } private suspend fun requestModelInputEntry( context: Context, title: CharSequence ): Pair? { return suspendCancellableCoroutine { ctx -> val binding = DialogEditableMapTextFieldBinding .inflate(context.layoutInflater, context.root, false) val dialog = MaterialAlertDialogBuilder(context) .setTitle(title) .setNegativeButton(R.string.cancel) { _, _ -> } .setPositiveButton(R.string.ok) { _, _ -> val k = binding.keyView.text?.toString()?.trim() ?: "" val v = binding.valueView.text?.toString()?.trim() ?: "" if (k.isNotEmpty() && v.isNotEmpty()) { ctx.resume(k to v) } } .setView(binding.root) .create() dialog.setOnCancelListener { if (!ctx.isCompleted) { ctx.resume(null) } } dialog.show() } } ================================================ FILE: design/src/main/java/yos/clash/material/design/preference/Overlay.kt ================================================ package yos.clash.material.design.preference import android.content.Context import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.databinding.DialogPreferenceListBinding import yos.clash.material.design.dialog.FullScreenDialog import yos.clash.material.design.util.applyLinearAdapter import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.root import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume internal enum class EditableListOverlayResult { Cancel, Apply, Reset } internal suspend fun requestEditableListOverlay( context: Context, adapter: RecyclerView.Adapter<*>, title: CharSequence, addNewItem: suspend () -> Unit ): EditableListOverlayResult { return coroutineScope { suspendCancellableCoroutine { ctx -> val dialog = FullScreenDialog(context) val binding = DialogPreferenceListBinding .inflate(context.layoutInflater, context.root, false) binding.surface = dialog.surface binding.mainList.applyLinearAdapter(context, adapter) binding.titleView.text = title binding.newView.setOnClickListener { launch { addNewItem() } } binding.resetView.setOnClickListener { ctx.resume(EditableListOverlayResult.Reset) dialog.dismiss() } binding.cancelView.setOnClickListener { dialog.dismiss() } binding.okView.setOnClickListener { ctx.resume(EditableListOverlayResult.Apply) dialog.dismiss() } dialog.setContentView(binding.root) dialog.setOnDismissListener { if (!ctx.isCompleted) { ctx.resume(EditableListOverlayResult.Cancel) } } ctx.invokeOnCancellation { dialog.dismiss() } dialog.show() } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/preference/Preference.kt ================================================ package yos.clash.material.design.preference import android.view.View fun interface OnChangedListener { fun onChanged() } interface Preference { val view: View var enabled: Boolean get() = view.isEnabled set(value) { view.isEnabled = value view.isClickable = value view.isFocusable = value view.alpha = if (value) 1.0f else 0.33f } } ================================================ FILE: design/src/main/java/yos/clash/material/design/preference/Screen.kt ================================================ package yos.clash.material.design.preference import android.content.Context import android.view.ViewGroup import android.widget.LinearLayout import android.widget.LinearLayout.LayoutParams import android.widget.LinearLayout.LayoutParams.MATCH_PARENT import android.widget.LinearLayout.LayoutParams.WRAP_CONTENT import kotlinx.coroutines.CoroutineScope interface PreferenceScreen : CoroutineScope { val context: Context val root: ViewGroup } fun CoroutineScope.preferenceScreen( context: Context, configure: PreferenceScreen.() -> Unit ): PreferenceScreen { val root = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL } val impl = object : PreferenceScreen, CoroutineScope by this { override val context: Context get() = context override val root: ViewGroup get() = root } impl.configure() return impl } fun PreferenceScreen.addElement(preference: Preference) { root.addView(preference.view, LayoutParams(MATCH_PARENT, WRAP_CONTENT)) } ================================================ FILE: design/src/main/java/yos/clash/material/design/preference/SelectableList.kt ================================================ package yos.clash.material.design.preference import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.appcompat.widget.ListPopupWindow import yos.clash.material.design.R import yos.clash.material.design.adapter.PopupListAdapter import yos.clash.material.design.util.getPixels import yos.clash.material.design.util.measureWidth import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.reflect.KMutableProperty0 interface SelectableListPreference : ClickablePreference { var selected: Int var listener: OnChangedListener? } fun PreferenceScreen.selectableList( value: KMutableProperty0, values: Array, valuesText: Array, @StringRes title: Int, @DrawableRes icon: Int? = null, configure: SelectableListPreference.() -> Unit = {}, ): SelectableListPreference { val impl = object : SelectableListPreference, ClickablePreference by clickable(title, icon) { override var selected: Int = 0 set(value) { field = value this.summary = context.getText(valuesText[value]) } override var listener: OnChangedListener? = null } impl.configure() launch(Dispatchers.Main) { val initial = withContext(Dispatchers.IO) { value.get() } impl.selected = values.indexOf(initial) impl.clicked { popupSelectMenu(impl, value, valuesText.map { context.getText(it) }, values) } } return impl } private fun PreferenceScreen.popupSelectMenu( impl: SelectableListPreference, value: KMutableProperty0, valuesText: List, values: Array, ) { ListPopupWindow(context).apply { val adapter = PopupListAdapter( context, valuesText, impl.selected, ) setAdapter(adapter) anchorView = impl.view width = adapter.measureWidth(context) .coerceAtLeast(context.getPixels(R.dimen.dialog_menu_min_width)) isModal = true horizontalOffset = context.getPixels(R.dimen.item_header_component_size) + context.getPixels(R.dimen.item_header_margin) * 2 setOnItemClickListener { _, _, position, _ -> dismiss() launch(Dispatchers.Main) { withContext(Dispatchers.IO) { value.set(values[position]) } impl.selected = position impl.listener?.onChanged() } } show() } } ================================================ FILE: design/src/main/java/yos/clash/material/design/preference/Switch.kt ================================================ package yos.clash.material.design.preference import android.graphics.drawable.Drawable import android.view.View import androidx.annotation.DrawableRes import androidx.annotation.StringRes import yos.clash.material.common.compat.getDrawableCompat import yos.clash.material.design.databinding.PreferenceSwitchBinding import yos.clash.material.design.util.layoutInflater import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.reflect.KMutableProperty0 interface SwitchPreference : Preference { var icon: Drawable? var title: CharSequence? var summary: CharSequence? var listener: OnChangedListener? } fun PreferenceScreen.switch( value: KMutableProperty0, @DrawableRes icon: Int? = null, @StringRes title: Int? = null, @StringRes summary: Int? = null, configure: SwitchPreference.() -> Unit = {}, ): SwitchPreference { val binding = PreferenceSwitchBinding .inflate(context.layoutInflater, root, false) val impl = object : SwitchPreference { override val view: View get() = binding.root override var icon: Drawable? get() = binding.iconView.background set(value) { binding.iconView.background = value binding.iconView.visibility = if (value == null) View.GONE else View.VISIBLE } override var title: CharSequence? get() = binding.titleView.text set(value) { binding.titleView.text = value } override var summary: CharSequence? get() = binding.summaryView.text set(value) { binding.summaryView.text = value } override var listener: OnChangedListener? = null override var enabled: Boolean get() = binding.root.isEnabled set(value) { binding.root.isEnabled = value binding.root.isFocusable = value binding.root.isClickable = value binding.root.alpha = if (value) 1.0f else 0.33f } } if (icon != null) { impl.icon = context.getDrawableCompat(icon) } else { impl.icon = null } if (title != null) { impl.title = context.getString(title) } if (summary != null) { impl.summary = context.getString(summary) } impl.configure() addElement(impl) launch(Dispatchers.Main) { val initialValue = withContext(Dispatchers.IO) { value.get() } binding.switchView.apply { isChecked = initialValue binding.root.setOnClickListener { isChecked = !isChecked this@switch.launch(Dispatchers.Main) { withContext(Dispatchers.IO) { value.set(isChecked) } impl.listener?.onChanged() } } } } return impl } ================================================ FILE: design/src/main/java/yos/clash/material/design/preference/Tips.kt ================================================ package yos.clash.material.design.preference import android.view.View import androidx.annotation.StringRes import yos.clash.material.design.databinding.PreferenceTipsBinding import yos.clash.material.design.util.getHtml import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.root interface TipsPreference : Preference { var text: CharSequence? } fun PreferenceScreen.tips( @StringRes text: Int, configure: TipsPreference.() -> Unit = {}, ): TipsPreference { val binding = PreferenceTipsBinding .inflate(context.layoutInflater, context.root, false) val impl = object : TipsPreference { override var text: CharSequence? get() = binding.tips.text set(value) { binding.tips.text = value } override val view: View get() = binding.root override var enabled: Boolean get() = binding.root.isEnabled set(value) { binding.root.isEnabled = value } } binding.tips.text = context.getHtml(text) impl.configure() addElement(impl) return impl } ================================================ FILE: design/src/main/java/yos/clash/material/design/preference/Value.kt ================================================ package yos.clash.material.design.preference interface NullableTextAdapter { fun from(value: T): String? fun to(text: String?): T companion object { val Port = object : NullableTextAdapter { override fun from(value: Int?): String? { if (value == null) return null return if (value > 0) value.toString() else "" } override fun to(text: String?): Int? { if (text == null) return null return text.toIntOrNull() ?: 0 } } val String = object : NullableTextAdapter { override fun from(value: String?): String? { return value } override fun to(text: String?): String? { return text } } } } interface TextAdapter { fun from(value: T): String fun to(text: String): T companion object { val String = object : TextAdapter { override fun from(value: String): String { return value } override fun to(text: String): String { return text } } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/store/UiStore.kt ================================================ package yos.clash.material.design.store import android.content.Context import yos.clash.material.common.store.Store import yos.clash.material.common.store.asStoreProvider import com.github.kr328.clash.core.model.ProxySort import yos.clash.material.design.model.AppInfoSort import yos.clash.material.design.model.DarkMode class UiStore(context: Context) { private val store = Store( context .getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE) .asStoreProvider() ) var enableVpn: Boolean by store.boolean( key = "enable_vpn", defaultValue = true ) var darkMode: DarkMode by store.enum( key = "dark_mode", defaultValue = DarkMode.Auto, values = DarkMode.values() ) var proxyExcludeNotSelectable by store.boolean( key = "proxy_exclude_not_selectable", defaultValue = false, ) var proxySingleLine: Boolean by store.boolean( key = "proxy_single_line", defaultValue = false ) var proxySort: ProxySort by store.enum( key = "proxy_sort", defaultValue = ProxySort.Default, values = ProxySort.values() ) var proxyLastGroup: String by store.string( key = "proxy_last_group", defaultValue = "" ) var accessControlSort: AppInfoSort by store.enum( key = "access_control_sort", defaultValue = AppInfoSort.Label, values = AppInfoSort.values(), ) var accessControlReverse: Boolean by store.boolean( key = "access_control_reverse", defaultValue = false ) var accessControlSystemApp: Boolean by store.boolean( key = "access_control_system_app", defaultValue = false, ) companion object { private const val PREFERENCE_NAME = "ui" } } ================================================ FILE: design/src/main/java/yos/clash/material/design/ui/DayNight.kt ================================================ package yos.clash.material.design.ui enum class DayNight { Day, Night } ================================================ FILE: design/src/main/java/yos/clash/material/design/ui/Insets.kt ================================================ package yos.clash.material.design.ui data class Insets(val start: Int, val top: Int, val end: Int, val bottom: Int) { companion object { val EMPTY = Insets(0, 0, 0, 0) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/ui/ObservableCurrentTime.kt ================================================ package yos.clash.material.design.ui import androidx.databinding.BaseObservable import androidx.databinding.Bindable import androidx.databinding.library.baseAdapters.BR class ObservableCurrentTime : BaseObservable() { var value: Long = System.currentTimeMillis() @Bindable get private set(value) { field = value notifyPropertyChanged(BR.value) } fun update() { value = System.currentTimeMillis() } } ================================================ FILE: design/src/main/java/yos/clash/material/design/ui/Surface.kt ================================================ package yos.clash.material.design.ui import androidx.databinding.BaseObservable import androidx.databinding.Bindable import yos.clash.material.design.BR class Surface : BaseObservable() { var insets: Insets = Insets.EMPTY @Bindable get set(value) { field = value notifyPropertyChanged(BR.insets) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/ui/ToastDuration.kt ================================================ package yos.clash.material.design.ui enum class ToastDuration { Short, Long, Indefinite } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/ActivityBar.kt ================================================ package yos.clash.material.design.util import android.app.Activity import android.content.Context import android.widget.ImageView import android.widget.TextView import yos.clash.material.design.R import yos.clash.material.design.view.ActivityBarLayout fun ActivityBarLayout.applyFrom(context: Context) { if (context is Activity) { findViewById(R.id.activity_bar_close_view)?.apply { setOnClickListener { context.onBackPressed() } } findViewById(R.id.activity_bar_title_view)?.apply { text = context.title } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/App.kt ================================================ package yos.clash.material.design.util import android.content.pm.PackageInfo import android.content.pm.PackageManager import yos.clash.material.common.compat.foreground import yos.clash.material.design.model.AppInfo fun PackageInfo.toAppInfo(pm: PackageManager): AppInfo { return AppInfo( packageName = packageName, icon = applicationInfo.loadIcon(pm).foreground(), label = applicationInfo.loadLabel(pm).toString(), installTime = firstInstallTime, updateDate = lastUpdateTime, ) } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/Binding.kt ================================================ package yos.clash.material.design.util import android.view.View import androidx.databinding.BindingAdapter @BindingAdapter("android:minHeight") fun bindMinHeight(view: View, value: Float) { view.minimumHeight = value.toInt() } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/Context.kt ================================================ package yos.clash.material.design.util import android.app.Activity import android.content.Context import android.text.Spanned import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.DimenRes import androidx.annotation.StringRes import yos.clash.material.common.compat.fromHtmlCompat val Context.layoutInflater: LayoutInflater get() = LayoutInflater.from(this) val Context.root: ViewGroup? get() { return when (this) { is Activity -> { findViewById(android.R.id.content) } else -> { null } } } fun Context.getPixels(@DimenRes resId: Int): Int { return resources.getDimensionPixelSize(resId) } fun Context.getHtml(@StringRes resId: Int): Spanned { return fromHtmlCompat(getString(resId)) } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/Diff.kt ================================================ package yos.clash.material.design.util import androidx.recyclerview.widget.DiffUtil fun List.diffWith( newList: List, detectMove: Boolean = false, id: (T) -> Any? = { it } ): DiffUtil.DiffResult { val oldList = this return DiffUtil.calculateDiff(object : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return id(oldList[oldItemPosition]) == id(newList[newItemPosition]) } override fun getOldListSize(): Int { return oldList.size } override fun getNewListSize(): Int { return newList.size } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition] == newList[newItemPosition] } }, detectMove) } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/Elevation.kt ================================================ package yos.clash.material.design.util import android.animation.ValueAnimator import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.R import yos.clash.material.design.view.ActivityBarLayout import yos.clash.material.design.view.ObservableScrollView private class AppBarElevationController( private val activityBar: ActivityBarLayout ) { private var animator: ValueAnimator? = null var elevated: Boolean = false set(value) { if (field == value) return field = value animator?.end() animator = if (value) { ValueAnimator.ofFloat( activityBar.elevation, activityBar.context.getPixels(R.dimen.toolbar_elevation).toFloat() ) } else { ValueAnimator.ofFloat( activityBar.elevation, 0f ) }.apply { addUpdateListener { activityBar.elevation = it.animatedValue as Float } start() } } } fun RecyclerView.bindAppBarElevation(activityBar: ActivityBarLayout) { addOnScrollListener(object : RecyclerView.OnScrollListener() { private val controller = AppBarElevationController(activityBar) override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { controller.elevated = !recyclerView.isTop } }) } fun ObservableScrollView.bindAppBarElevation(activityBar: ActivityBarLayout) { val controller = AppBarElevationController(activityBar) addOnScrollChangedListener { view, _, _, _, _ -> controller.elevated = !view.isTop } } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/I18n.kt ================================================ package yos.clash.material.design.util import android.content.Context import com.github.kr328.clash.core.model.Provider import yos.clash.material.common.compat.preferredLocale import yos.clash.material.design.R import yos.clash.material.service.model.Profile import java.text.SimpleDateFormat import java.util.* private const val DATE_DATE_ONLY = "yyyy-MM-dd" private const val DATE_TIME_ONLY = "HH:mm:ss.SSS" private const val DATE_ALL = "$DATE_DATE_ONLY $DATE_TIME_ONLY" fun Profile.Type.toString(context: Context): String { return when (this) { Profile.Type.File -> context.getString(R.string.file) Profile.Type.Url -> context.getString(R.string.url) Profile.Type.External -> context.getString(R.string.external) } } fun Provider.type(context: Context): String { val type = when (type) { Provider.Type.Proxy -> context.getString(R.string.proxy) Provider.Type.Rule -> context.getString(R.string.rule) } val vehicle = when (vehicleType) { Provider.VehicleType.HTTP -> context.getString(R.string.http) Provider.VehicleType.File -> context.getString(R.string.file) Provider.VehicleType.Compatible -> context.getString(R.string.compatible) } return context.getString(R.string.format_provider_type, type, vehicle) } @JvmOverloads fun Date.format( context: Context, includeDate: Boolean = true, includeTime: Boolean = true, ): String { val locale = context.resources.configuration.preferredLocale return when { includeDate && includeTime -> SimpleDateFormat(DATE_ALL, locale).format(this) includeDate -> SimpleDateFormat(DATE_DATE_ONLY, locale).format(this) includeTime -> SimpleDateFormat(DATE_TIME_ONLY, locale).format(this) else -> "" } } fun Long.formatDate( context: Context, includeDate: Boolean = true, includeTime: Boolean = true, ): String = Date(this).format(context, includeDate, includeTime) fun Long.toBytesString(): String { return when { this > 1024 * 1024 * 1024 * 1024L -> String.format("%.2f TiB", (this.toDouble() / 1024 / 1024 / 1024 / 1024)) this > 1024 * 1024 * 1024 -> String.format("%.2f GiB", (this.toDouble() / 1024 / 1024 / 1024)) this > 1024 * 1024 -> String.format("%.2f MiB", (this.toDouble() / 1024 / 1024)) this > 1024 -> String.format("%.2f KiB", (this.toDouble() / 1024)) else -> "$this Bytes" } } fun progress(used: Long, total: Long): Int { return ((used.toFloat() / total.toFloat()) * 100).toInt() } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/Inserts.kt ================================================ package yos.clash.material.design.util import android.view.View import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import yos.clash.material.design.ui.Insets fun View.setOnInsertsChangedListener(adaptLandscape: Boolean = true, listener: (Insets) -> Unit) { setOnApplyWindowInsetsListener { v, ins -> val compat = WindowInsetsCompat.toWindowInsetsCompat(ins) val insets = compat.getInsets(WindowInsetsCompat.Type.systemBars()) val rInsets = if (ViewCompat.getLayoutDirection(v) == ViewCompat.LAYOUT_DIRECTION_LTR) { Insets( insets.left, insets.top, insets.right, insets.bottom, ) } else { Insets( insets.right, insets.top, insets.left, insets.bottom, ) } listener(if (adaptLandscape) rInsets.landscape(v.context) else rInsets) compat.toWindowInsets()!! } requestApplyInsets() } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/Interval.kt ================================================ package yos.clash.material.design.util import android.content.Context import yos.clash.material.design.R import java.util.concurrent.TimeUnit fun Long.elapsedIntervalString(context: Context): String { val day = TimeUnit.MILLISECONDS.toDays(this) val hour = TimeUnit.MILLISECONDS.toHours(this) val minute = TimeUnit.MILLISECONDS.toMinutes(this) return when { day > 0 -> context.getString(R.string.format_days_ago, day) hour > 0 -> context.getString(R.string.format_hours_ago, hour) minute > 0 -> context.getString(R.string.format_minutes_ago, minute) else -> context.getString(R.string.recently) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/Landscape.kt ================================================ package yos.clash.material.design.util import android.content.Context import yos.clash.material.design.R import yos.clash.material.design.ui.Insets fun Insets.landscape(context: Context): Insets { val displayMetrics = context.resources.displayMetrics val minWidth = context.getPixels(R.dimen.surface_landscape_min_width) val width = displayMetrics.widthPixels val height = displayMetrics.heightPixels return if (width > height && width > minWidth) { val expectedWidth = width.coerceAtMost(height.coerceAtLeast(minWidth)) val padding = (width - expectedWidth).coerceAtLeast(start + end) / 2 copy(start = padding.coerceAtLeast(start), end = padding.coerceAtLeast(end)) } else { this } } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/ListView.kt ================================================ package yos.clash.material.design.util import android.content.Context import android.view.View import android.view.View.MeasureSpec import android.widget.FrameLayout import android.widget.ListAdapter fun ListAdapter.measureWidth(context: Context): Int { val parent = FrameLayout(context) val widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) val heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) var itemView: View? = null var maxWidth = 0 var itemType = 0 for (i in 0 until count) { val positionType = getItemViewType(i) if (positionType != itemType) { itemType = positionType itemView = null } itemView = getView(i, itemView, parent) itemView.measure(widthMeasureSpec, heightMeasureSpec) val itemWidth: Int = itemView.measuredWidth if (itemWidth > maxWidth) { maxWidth = itemWidth } } return maxWidth } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/RecyclerView.kt ================================================ package yos.clash.material.design.util import android.content.Context import android.view.View import androidx.core.view.children import androidx.databinding.Observable import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import yos.clash.material.design.BR import yos.clash.material.design.ui.Surface import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlin.reflect.KMutableProperty0 fun RecyclerView.applyLinearAdapter(context: Context, adapter: RecyclerView.Adapter<*>) { this.layoutManager = LinearLayoutManager(context) this.adapter = adapter } suspend fun RecyclerView.Adapter.swapDataSet( property: KMutableProperty0>, newDataset: List, compareEquals: Boolean = true ) { val ignore = withContext(Dispatchers.Default) { compareEquals && property.get() == newDataset } if (ignore) return withContext(Dispatchers.Main) { if (property.get().size == newDataset.size) { property.set(newDataset) notifyItemRangeChanged(0, newDataset.size) } else { notifyItemRangeRemoved(0, property.get().size) property.set(newDataset) notifyItemRangeInserted(0, newDataset.size) } } } suspend fun RecyclerView.Adapter.patchDataSet( property: KMutableProperty0>, newDataset: List, detectMove: Boolean = false, id: (T) -> Any? = { it } ) { val result = withContext(Dispatchers.Default) { property.get().diffWith(newDataset, detectMove, id) } withContext(Dispatchers.Main) { property.set(newDataset) result.dispatchUpdatesTo(this@patchDataSet) } } fun RecyclerView.invalidateChildren() { children.forEach { it.postInvalidate() } } fun RecyclerView.bindInsets(surface: Surface, top: Int = 0, bottom: Int = 0) { fun applyInsets() { val t = surface.insets.top + top val b = surface.insets.bottom + bottom setPaddingRelative(0, t, 0, b) } surface.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() { override fun onPropertyChanged(sender: Observable?, propertyId: Int) { if (propertyId == BR.insets) { applyInsets() } } }) applyInsets() } fun RecyclerView.addScrolledToBottomObserver(listener: (RecyclerView, Boolean) -> Unit) { val observer = object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { listener(this@addScrolledToBottomObserver, recyclerView.isBottom) } } } addOnScrollListener(observer) } val RecyclerView.firstVisibleView: View? get() { return when (val mgr = layoutManager) { is LinearLayoutManager -> mgr.findViewByPosition(mgr.findFirstVisibleItemPosition()) else -> throw UnsupportedOperationException("unsupported manager: $mgr") } } val RecyclerView.isTop: Boolean get() = computeHorizontalScrollOffset() == 0 && computeVerticalScrollOffset() == 0 val RecyclerView.isBottom: Boolean get() { return when (val mgr = layoutManager) { is GridLayoutManager -> { mgr.findFirstVisibleItemPosition() != 0 && mgr.findLastVisibleItemPosition() == adapter!!.itemCount - 1 } else -> { throw UnsupportedOperationException("unsupported layout manager") } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/ScrollView.kt ================================================ package yos.clash.material.design.util import yos.clash.material.design.view.ObservableScrollView val ObservableScrollView.isTop: Boolean get() = scrollX == 0 && scrollY == 0 ================================================ FILE: design/src/main/java/yos/clash/material/design/util/Theme.kt ================================================ package yos.clash.material.design.util import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import android.util.TypedValue import androidx.annotation.AttrRes import androidx.annotation.StyleRes import yos.clash.material.common.compat.getDrawableCompat import yos.clash.material.design.R interface ClickableScope { fun focusable(defaultValue: Boolean): Boolean fun clickable(defaultValue: Boolean): Boolean fun background(): Drawable? fun foreground(): Drawable? } val Context.selectableItemBackground: Drawable? get() { return getDrawableCompat(resolveThemedResourceId(android.R.attr.selectableItemBackground)) } fun Context.resolveClickableAttrs( attributeSet: AttributeSet?, @AttrRes defaultAttrRes: Int = 0, @StyleRes defaultStyleRes: Int = 0, block: ClickableScope.() -> Unit, ) { theme.obtainStyledAttributes( attributeSet, R.styleable.Clickable, defaultAttrRes, defaultStyleRes ).apply { val impl = object : ClickableScope { override fun focusable(defaultValue: Boolean): Boolean { return getBoolean(R.styleable.Clickable_android_focusable, defaultValue) } override fun clickable(defaultValue: Boolean): Boolean { return getBoolean(R.styleable.Clickable_android_clickable, defaultValue) } override fun background(): Drawable? { return getDrawable(R.styleable.Clickable_android_background) } override fun foreground(): Drawable? { return getDrawable(R.styleable.Clickable_android_focusable) } } impl.apply(block) recycle() } } fun Context.resolveThemedColor(@AttrRes resId: Int): Int { return TypedValue().apply { theme.resolveAttribute(resId, this, true) }.data } fun Context.resolveThemedBoolean(@AttrRes resId: Int): Boolean { return TypedValue().apply { theme.resolveAttribute(resId, this, true) }.data != 0 } fun Context.resolveThemedResourceId(@AttrRes resId: Int): Int { return TypedValue().apply { theme.resolveAttribute(resId, this, true) }.resourceId } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/Toast.kt ================================================ package yos.clash.material.design.util import yos.clash.material.design.Design import yos.clash.material.design.R import yos.clash.material.design.ui.ToastDuration import com.google.android.material.dialog.MaterialAlertDialogBuilder suspend fun Design<*>.showExceptionToast(message: CharSequence) { showToast(message, ToastDuration.Long) { setAction(R.string.detail) { MaterialAlertDialogBuilder(it.context) .setTitle(R.string.error) .setMessage(message) .setCancelable(true) .setPositiveButton(R.string.ok) { _, _ -> } .show() } } } suspend fun Design<*>.showExceptionToast(exception: Exception) { showExceptionToast(exception.message ?: "Unknown") } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/Validator.kt ================================================ package yos.clash.material.design.util import yos.clash.material.common.util.PatternFileName typealias Validator = (String) -> Boolean val ValidatorAcceptAll: Validator = { true } val ValidatorFileName: Validator = { PatternFileName.matches(it) && it.isNotBlank() } val ValidatorNotBlank: Validator = { it.isNotBlank() } val ValidatorHttpUrl: Validator = { it.startsWith("https://", ignoreCase = true) || it.startsWith("http://", ignoreCase = true) } val ValidatorAutoUpdateInterval: Validator = { it.isEmpty() || (it.toLongOrNull() ?: 0) >= 15 } ================================================ FILE: design/src/main/java/yos/clash/material/design/util/View.kt ================================================ package yos.clash.material.design.util import android.view.View import android.view.inputmethod.InputMethodManager import androidx.core.content.getSystemService fun View.requestTextInput() { post { requestFocus() postDelayed({ context.getSystemService() ?.showSoftInput(this, 0) }, 300) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/view/ActionLabel.kt ================================================ package yos.clash.material.design.view import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import androidx.annotation.AttrRes import androidx.annotation.StyleRes import yos.clash.material.design.R import yos.clash.material.design.databinding.ComponentActionLabelBinding import yos.clash.material.design.util.layoutInflater class ActionLabel @JvmOverloads constructor( context: Context, attributeSet: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0, @StyleRes defStyleRes: Int = 0 ) : FrameLayout(context, attributeSet, defStyleAttr, defStyleRes) { private val binding = ComponentActionLabelBinding .inflate(context.layoutInflater, this, true) var icon: Drawable? get() = binding.iconView.background set(value) { binding.iconView.background = value binding.iconView.visibility = if (value == null) View.GONE else View.VISIBLE } var text: CharSequence? get() = binding.textView.text set(value) { binding.textView.text = value } var subtext: CharSequence? get() = binding.subtextView.text set(value) { binding.subtextView.text = value binding.subtextView.visibility = if (value == null) View.GONE else View.VISIBLE } override fun setOnClickListener(l: OnClickListener?) { binding.clickAble.setOnClickListener(l) } init { context.theme.obtainStyledAttributes( attributeSet, R.styleable.ActionLabel, defStyleAttr, defStyleRes ).apply { try { icon = getDrawable(R.styleable.ActionLabel_icon) text = getString(R.styleable.ActionLabel_text) subtext = getString(R.styleable.ActionLabel_subtext) } finally { recycle() } } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/view/ActionTextField.kt ================================================ package yos.clash.material.design.view import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import android.widget.FrameLayout import androidx.annotation.AttrRes import androidx.annotation.StyleRes import yos.clash.material.design.R import yos.clash.material.design.databinding.ComponentActionTextFieldBinding import yos.clash.material.design.util.layoutInflater class ActionTextField @JvmOverloads constructor( context: Context, attributeSet: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0, @StyleRes defStyleRes: Int = 0 ) : FrameLayout(context, attributeSet, defStyleAttr, defStyleRes) { private val binding = ComponentActionTextFieldBinding .inflate(context.layoutInflater, this, true) var icon: Drawable? get() = binding.iconView.background set(value) { binding.iconView.background = value } var title: CharSequence? get() = binding.titleView.text set(value) { binding.titleView.text = value } var text: CharSequence? get() = binding.textView.text set(value) { if (isEnabled) binding.textView.text = value else binding.textView.text = context.getText(R.string.unavailable) } var placeholder: CharSequence? get() = binding.textView.hint set(value) { binding.textView.hint = value } override fun setEnabled(enabled: Boolean) { super.setEnabled(enabled) if (enabled) { binding.root.alpha = 1.0f binding.actionView.isFocusable = true binding.actionView.isClickable = true } else { binding.root.alpha = 0.33f binding.actionView.isFocusable = false binding.actionView.isClickable = false } text = text } override fun setOnClickListener(l: OnClickListener?) { binding.actionView.setOnClickListener(l) } init { context.theme.obtainStyledAttributes( attributeSet, R.styleable.ActionTextField, defStyleAttr, defStyleRes ).apply { try { isEnabled = getBoolean(R.styleable.ActionTextField_enabled, true) icon = getDrawable(R.styleable.ActionTextField_icon) title = getString(R.styleable.ActionTextField_title) text = getString(R.styleable.ActionTextField_text) placeholder = getString(R.styleable.ActionTextField_placeholder) } finally { recycle() } } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/view/ActivityBarLayout.kt ================================================ package yos.clash.material.design.view import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.widget.FrameLayout import androidx.annotation.AttrRes import androidx.annotation.StyleRes import yos.clash.material.design.util.resolveThemedColor class ActivityBarLayout @JvmOverloads constructor( context: Context, attributeSet: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0, @StyleRes defStyleRes: Int = 0 ) : FrameLayout(context, attributeSet, defStyleAttr, defStyleRes) { init { alpha = 0.96f setBackgroundColor(context.resolveThemedColor(android.R.attr.windowBackground)) } override fun dispatchTouchEvent(ev: MotionEvent?): Boolean { super.dispatchTouchEvent(ev) return true } } ================================================ FILE: design/src/main/java/yos/clash/material/design/view/AppRecyclerView.kt ================================================ package yos.clash.material.design.view import android.content.Context import android.graphics.Canvas import android.util.AttributeSet import androidx.annotation.AttrRes import androidx.recyclerview.widget.RecyclerView class AppRecyclerView @JvmOverloads constructor( context: Context, attributeSet: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0 ) : RecyclerView(context, attributeSet, defStyleAttr) { init { isFocusable = false } } ================================================ FILE: design/src/main/java/yos/clash/material/design/view/LargeActionCard.kt ================================================ package yos.clash.material.design.view import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import androidx.annotation.AttrRes import yos.clash.material.design.R import yos.clash.material.design.databinding.ComponentLargeActionLabelBinding import yos.clash.material.design.util.* import com.google.android.material.card.MaterialCardView class LargeActionCard @JvmOverloads constructor( context: Context, attributeSet: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0 ) : MaterialCardView(context, attributeSet, defStyleAttr) { private val binding = ComponentLargeActionLabelBinding .inflate(context.layoutInflater, this, true) var text: CharSequence? get() = binding.textView.text set(value) { binding.textView.text = value } var subtext: CharSequence? get() = binding.subtextView.text set(value) { binding.subtextView.text = value } var icon: Drawable? get() = binding.iconView.background set(value) { binding.iconView.background = value } init { context.resolveClickableAttrs(attributeSet, defStyleAttr) { isFocusable = focusable(true) isClickable = clickable(true) foreground = foreground() ?: context.selectableItemBackground } context.theme.obtainStyledAttributes( attributeSet, R.styleable.LargeActionCard, defStyleAttr, 0 ).apply { try { icon = getDrawable(R.styleable.LargeActionCard_icon) text = getString(R.styleable.LargeActionCard_text) subtext = getString(R.styleable.LargeActionCard_subtext) } finally { recycle() } } minimumHeight = context.getPixels(R.dimen.large_action_card_min_height) radius = context.getPixels(R.dimen.large_action_card_radius).toFloat() elevation = context.getPixels(R.dimen.large_action_card_elevation).toFloat() setCardBackgroundColor(context.resolveThemedColor(R.attr.colorSurface)) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/view/LargeActionLabel.kt ================================================ package yos.clash.material.design.view import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import androidx.annotation.AttrRes import androidx.annotation.StyleRes import yos.clash.material.design.R import yos.clash.material.design.databinding.ComponentLargeActionLabelBinding import yos.clash.material.design.util.layoutInflater import yos.clash.material.design.util.resolveClickableAttrs import yos.clash.material.design.util.selectableItemBackground class LargeActionLabel @JvmOverloads constructor( context: Context, attributeSet: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0, @StyleRes defStyleRes: Int = 0 ) : FrameLayout(context, attributeSet, defStyleAttr, defStyleRes) { private val binding = ComponentLargeActionLabelBinding .inflate(context.layoutInflater, this, true) var icon: Drawable? get() = binding.iconView.background set(value) { binding.iconView.background = value } var text: CharSequence? get() = binding.textView.text set(value) { binding.textView.text = value } var subtext: CharSequence? get() = binding.subtextView.text set(value) { binding.subtextView.text = value if (value == null) { binding.subtextView.visibility = View.GONE } else { binding.subtextView.visibility = View.VISIBLE } } init { context.resolveClickableAttrs( attributeSet, defStyleAttr, defStyleRes ) { isFocusable = focusable(true) isClickable = clickable(true) background = background() ?: context.selectableItemBackground } context.theme.obtainStyledAttributes( attributeSet, R.styleable.LargeActionLabel, defStyleAttr, defStyleRes ).apply { try { icon = getDrawable(R.styleable.LargeActionLabel_icon) text = getString(R.styleable.LargeActionLabel_text) subtext = getString(R.styleable.LargeActionLabel_subtext) } finally { recycle() } } } } ================================================ FILE: design/src/main/java/yos/clash/material/design/view/ObservableScrollView.kt ================================================ package yos.clash.material.design.view import android.content.Context import android.util.AttributeSet import android.widget.ScrollView import androidx.annotation.AttrRes import androidx.annotation.StyleRes class ObservableScrollView @JvmOverloads constructor( context: Context, attributeSet: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0, @StyleRes defStyleRes: Int = 0 ) : ScrollView(context, attributeSet, defStyleAttr, defStyleRes) { fun interface OnScrollChangedListener { fun onChanged(scrollView: ObservableScrollView, x: Int, y: Int, oldl: Int, oldt: Int) } private val scrollChangedListeners: MutableSet = mutableSetOf() override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) { super.onScrollChanged(l, t, oldl, oldt) scrollChangedListeners.forEach { it.onChanged(this, l, t, oldl, oldt) } } fun addOnScrollChangedListener(listener: OnScrollChangedListener) { scrollChangedListeners.add(listener) } } ================================================ FILE: design/src/main/java/yos/clash/material/design/view/VerticalScrollableHost.kt ================================================ package yos.clash.material.design.view import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.widget.FrameLayout import kotlin.math.absoluteValue import kotlin.math.tan class VerticalScrollableHost @JvmOverloads constructor( context: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0 ) : FrameLayout(context, attributeSet, defStyleAttr, defStyleRes) { private var initialX = 0f private var initialY = 0f private val degree = tan(Math.toRadians(15.0)) override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { val parentView = parent ?: return super.onInterceptTouchEvent(ev) if (ev.action == MotionEvent.ACTION_DOWN) { initialX = ev.x initialY = ev.y parentView.requestDisallowInterceptTouchEvent(true) } else if (ev.action == MotionEvent.ACTION_MOVE) { val dx = ev.x - initialX val dy = ev.y - initialY val t = dy.absoluteValue / dx.absoluteValue if (t < degree) { parentView.requestDisallowInterceptTouchEvent(false) } } return super.onInterceptTouchEvent(ev) } } ================================================ FILE: design/src/main/res/drawable/bg_bottom_sheet.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_adb.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_add.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_apps.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_arrow_back.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_assignment.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_attach_file.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_brightness_4.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_clear_all.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_close.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_cloud_download.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_content_copy.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_delete.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_dns.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_domain.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_edit.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_extension.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_flash_on.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_get_app.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_help_center.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_info.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_more_vert.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_publish.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_replay.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_restore.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_save.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_search.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_settings.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_stop.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_swap_vert.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_swap_vertical_circle.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_sync.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_update.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_view_list.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_vpn_lock.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_baseline_work.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_clash.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_outline_article.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_outline_check_circle.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_outline_delete.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_outline_folder.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_outline_inbox.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_outline_info.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_outline_label.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_outline_not_interested.xml ================================================ ================================================ FILE: design/src/main/res/drawable/ic_outline_update.xml ================================================ ================================================ FILE: design/src/main/res/drawable/yos_shape.xml ================================================ ================================================ FILE: design/src/main/res/drawable/yos_shape_color.xml ================================================ ================================================ FILE: design/src/main/res/layout/adapter_app.xml ================================================ ================================================ FILE: design/src/main/res/layout/adapter_editable_text_list.xml ================================================ ================================================ FILE: design/src/main/res/layout/adapter_editable_text_map.xml ================================================ ================================================ FILE: design/src/main/res/layout/adapter_file.xml ================================================ ================================================ FILE: design/src/main/res/layout/adapter_log_message.xml ================================================ ================================================ FILE: design/src/main/res/layout/adapter_profile.xml ================================================ ================================================ FILE: design/src/main/res/layout/adapter_profile_provider.xml ================================================ ================================================ FILE: design/src/main/res/layout/adapter_provider.xml ================================================ ================================================ FILE: design/src/main/res/layout/adapter_sideload_provider.xml ================================================ ================================================ FILE: design/src/main/res/layout/common_activity_bar.xml ================================================ ================================================ FILE: design/src/main/res/layout/common_recycler_list.xml ================================================ ================================================ FILE: design/src/main/res/layout/component_action_label.xml ================================================ ================================================ FILE: design/src/main/res/layout/component_action_text_field.xml ================================================ ================================================ FILE: design/src/main/res/layout/component_large_action_label.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_about.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_access_control.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_app_crashed.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_files.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_logcat.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_logs.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_main.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_new_profile.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_profiles.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_properties.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_providers.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_proxy.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_settings.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_settings_common.xml ================================================ ================================================ FILE: design/src/main/res/layout/design_settings_overide.xml ================================================ ================================================ FILE: design/src/main/res/layout/dialog_editable_map_text_field.xml ================================================ ================================================ FILE: design/src/main/res/layout/dialog_fetch_status.xml ================================================ ================================================ FILE: design/src/main/res/layout/dialog_files_menu.xml ================================================ ================================================ FILE: design/src/main/res/layout/dialog_preference_list.xml ================================================