Skip to content

Commit

Permalink
Fix windows config
Browse files Browse the repository at this point in the history
  • Loading branch information
HeHang0 committed Jan 10, 2024
1 parent c87ce2b commit 3b5c428
Show file tree
Hide file tree
Showing 14 changed files with 149 additions and 40 deletions.
2 changes: 1 addition & 1 deletion web/src/components/Playlist.vue
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const props = withDefaults(defineProps<Props>(), {
<style lang="less" scoped>
.music-play-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(165px, 1fr));
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
grid-column-gap: 5px;
grid-row-gap: 5px;
width: 100%;
Expand Down
1 change: 0 additions & 1 deletion web/src/components/WindowControls.vue
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ function prepareClose() {
align-items: center;
padding-left: 10px;
margin-left: 10px;
margin-right: 10px;
&::before {
content: '';
position: absolute;
Expand Down
4 changes: 2 additions & 2 deletions web/src/style/base.less
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@
rgb(235, 240, 251),
rgb(248, 239, 241));

@media (max-width: 800px),
(max-height: 720px) {
@media (max-width: 600px),
(max-height: 600px) {
--music-page-padding-horizontal: 10px;
}
}
Expand Down
8 changes: 4 additions & 4 deletions web/src/utils/storage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { webView2Services } from '../utils/utils';
const useFileAccessor = false;
const useFileAccessor = webView2Services.enabled && webView2Services.isWindows;
export enum StorageKey {
Language = 'language',
AppTheme = 'app-theme',
Expand Down Expand Up @@ -33,7 +33,7 @@ async function setValue<T>(key: string, value: T) {
result = `${value}`;
}
if (useFileAccessor) {
await webView2Services.fileAccessor?.WriteFile('musiche-' + key, result);
await webView2Services.fileAccessor?.WriteConfig('musiche-' + key, result);
} else {
localStorage.setItem('musiche-' + key, result);
}
Expand All @@ -47,7 +47,7 @@ async function getValue<T>(
var value: any = '';
if (useFileAccessor) {
value =
(await webView2Services.fileAccessor?.ReadFile('musiche-' + key)) || '';
(await webView2Services.fileAccessor?.ReadConfig('musiche-' + key)) || '';
} else {
value = localStorage.getItem('musiche-' + key) as any;
}
Expand All @@ -64,7 +64,7 @@ async function getValue<T>(

async function removeKey(key: string) {
if (useFileAccessor) {
await webView2Services.fileAccessor?.DeleteFile('musiche-' + key);
await webView2Services.fileAccessor?.DeleteConfig('musiche-' + key);
} else {
localStorage.removeItem('musiche-' + key);
}
Expand Down
16 changes: 15 additions & 1 deletion web/src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ interface FileAccessor {
ReadFile: (path: string) => Promise<string>;
WriteFile: (path: string, text: string) => Promise<void>;
DeleteFile: (path: string) => Promise<void>;
ReadConfig: (path: string) => Promise<string>;
WriteConfig: (path: string, text: string) => Promise<void>;
DeleteConfig: (path: string) => Promise<void>;
FileExists: (path: string) => Promise<boolean>;
ShowSelectedDirectory: () => Promise<string[]>;
GetMyMusicDirectory: () => Promise<string>;
Expand All @@ -25,11 +28,15 @@ interface FileAccessor {
export const webView2Services = {
enabled: false,
specialService: null,
fileAccessor: null
fileAccessor: null,
isWindows: false,
isMobile: false
} as {
enabled: boolean;
specialService: SpecialService | null;
fileAccessor: FileAccessor | null;
isWindows: boolean;
isMobile: boolean;
};

try {
Expand Down Expand Up @@ -58,6 +65,9 @@ try {
callHandler = (window as any).flutter_inappwebview.callHandler;
}
webView2Services.fileAccessor = {
ReadConfig: (_path: string) => Promise.resolve(''),
WriteConfig: (_path: string, _text: string) => Promise.resolve(),
DeleteConfig: (_path: string) => Promise.resolve(),
ReadFile: (path: string) =>
callHandler ? callHandler('readFile', path) : Promise.resolve(''),
WriteFile: (path: string, text: string) =>
Expand All @@ -81,6 +91,8 @@ try {
? callHandler('listAllAudios', path, recursive)
: Promise.resolve('')
};
webView2Services.isMobile = true;
webView2Services.isWindows = false;
} else {
webView2Services.specialService = (
window as any
Expand All @@ -89,6 +101,8 @@ try {
window as any
)?.chrome?.webview?.hostObjects?.fileAccessor;
webView2Services.enabled = !!webView2Services.specialService;
webView2Services.isMobile = !webView2Services.specialService;
webView2Services.isWindows = webView2Services.enabled;
}
} catch (error) {}

Expand Down
4 changes: 1 addition & 3 deletions windows/App.xaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
<Application x:Class="Musiche.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Musiche"
StartupUri="MainWindow.xaml">
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
</Application.Resources>
</Application>
35 changes: 34 additions & 1 deletion windows/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.Windows;
using System.IO.Pipes;
using System;
using System.Windows;

namespace Musiche
{
Expand All @@ -7,5 +9,36 @@ namespace Musiche
/// </summary>
public partial class App : Application
{
System.Threading.Mutex procMutex;

protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
procMutex = new System.Threading.Mutex(true, "_MUSICHE_MUTEX", out var result);
if (!result)
{
try
{
using (var clientStream = new NamedPipeClientStream(".", "_MUSICHE_PIPE", PipeDirection.InOut, PipeOptions.None))
{
clientStream.Connect();
}
}
catch (Exception)
{
}
Current.Shutdown();
System.Diagnostics.Process.GetCurrentProcess().Kill();
return;
}
MainWindow = new MainWindow();
MainWindow.Show();
}

protected override void OnExit(ExitEventArgs e)
{
procMutex?.ReleaseMutex();
base.OnExit(e);
}
}
}
2 changes: 1 addition & 1 deletion windows/LyricWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ private void SaveStatus()

private void SetIcons()
{
var uri = new Uri(Path.GetDirectoryName(Utils.IconFont.IconFontPath));
var uri = new Uri(Path.GetDirectoryName(Utils.File.IconFontPath));
FontFamily fontFamily = new FontFamily(uri.AbsoluteUri+"/#iconfont");
foreach (object item in IconPannel.Children)
{
Expand Down
26 changes: 25 additions & 1 deletion windows/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Net;
using System.Net.Sockets;
using System.Threading;
Expand Down Expand Up @@ -65,6 +66,25 @@ public MainWindow()
positionTimer.Stop();
mediaMetaManager.AudioStatusChanged += OnAudioStatusChanged;
}
InitNamedPipeServerStream();
}

private async void InitNamedPipeServerStream()
{
NamedPipeServerStream serverStream = new NamedPipeServerStream("_MUSICHE_PIPE", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
try
{
await serverStream.WaitForConnectionAsync();
Dispatcher.Invoke(() =>
{
ShowApp(null, null);
});
serverStream.Close();
}
catch (Exception)
{
}
InitNamedPipeServerStream();
}

private void UpdateAudioPosition(object sender, ElapsedEventArgs e)
Expand Down Expand Up @@ -107,7 +127,7 @@ private void MainWindow_SourceInitialized(object sender, EventArgs e)
webServer = new WebServer(54621);
webview2.Control.Source = new Uri("http://127.0.0.1:5173");
string exeDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
logStream = System.IO.File.Open(Path.Combine(exeDirectory, "log." + DateTime.Now.ToString("yyyy-MM-dd") + ".log"), FileMode.Append);
logStream = File.Open(Path.Combine(exeDirectory, "log." + DateTime.Now.ToString("yyyy-MM-dd") + ".log"), FileMode.Append);
#else
int port = GetAvailablePort();
webServer = new WebServer(port);
Expand Down Expand Up @@ -135,6 +155,7 @@ private void OnAudioStatusChanged(object sender, string message)
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
webSocketHandler.SendMessage("{\"type\": \"close\"}");
webview2?.SaveConfig();
}

private async void WebServer_ClientConnected(object sender, System.Net.HttpListenerContext context)
Expand Down Expand Up @@ -248,6 +269,9 @@ public void ExitApp(object sender, EventArgs e)
hotkey?.Clear();
logStream?.Close();
notifyIcon?.Dispose();
webview2?.SaveConfig();
webview2?.webview2?.Stop();
webview2?.webview2?.Dispose();
Application.Current.Shutdown();
}

Expand Down
2 changes: 1 addition & 1 deletion windows/NotifyIcon/ModernToolStripRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class ModernToolStripRenderer : ToolStripProfessionalRenderer
public ModernToolStripRenderer()
{
pfc = new System.Drawing.Text.PrivateFontCollection();
pfc.AddFontFile(Utils.IconFont.IconFontPath);
pfc.AddFontFile(Utils.File.IconFontPath);
iconFont = new Font(pfc.Families[0], 9, FontStyle.Bold);
}
protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e)
Expand Down
14 changes: 14 additions & 0 deletions windows/Utils/File.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,31 @@ public class File
public static readonly string AppName;
public static readonly string DataPath;
public static readonly string StoragePath;
public static readonly string ConfigPath;
public static readonly string Webview2Path;
public static readonly string DisableGPUName = "--disable-gpu";
public static readonly string IconFontPath;

static File()
{
Roming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
AppName = System.Reflection.Assembly.GetExecutingAssembly()?.GetName()?.Name?.ToString() ?? "Musiche";
DataPath = Path.Combine(Roming, AppName, "Data");
StoragePath = Path.Combine(DataPath, "Storage");
ConfigPath = Path.Combine(StoragePath, "config.json");
Webview2Path = Path.Combine(DataPath, "Webview2");
CreateDirectoryIFNotExists(StoragePath);
CreateDirectoryIFNotExists(Webview2Path);
IconFontPath = Path.Combine(DataPath, "music_he_icon_font.ttf");
WriteIconFont();
}

private static void WriteIconFont()
{
try
{
System.IO.File.WriteAllBytes(IconFontPath, Properties.Resources.iconfont);
}catch (Exception) { }
}

public static void CreateDirectoryIFNotExists(string path)
Expand Down
22 changes: 0 additions & 22 deletions windows/Utils/IconFont.cs

This file was deleted.

41 changes: 40 additions & 1 deletion windows/Webview2/FileAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,48 @@ namespace Musiche.Webview2
{
public class FileAccessor
{
private readonly Dictionary<string, string> _configMap;
public FileAccessor()
{
//Utils.File.CreateDirectoryIFNotExists(Utils.File.StoragePath);
if (File.Exists(Utils.File.ConfigPath))
{
try
{
_configMap = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(Utils.File.ConfigPath));
return;
}
catch (Exception)
{
}
}
_configMap = new Dictionary<string, string>();
}

public void SaveConfig()
{
try
{
File.WriteAllText(Utils.File.ConfigPath, JsonConvert.SerializeObject(_configMap));
}
catch (Exception)
{
}
}

public string ReadConfig(string key)
{
_configMap.TryGetValue(key, out string value);
return string.IsNullOrEmpty(value) ? string.Empty : value;
}

public void WriteConfig(string key, string value)
{
_configMap[key] = value;
}

public void DeleteConfig(string key)
{
_configMap.Remove(key);
}

#pragma warning disable CS1998
Expand Down
Loading

0 comments on commit 3b5c428

Please sign in to comment.