Skip to content

Commit

Permalink
Remake desktop
Browse files Browse the repository at this point in the history
Optimize lots of details
  • Loading branch information
chen08209 committed Nov 30, 2024
1 parent 0901390 commit cc447f7
Show file tree
Hide file tree
Showing 78 changed files with 4,960 additions and 1,926 deletions.
2 changes: 1 addition & 1 deletion core/Clash.Meta
66 changes: 66 additions & 0 deletions core/action.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package main

import (
"encoding/json"
)

const (
messageMethod Method = "message"
initClashMethod Method = "initClash"
getIsInitMethod Method = "getIsInit"
forceGcMethod Method = "forceGc"
shutdownMethod Method = "shutdown"
validateConfigMethod Method = "validateConfig"
updateConfigMethod Method = "updateConfig"
getProxiesMethod Method = "getProxies"
changeProxyMethod Method = "changeProxy"
getTrafficMethod Method = "getTraffic"
getTotalTrafficMethod Method = "getTotalTraffic"
resetTrafficMethod Method = "resetTraffic"
asyncTestDelayMethod Method = "asyncTestDelay"
getConnectionsMethod Method = "getConnections"
closeConnectionsMethod Method = "closeConnections"
closeConnectionMethod Method = "closeConnection"
getExternalProvidersMethod Method = "getExternalProviders"
getExternalProviderMethod Method = "getExternalProvider"
updateGeoDataMethod Method = "updateGeoData"
updateExternalProviderMethod Method = "updateExternalProvider"
sideLoadExternalProviderMethod Method = "sideLoadExternalProvider"
startLogMethod Method = "startLog"
stopLogMethod Method = "stopLog"
startListenerMethod Method = "startListener"
stopListenerMethod Method = "stopListener"
)

type Method string

type Action struct {
Id string `json:"id"`
Method Method `json:"method"`
Data interface{} `json:"data"`
}

func (action Action) Json() ([]byte, error) {
data, err := json.Marshal(action)
return data, err
}

func (action Action) callback(data interface{}) bool {
if conn == nil {
return false
}
sendAction := Action{
Id: action.Id,
Method: action.Method,
Data: data,
}
res, err := sendAction.Json()
if err != nil {
return false
}
_, err = conn.Write(append(res, []byte("\n")...))
if err != nil {
return false
}
return true
}
95 changes: 24 additions & 71 deletions core/common.go
Original file line number Diff line number Diff line change
@@ -1,35 +1,30 @@
package main

import "C"
import (
"context"
"core/state"
"errors"
"fmt"
"github.com/metacubex/mihomo/common/batch"
"github.com/metacubex/mihomo/constant/features"
"github.com/metacubex/mihomo/hub/route"
"github.com/samber/lo"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"time"

"github.com/metacubex/mihomo/adapter"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/adapter/outboundgroup"
"github.com/metacubex/mihomo/adapter/provider"
"github.com/metacubex/mihomo/common/batch"
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/resolver"
"github.com/metacubex/mihomo/config"
"github.com/metacubex/mihomo/constant"
cp "github.com/metacubex/mihomo/constant/provider"
"github.com/metacubex/mihomo/hub"
"github.com/metacubex/mihomo/hub/executor"
"github.com/metacubex/mihomo/listener"
"github.com/metacubex/mihomo/log"
rp "github.com/metacubex/mihomo/rules/provider"
Expand Down Expand Up @@ -81,31 +76,12 @@ func (a ExternalProviders) Len() int { return len(a) }
func (a ExternalProviders) Less(i, j int) bool { return a[i].Name < a[j].Name }
func (a ExternalProviders) Swap(i, j int) { a[i], a[j] = a[j], a[i] }

var b, _ = batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](50))

func restartExecutable(execPath string) {
var err error
executor.Shutdown()
if runtime.GOOS == "windows" {
cmd := exec.Command(execPath, os.Args[1:]...)
log.Infoln("restarting: %q %q", execPath, os.Args[1:])
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Start()
if err != nil {
log.Fatalln("restarting: %s", err)
}

os.Exit(0)
}

log.Infoln("restarting: %q %q", execPath, os.Args[1:])
err = syscall.Exec(execPath, os.Args, os.Environ())
if err != nil {
log.Fatalln("restarting: %s", err)
}
}
var (
isRunning = false
runLock sync.Mutex
ips = []string{"ipinfo.io", "ipapi.co", "api.ip.sb", "ipwho.is"}
b, _ = batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](50))
)

func readFile(path string) ([]byte, error) {
if _, err := os.Stat(path); os.IsNotExist(err) {
Expand All @@ -119,19 +95,6 @@ func readFile(path string) ([]byte, error) {
return data, err
}

func removeFile(path string) error {
absPath, err := filepath.Abs(path)
if err != nil {
return err
}
err = os.Remove(absPath)
if err != nil {
return err
}

return nil
}

func getProfilePath(id string) string {
return filepath.Join(constant.Path.HomeDir(), "profiles", id+".yaml")
}
Expand Down Expand Up @@ -262,8 +225,6 @@ func trimArr(arr []string) (r []string) {
return
}

var ips = []string{"ipinfo.io", "ipapi.co", "api.ip.sb", "ipwho.is"}

func overrideRules(rules *[]string) {
var target = ""
for _, line := range *rules {
Expand Down Expand Up @@ -325,20 +286,13 @@ func overwriteConfig(targetConfig *config.RawConfig, patchConfig config.RawConfi
}
}
overrideRules(&targetConfig.Rule)
//if runtime.GOOS == "android" {
// targetConfig.DNS.NameServer = append(targetConfig.DNS.NameServer, "dhcp://"+dns.SystemDNSPlaceholder)
//} else if runtime.GOOS == "windows" {
// targetConfig.DNS.NameServer = append(targetConfig.DNS.NameServer, dns.SystemDNSPlaceholder)
//}
//if configParams.IsCompatible == false {
// targetConfig.ProxyProvider = make(map[string]map[string]any)
// targetConfig.RuleProvider = make(map[string]map[string]any)
// generateProxyGroupAndRule(&targetConfig.ProxyGroup, &targetConfig.Rule)
//}
}

func patchConfig(general *config.General, controller *config.Controller, tls *config.TLS) {
func patchConfig() {
log.Infoln("[Apply] patch")
general := currentConfig.General
controller := currentConfig.Controller
tls := currentConfig.TLS
tunnel.SetSniffing(general.Sniffing)
tunnel.SetFindProcessMode(general.FindProcessMode)
dialer.SetTcpConcurrent(general.TCPConcurrent)
Expand All @@ -365,16 +319,12 @@ func patchConfig(general *config.General, controller *config.Controller, tls *co
})
}

var isRunning = false

var runLock sync.Mutex

func updateListeners(general *config.General, listeners map[string]constant.InboundListener) {
func updateListeners() {
if !isRunning {
return
}
runLock.Lock()
defer runLock.Unlock()
general := currentConfig.General
listeners := currentConfig.Listeners
stopListeners()
listener.PatchInboundListeners(listeners, tunnel.Tunnel, true)
listener.SetAllowLan(general.AllowLan)
Expand Down Expand Up @@ -424,19 +374,22 @@ func patchSelectGroup() {
}
}

func applyConfig() error {
cfg, err := config.ParseRawConfig(state.CurrentRawConfig)
func applyConfig(rawConfig *config.RawConfig) error {
runLock.Lock()
defer runLock.Unlock()
var err error
currentConfig, err = config.ParseRawConfig(rawConfig)
if err != nil {
cfg, _ = config.ParseRawConfig(config.DefaultRawConfig())
currentConfig, _ = config.ParseRawConfig(config.DefaultRawConfig())
}
if configParams.IsPatch {
patchConfig(cfg.General, cfg.Controller, cfg.TLS)
patchConfig()
} else {
closeConnections()
handleCloseConnectionsUnLock()
runtime.GC()
hub.ApplyConfig(cfg)
hub.ApplyConfig(currentConfig)
patchSelectGroup()
}
updateListeners(cfg.General, cfg.Listeners)
updateListeners()
return err
}
Loading

0 comments on commit cc447f7

Please sign in to comment.