removal of TaskDialog usage...

This commit is contained in:
Frank Skare
2021-05-23 19:30:21 +02:00
parent 0b28770d1a
commit eaa8a3ca6c
59 changed files with 1035 additions and 7065 deletions

View File

@@ -6,15 +6,13 @@ using System.IO;
using System.Windows.Forms;
using System.Threading.Tasks;
using static mpvnet.Core;
using static TaskDialog.Msg;
using static mpvnet.Global;
namespace mpvnet
{
public static class App
{
public static string RegPath { get; } = @"HKCU\Software\" + Application.ProductName;
public static string ConfPath { get => core.ConfigFolder + "mpvnet.conf"; }
public static string ConfPath { get => Core.ConfigFolder + "mpvnet.conf"; }
public static string ProcessInstance { get; set; } = "single";
public static string DarkMode { get; set; } = "always";
public static string DarkTheme { get; set; } = "dark";
@@ -43,8 +41,8 @@ namespace mpvnet
public static void Init()
{
string dummy = core.ConfigFolder;
var dummy2 = core.Conf;
string dummy = Core.ConfigFolder;
var dummy2 = Core.Conf;
foreach (var i in Conf)
ProcessProperty(i.Key, i.Value, true);
@@ -53,7 +51,7 @@ namespace mpvnet
{
try
{
string filePath = core.ConfigFolder + "mpvnet-debug.log";
string filePath = Core.ConfigFolder + "mpvnet-debug.log";
if (File.Exists(filePath))
File.Delete(filePath);
@@ -72,16 +70,16 @@ namespace mpvnet
string themeContent = null;
if (File.Exists(core.ConfigFolder + "theme.conf"))
themeContent = File.ReadAllText(core.ConfigFolder + "theme.conf");
if (File.Exists(Core.ConfigFolder + "theme.conf"))
themeContent = File.ReadAllText(Core.ConfigFolder + "theme.conf");
Theme.Init(
themeContent,
Properties.Resources.theme,
IsDarkMode ? DarkTheme : LightTheme);
core.Shutdown += Shutdown;
core.Initialized += Initialized;
Core.Shutdown += Shutdown;
Core.Initialized += Initialized;
}
public static void RunTask(Action action)
@@ -99,34 +97,32 @@ namespace mpvnet
get {
return "Copyright (C) 2000-2021 mpv.net/mpv/mplayer\n" +
$"mpv.net {Application.ProductVersion} ({File.GetLastWriteTime(Application.ExecutablePath).ToShortDateString()})\n" +
$"{core.get_property_string("mpv-version")} ({File.GetLastWriteTime(Folder.Startup + "mpv-1.dll").ToShortDateString()})\nffmpeg {core.get_property_string("ffmpeg-version")}\nMIT License";
$"{Core.get_property_string("mpv-version")} ({File.GetLastWriteTime(Folder.Startup + "mpv-1.dll").ToShortDateString()})\nffmpeg {Core.get_property_string("ffmpeg-version")}\nMIT License";
}
}
public static void ShowException(object obj)
{
if (obj is Exception e)
{
if (IsStartedFromTerminal)
ConsoleHelp.WriteError(e.ToString());
else
Msg.ShowException(e);
}
if (IsStartedFromTerminal)
Terminal.WriteError(obj.ToString());
else
{
if (IsStartedFromTerminal)
ConsoleHelp.WriteError(obj.ToString());
if (obj is Exception e)
Msg.ShowException(e);
else
MsgError(obj.ToString());
Msg.ShowError(obj.ToString());
}
}
public static void ShowError(string title, string msg)
public static void ShowError(string title, string msg = null)
{
if (IsStartedFromTerminal)
{
ConsoleHelp.WriteError(title);
ConsoleHelp.WriteError(msg);
if (title != null)
Terminal.WriteError(title);
if (msg != null)
Terminal.WriteError(msg);
}
else
Msg.ShowError(title, msg);
@@ -136,8 +132,8 @@ namespace mpvnet
{
if (RememberVolume)
{
core.set_property_int("volume", RegistryHelp.GetInt("Volume", 70));
core.set_property_string("mute", RegistryHelp.GetString("Mute", "no"));
Core.set_property_int("volume", RegistryHelp.GetInt("volume", 70));
Core.set_property_string("mute", RegistryHelp.GetString("mute", "no"));
}
}
@@ -145,8 +141,8 @@ namespace mpvnet
{
if (RememberVolume)
{
RegistryHelp.SetValue(RegPath, "Volume", core.get_property_int("volume"));
RegistryHelp.SetValue(RegPath, "Mute", core.get_property_string("mute"));
RegistryHelp.SetInt("volume", Core.get_property_int("volume"));
RegistryHelp.SetString("mute", Core.get_property_string("mute"));
}
}
@@ -185,31 +181,31 @@ namespace mpvnet
case "minimum-aspect-ratio": MinimumAspectRatio = value.ToFloat(); return true;
case "dark-theme": DarkTheme = value.Trim('\'', '"'); return true;
case "light-theme": LightTheme = value.Trim('\'', '"'); return true;
case "video-file-extensions": VideoTypes = value.Split(" ,;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); return true;
case "audio-file-extensions": AudioTypes = value.Split(" ,;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); return true;
case "image-file-extensions": ImageTypes = value.Split(" ,;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); return true;
case "video-file-extensions": CorePlayer.VideoTypes = value.Split(" ,;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); return true;
case "audio-file-extensions": CorePlayer.AudioTypes = value.Split(" ,;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); return true;
case "image-file-extensions": CorePlayer.ImageTypes = value.Split(" ,;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); return true;
default:
if (writeError)
ConsoleHelp.WriteError($"unknown mpvnet.conf property: {name}");
Terminal.WriteError($"unknown mpvnet.conf property: {name}");
return false;
}
}
public static void ShowSetup()
{
int value = RegistryHelp.GetInt(Folder.Startup);
int value = RegistryHelp.GetInt("location: " + Folder.Startup);
if (value != 1)
{
if (Msg.ShowQuestion("Would you like to setup mpv.net?",
"The setup allows to create a start menu shortcut, file associations and " +
"adding mpv.net to the Path environment variable.") == MsgResult.OK)
"adding mpv.net to the Path environment variable.") == DialogResult.OK)
Commands.Execute("show-setup-dialog");
else
MsgInfo("The setup dialog can be found in the context menu at:\n\nTools > Setup");
Msg.ShowInfo("The setup dialog can be found at:\n\nContext Menu > Tools > Setup");
RegistryHelp.SetValue(RegistryHelp.ApplicationKey, Folder.Startup, 1);
RegistryHelp.SetInt("location: " + Folder.Startup, 1);
}
}
}

View File

@@ -33,7 +33,14 @@ namespace mpvnet
Compile(outputFile, file);
if (File.Exists(outputFile))
References.Add(Assembly.LoadFile(outputFile).CreateInstance("Script"));
{
object instance = Assembly.LoadFile(outputFile).CreateInstance("Script");
if (instance != null)
References.Add(instance);
else
Terminal.WriteError("Failed to initialize script.", outputFile.FileName());
}
}
public static void Compile(string outputFile, string file)
@@ -42,6 +49,7 @@ namespace mpvnet
CompilerParameters parameters = new CompilerParameters();
string[] dependencies = {
Folder.Startup + "mpvnet.exe",
"Microsoft.VisualBasic.dll",
"System.Core.dll", "System.Data.dll", "System.dll", "System.Drawing.dll", "System.Web.dll",
"System.Windows.Forms.dll", "System.Xaml.dll", "System.Xml.dll", "System.Xml.Linq.dll",
@@ -55,10 +63,10 @@ namespace mpvnet
CompilerResults results = provider.CompileAssemblyFromFile(parameters, file);
var errors = results.Errors.Cast<CompilerError>().Select(i => "Line Number " +
i.Line + "\r\n" + "Error Number: " + i.ErrorNumber + "\r\n" + i.ErrorText);
i.Line + "\n" + "Error Number: " + i.ErrorNumber + "\n" + i.ErrorText);
if (errors.Count() > 0)
ConsoleHelp.WriteError(string.Join("\r\n\r\n", errors), Path.GetFileName(file));
Terminal.WriteError(string.Join("\n\n", errors), Path.GetFileName(file));
}
static string GetMD5(string code)

View File

@@ -10,8 +10,7 @@ using System.Windows;
using VB = Microsoft.VisualBasic;
using static mpvnet.NewLine;
using static mpvnet.Core;
using static mpvnet.Global;
namespace mpvnet
{
@@ -23,21 +22,19 @@ namespace mpvnet
{
case "add-files-to-playlist": OpenFiles("append"); break; // deprecated 2019
case "cycle-audio": CycleAudio(); break;
case "execute-mpv-command": ExecuteMpvCommand(); break;
case "execute-mpv-command": Msg.ShowError("Command was removed, reset input.conf."); break;
case "load-audio": LoadAudio(); break;
case "load-sub": LoadSubtitle(); break;
case "manage-file-associations": // deprecated 2019
case "open-conf-folder": ProcessHelp.ShellExecute(core.ConfigFolder); break;
case "open-conf-folder": ProcessHelp.ShellExecute(Core.ConfigFolder); break;
case "open-files": OpenFiles(args); break;
case "open-optical-media": Open_DVD_Or_BD_Folder(); break;
case "open-url": OpenURL(); break;
case "playlist-first": PlaylistFirst(); break;
case "playlist-last": PlaylistLast(); break;
case "scale-window": ScaleWindow(float.Parse(args[0], CultureInfo.InvariantCulture)); break;
case "window-scale": WindowScale(float.Parse(args[0], CultureInfo.InvariantCulture)); break;
case "shell-execute": ProcessHelp.ShellExecute(args[0]); break;
case "show-about": ShowDialog(typeof(AboutWindow)); break;
case "show-audio-devices": ShowTextWithEditor("audio-device-list", core.get_property_osd_string("audio-device-list")); break;
case "show-audio-devices": ShowTextWithEditor("audio-device-list", Core.get_property_osd_string("audio-device-list")); break;
case "show-command-palette": ShowDialog(typeof(CommandPaletteWindow)); break;
case "show-commands": ShowCommands(); break;
case "show-conf-editor": ShowDialog(typeof(ConfWindow)); break;
@@ -46,15 +43,16 @@ namespace mpvnet
case "show-history": ShowHistory(); break;
case "show-info": ShowInfo(); break;
case "show-input-editor": ShowDialog(typeof(InputWindow)); break;
case "show-keys": ShowTextWithEditor("input-key-list", core.get_property_string("input-key-list").Replace(",", BR)); break;
case "show-keys": ShowTextWithEditor("input-key-list", Core.get_property_string("input-key-list").Replace(",", BR)); break;
case "show-media-search": ShowDialog(typeof(EverythingWindow)); break;
case "show-profiles": ShowTextWithEditor("profile-list", mpvHelp.GetProfiles()); break;
case "show-playlist": ShowPlaylist(); break;
case "show-profiles": ShowTextWithEditor("profile-list", mpvHelp.GetProfiles()); break;
case "show-properties": ShowProperties(); break;
case "show-protocols": ShowTextWithEditor("protocol-list", mpvHelp.GetProtocols()); break;
case "show-setup-dialog": ShowDialog(typeof(SetupWindow)); break;
case "show-text": ShowText(args[0], Convert.ToInt32(args[1]), Convert.ToInt32(args[2])); break;
case "update-check": UpdateCheck.CheckOnline(true); break;
case "window-scale": WindowScale(float.Parse(args[0], CultureInfo.InvariantCulture)); break;
default: Msg.ShowError($"No command '{id}' found."); break;
}
@@ -85,7 +83,7 @@ namespace mpvnet
InvokeOnMainThread(new Action(() => {
using (var d = new OpenFileDialog() { Multiselect = true })
if (d.ShowDialog() == DialogResult.OK)
core.LoadFiles(d.FileNames, loadFolder, append);
Core.LoadFiles(d.FileNames, loadFolder, append);
}));
}
@@ -99,18 +97,18 @@ namespace mpvnet
if (dialog.ShowDialog() == DialogResult.OK)
{
core.command("stop");
Core.command("stop");
Thread.Sleep(500);
if (Directory.Exists(dialog.SelectedPath + "\\BDMV"))
{
core.set_property_string("bluray-device", dialog.SelectedPath);
core.LoadFiles(new[] { @"bd://" }, false, false);
Core.set_property_string("bluray-device", dialog.SelectedPath);
Core.LoadFiles(new[] { @"bd://" }, false, false);
}
else
{
core.set_property_string("dvd-device", dialog.SelectedPath);
core.LoadFiles(new[] { @"dvd://" }, false, false);
Core.set_property_string("dvd-device", dialog.SelectedPath);
Core.LoadFiles(new[] { @"dvd://" }, false, false);
}
}
}
@@ -119,31 +117,31 @@ namespace mpvnet
public static void PlaylistFirst()
{
int pos = core.get_property_int("playlist-pos");
int pos = Core.get_property_int("playlist-pos");
if (pos != 0)
core.set_property_int("playlist-pos", 0);
Core.set_property_int("playlist-pos", 0);
}
public static void PlaylistLast()
{
int pos = core.get_property_int("playlist-pos");
int count = core.get_property_int("playlist-count");
int pos = Core.get_property_int("playlist-pos");
int count = Core.get_property_int("playlist-count");
if (pos < count - 1)
core.set_property_int("playlist-pos", count - 1);
Core.set_property_int("playlist-pos", count - 1);
}
public static void ShowHistory()
{
if (File.Exists(core.ConfigFolder + "history.txt"))
ProcessHelp.ShellExecute(core.ConfigFolder + "history.txt");
if (File.Exists(Core.ConfigFolder + "history.txt"))
ProcessHelp.ShellExecute(Core.ConfigFolder + "history.txt");
else
{
if (Msg.ShowQuestion("Create history.txt file in config folder?",
"mpv.net will write the date, time and filename of opened files to it.") == MsgResult.OK)
"mpv.net will write the date, time and filename of opened files to it.") == DialogResult.OK)
File.WriteAllText(core.ConfigFolder + "history.txt", "");
File.WriteAllText(Core.ConfigFolder + "history.txt", "");
}
}
@@ -153,19 +151,19 @@ namespace mpvnet
{
string performer, title, album, genre, date, duration, text = "";
long fileSize = 0;
string path = core.get_property_string("path");
string path = Core.get_property_string("path");
if (path.Contains("://"))
path = core.get_property_string("media-title");
path = Core.get_property_string("media-title");
int width = core.get_property_int("video-params/w");
int height = core.get_property_int("video-params/h");
int width = Core.get_property_int("video-params/w");
int height = Core.get_property_int("video-params/h");
if (File.Exists(path))
{
fileSize = new FileInfo(path).Length;
if (AudioTypes.Contains(path.Ext()))
if (CorePlayer.AudioTypes.Contains(path.Ext()))
{
using (MediaInfo mediaInfo = new MediaInfo(path))
{
@@ -185,11 +183,11 @@ namespace mpvnet
text += "Size: " + mediaInfo.GetInfo(MediaInfoStreamKind.General, "FileSize/String") + "\n";
text += "Type: " + path.Ext().ToUpper();
core.commandv("show-text", text, "5000");
Core.commandv("show-text", text, "5000");
return;
}
}
else if (ImageTypes.Contains(path.Ext()))
else if (CorePlayer.ImageTypes.Contains(path.Ext()))
{
using (MediaInfo mediaInfo = new MediaInfo(path))
{
@@ -199,16 +197,16 @@ namespace mpvnet
"Size: " + mediaInfo.GetInfo(MediaInfoStreamKind.General, "FileSize/String") + "\n" +
"Type: " + path.Ext().ToUpper();
core.commandv("show-text", text, "5000");
Core.commandv("show-text", text, "5000");
return;
}
}
}
TimeSpan position = TimeSpan.FromSeconds(core.get_property_number("time-pos"));
TimeSpan duration2 = TimeSpan.FromSeconds(core.get_property_number("duration"));
string videoFormat = core.get_property_string("video-format").ToUpper();
string audioCodec = core.get_property_string("audio-codec-name").ToUpper();
TimeSpan position = TimeSpan.FromSeconds(Core.get_property_number("time-pos"));
TimeSpan duration2 = TimeSpan.FromSeconds(Core.get_property_number("duration"));
string videoFormat = Core.get_property_string("video-format").ToUpper();
string audioCodec = Core.get_property_string("audio-codec-name").ToUpper();
text = path.FileName() + "\n" +
FormatTime(position.TotalMinutes) + ":" +
@@ -222,7 +220,7 @@ namespace mpvnet
text += $"{videoFormat}\n{audioCodec}";
core.commandv("show-text", text, "5000");
Core.commandv("show-text", text, "5000");
string FormatTime(double value) => ((int)value).ToString("00");
}
catch (Exception e)
@@ -230,19 +228,6 @@ namespace mpvnet
App.ShowException(e);
}
}
public static void ExecuteMpvCommand() // deprecated 2019
{
InvokeOnMainThread(new Action(() => {
string command = VB.Interaction.InputBox("Enter a mpv command to be executed.", "Execute Command", RegistryHelp.GetString("RecentExecutedCommand"));
if (string.IsNullOrEmpty(command))
return;
RegistryHelp.SetValue(App.RegPath, "RecentExecutedCommand", command);
core.command(command, false);
}));
}
public static void OpenURL()
{
@@ -256,7 +241,7 @@ namespace mpvnet
return;
}
core.LoadFiles(new [] { clipboard }, false, Control.ModifierKeys.HasFlag(Keys.Control));
Core.LoadFiles(new [] { clipboard }, false, Control.ModifierKeys.HasFlag(Keys.Control));
}));
}
@@ -265,7 +250,7 @@ namespace mpvnet
InvokeOnMainThread(new Action(() => {
using (var d = new OpenFileDialog())
{
string path = core.get_property_string("path");
string path = Core.get_property_string("path");
if (File.Exists(path))
d.InitialDirectory = Path.GetDirectoryName(path);
@@ -274,7 +259,7 @@ namespace mpvnet
if (d.ShowDialog() == DialogResult.OK)
foreach (string filename in d.FileNames)
core.commandv("sub-add", filename);
Core.commandv("sub-add", filename);
}
}));
}
@@ -284,40 +269,40 @@ namespace mpvnet
InvokeOnMainThread(new Action(() => {
using (var d = new OpenFileDialog())
{
string path = core.get_property_string("path");
string path = Core.get_property_string("path");
if (File.Exists(path))
d.InitialDirectory = Path.GetDirectoryName(path);
d.Multiselect = true;
if (d.ShowDialog() == DialogResult.OK)
foreach (string i in d.FileNames)
core.commandv("audio-add", i);
Core.commandv("audio-add", i);
}
}));
}
public static void CycleAudio()
{
MediaTrack[] audioTracks = core.MediaTracks.Where(track => track.Type == "a").ToArray();
MediaTrack[] audioTracks = Core.MediaTracks.Where(track => track.Type == "a").ToArray();
int len = audioTracks.Length;
if (len < 1)
{
core.commandv("show-text", "No audio tracks");
Core.commandv("show-text", "No audio tracks");
return;
}
int aid = core.get_property_int("aid");
int aid = Core.get_property_int("aid");
if (len > 1)
{
if (++aid > len)
aid = 1;
core.commandv("set", "aid", aid.ToString());
Core.commandv("set", "aid", aid.ToString());
}
core.commandv("show-text", aid + "/" + len + ": " + audioTracks[aid - 1].Text.Substring(3), "5000");
Core.commandv("show-text", aid + "/" + len + ": " + audioTracks[aid - 1].Text.Substring(3), "5000");
}
public static void ShowCommands()
@@ -341,13 +326,13 @@ namespace mpvnet
}
}";
string json = core.get_property_string("command-list");
string json = Core.get_property_string("command-list");
ShowTextWithEditor("command-list", PowerShell.InvokeAndReturnString(code, "json", json));
}
public static void ShowProperties()
{
var props = core.get_property_string("property-list").Split(',').OrderBy(prop => prop);
var props = Core.get_property_string("property-list").Split(',').OrderBy(prop => prop);
ShowTextWithEditor("property-list", string.Join(BR, props));
}
@@ -358,9 +343,9 @@ namespace mpvnet
ProcessHelp.ShellExecute(file);
}
public static void ScaleWindow(float factor) => core.RaiseScaleWindow(factor);
public static void ScaleWindow(float factor) => Core.RaiseScaleWindow(factor);
public static void WindowScale(float value) => core.RaiseWindowScale(value);
public static void WindowScale(float value) => Core.RaiseWindowScale(value);
public static void ShowText(string text, int duration = 0, int fontSize = 0)
{
@@ -368,12 +353,12 @@ namespace mpvnet
return;
if (duration == 0)
duration = core.get_property_int("osd-duration");
duration = Core.get_property_int("osd-duration");
if (fontSize == 0)
fontSize = core.get_property_int("osd-font-size");
fontSize = Core.get_property_int("osd-font-size");
core.command("show-text \"${osd-ass-cc/0}{\\\\fs" + fontSize +
Core.command("show-text \"${osd-ass-cc/0}{\\\\fs" + fontSize +
"}${osd-ass-cc/1}" + text + "\" " + duration);
}
@@ -384,13 +369,13 @@ namespace mpvnet
if (args?.Length == 1)
duration = Convert.ToInt32(args[0]);
var size = core.get_property_number("osd-font-size");
core.set_property_number("osd-font-size", 40);
core.command("show-text ${playlist} " + duration);
var size = Core.get_property_number("osd-font-size");
Core.set_property_number("osd-font-size", 40);
Core.command("show-text ${playlist} " + duration);
App.RunTask(() => {
Thread.Sleep(6000);
core.set_property_number("osd-font-size", size);
Core.set_property_number("osd-font-size", size);
});
}
}

View File

@@ -6,7 +6,7 @@ using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using static mpvnet.Core;
using static mpvnet.Global;
namespace mpvnet
{
@@ -33,14 +33,14 @@ namespace mpvnet
if (knownExtensions.Contains(Path.GetFileName(extDir)))
catalog.Catalogs.Add(new DirectoryCatalog(extDir, Path.GetFileName(extDir) + ".dll"));
else
ConsoleHelp.WriteError("Failed to load extension:\n\n" + extDir +
Terminal.WriteError("Failed to load extension:\n\n" + extDir +
"\n\nOnly extensions that ship with mpv.net are allowed in <startup>\\extensions" +
"\n\nUser extensions have to use <config folder>\\extensions" +
"\n\nNever copy or install a new mpv.net version over a old mpv.net version.");
}
}
dir = core.ConfigFolder + "extensions";
dir = Core.ConfigFolder + "extensions";
if (Directory.Exists(dir))
foreach (string extDir in Directory.GetDirectories(dir))

View File

@@ -2,7 +2,7 @@
using System.Globalization;
using System.IO;
public static class Extensions
public static class TestStringExtension
{
public static bool ContainsEx(this string instance, string value)
{
@@ -19,11 +19,14 @@ public static class Extensions
return false;
}
}
public static class ConvertToStringExtension
{
public static string ToUpperEx(this string instance)
{
if (instance != null)
return instance.ToUpper();
return instance.ToUpperInvariant();
return "";
}
@@ -31,11 +34,48 @@ public static class Extensions
public static string ToLowerEx(this string instance)
{
if (instance != null)
return instance.ToLower();
return instance.ToLowerInvariant();
return "";
}
public static string TrimEx(this string instance)
{
if (instance == null)
return "";
return instance.Trim();
}
}
public static class ConvertStringExtension
{
public static int ToInt(this string instance)
{
int.TryParse(instance, out int result);
return result;
}
public static float ToFloat(this string instance)
{
float.TryParse(instance.Replace(",", "."), NumberStyles.Float,
CultureInfo.InvariantCulture, out float result);
return result;
}
}
public static class PathStringExtension
{
// return extension with lower case and without dot.
public static string Ext(this string instance)
{
if (instance == null)
return "";
return Path.GetExtension(instance).TrimStart('.').ToLower();
}
public static string FileName(this string instance)
{
if (string.IsNullOrEmpty(instance))
@@ -54,25 +94,23 @@ public static class Extensions
return instance;
}
public static string Ext(this string instance)
// Ensure trailing directory separator char
public static string AddSep(this string instance)
{
if (instance == null)
if (string.IsNullOrEmpty(instance))
return "";
return Path.GetExtension(instance).TrimStart('.').ToLower();
if (!instance.EndsWith(Path.DirectorySeparatorChar.ToString()))
instance = instance + Path.DirectorySeparatorChar;
return instance;
}
public static int ToInt(this string instance)
public static bool IsIdenticalFolder(this string instance, string testFolder)
{
int.TryParse(instance, out int result);
return result;
}
if (string.IsNullOrEmpty(instance) || string.IsNullOrEmpty(testFolder))
return false;
public static float ToFloat(this string instance)
{
float.TryParse(instance.Replace(",", "."), NumberStyles.Float,
CultureInfo.InvariantCulture, out float result);
return result;
return instance.ToLowerInvariant().AddSep() == testFolder.ToLowerInvariant().AddSep();
}
}

13
src/Misc/Global.cs Normal file
View File

@@ -0,0 +1,13 @@

using System;
namespace mpvnet
{
public class Global
{
public static string BR = Environment.NewLine;
public static string BR2 = Environment.NewLine + Environment.NewLine;
public static CorePlayer Core { get; } = new CorePlayer();
}
}

View File

@@ -5,7 +5,7 @@ using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using static mpvnet.Core;
using static mpvnet.Global;
namespace mpvnet
{
@@ -18,7 +18,7 @@ namespace mpvnet
public static void RegisterGlobalHotkeys(IntPtr hwnd)
{
HWND = hwnd;
string path = core.ConfigFolder + "global-input.conf";
string path = Core.ConfigFolder + "global-input.conf";
if (!File.Exists(path))
return;
@@ -82,14 +82,14 @@ namespace mpvnet
bool success = RegisterHotKey(HWND, ID++, mod, vk);
if (!success)
ConsoleHelp.WriteError(line + ": " + new Win32Exception().Message + "\n", "global-input.conf");
Terminal.WriteError(line + ": " + new Win32Exception().Message + "\n", "global-input.conf");
}
}
public static void Execute(int id)
{
if (Commands.ContainsKey(id))
core.command(Commands[id]);
Core.command(Commands[id]);
}
static int mpv_to_VK(string value)

View File

@@ -7,8 +7,7 @@ using System.Windows.Forms;
using Microsoft.Win32;
using static mpvnet.Core;
using static mpvnet.NewLine;
using static mpvnet.Global;
namespace mpvnet
{
@@ -37,55 +36,6 @@ namespace mpvnet
}
}
public static class ConsoleHelp
{
public static int Padding { get; set; }
public static void WriteError(object obj, string module = "mpv.net")
{
Write(obj, module, ConsoleColor.DarkRed, false);
}
public static void Write(object obj, string module = "mpv.net")
{
Write(obj, module, ConsoleColor.Black, true);
}
public static void Write(object obj, string module, ConsoleColor color)
{
Write(obj, module, color, false);
}
public static void Write(object obj, string module, ConsoleColor color, bool useDefaultColor)
{
if (obj == null)
return;
string value = obj.ToString();
if (!string.IsNullOrEmpty(module))
module = "[" + module + "] ";
if (useDefaultColor)
Console.ResetColor();
else
Console.ForegroundColor = color;
value = module + value;
if (Padding > 0 && value.Length < Padding)
value = value.PadRight(Padding);
if (color == ConsoleColor.Red || color == ConsoleColor.DarkRed)
Console.Error.WriteLine(value);
else
Console.WriteLine(value);
Console.ResetColor();
Trace.WriteLine(obj);
}
}
public class CursorHelp
{
static bool IsVisible = true;
@@ -134,7 +84,7 @@ namespace mpvnet
''
}";
string json = core.get_property_string("profile-list");
string json = Core.get_property_string("profile-list");
return PowerShell.InvokeAndReturnString(code, "json", json).Trim();
}
@@ -146,19 +96,19 @@ namespace mpvnet
$item.codec + ' - ' + $item.description
}";
string json = core.get_property_string("decoder-list");
string json = Core.get_property_string("decoder-list");
return PowerShell.InvokeAndReturnString(code, "json", json).Trim();
}
public static string GetProtocols()
{
string list = core.get_property_string("protocol-list");
string list = Core.get_property_string("protocol-list");
return string.Join(BR, list.Split(',').OrderBy(a => a));
}
public static string GetDemuxers()
{
string list = core.get_property_string("demuxer-lavf-list");
string list = Core.get_property_string("demuxer-lavf-list");
return string.Join(BR, list.Split(',').OrderBy(a => a));
}
}
@@ -172,6 +122,17 @@ namespace mpvnet
SetValue(ApplicationKey, name, value);
}
public static void SetString(string name, string value)
{
SetValue(ApplicationKey, name, value);
}
public static void SetValue(string name, object value)
{
using (RegistryKey regKey = GetRootKey(ApplicationKey).CreateSubKey(ApplicationKey.Substring(5), RegistryKeyPermissionCheck.ReadWriteSubTree))
regKey.SetValue(name, value);
}
public static void SetValue(string path, string name, object value)
{
using (RegistryKey regKey = GetRootKey(path).CreateSubKey(path.Substring(5), RegistryKeyPermissionCheck.ReadWriteSubTree))
@@ -190,6 +151,8 @@ namespace mpvnet
return !(value is int) ? defaultValue : (int)value;
}
public static object GetValue(string name) => GetValue(ApplicationKey, name, null);
public static object GetValue(string path, string name, object defaultValue = null)
{
using (RegistryKey regKey = GetRootKey(path).OpenSubKey(path.Substring(5)))

View File

@@ -13,16 +13,10 @@ using System.Windows.Forms;
using Microsoft.Win32;
using static mpvnet.Core;
using static mpvnet.Global;
namespace mpvnet
{
public static class NewLine
{
public static string BR = Environment.NewLine;
public static string BR2 = Environment.NewLine + Environment.NewLine;
}
public class Sys
{
public static bool IsDarkTheme {
@@ -102,13 +96,13 @@ namespace mpvnet
RegistryHelp.SetValue($@"HKCR\" + "." + ext, null, ExeFilenameNoExt + "." + ext);
RegistryHelp.SetValue($@"HKCR\" + "." + ext + @"\OpenWithProgIDs", ExeFilenameNoExt + "." + ext, "");
if (VideoTypes.Contains(ext))
if (CorePlayer.VideoTypes.Contains(ext))
RegistryHelp.SetValue(@"HKCR\" + "." + ext, "PerceivedType", "video");
if (AudioTypes.Contains(ext))
if (CorePlayer.AudioTypes.Contains(ext))
RegistryHelp.SetValue(@"HKCR\" + "." + ext, "PerceivedType", "audio");
if (ImageTypes.Contains(ext))
if (CorePlayer.ImageTypes.Contains(ext))
RegistryHelp.SetValue(@"HKCR\" + "." + ext, "PerceivedType", "image");
RegistryHelp.SetValue($@"HKCR\" + ExeFilenameNoExt + "." + ext + @"\shell\open\command", null, $"\"{ExePath}\" \"%1\"");
@@ -203,7 +197,7 @@ namespace mpvnet
public static ObservableCollection<CommandItem> Items {
get {
if (_Items is null)
_Items = GetItems(File.ReadAllText(core.InputConfPath));
_Items = GetItems(File.ReadAllText(Core.InputConfPath));
return _Items;
}
@@ -212,6 +206,26 @@ namespace mpvnet
public class Folder
{
public static string Startup { get; } = Application.StartupPath + @"\";
public static string Startup { get; } = Application.StartupPath.AddSep();
public static string AppData { get; } = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).AddSep();
public static string CustomSettings {
get {
string linkFile = Startup + "settings-directory.txt";
if (File.Exists(linkFile))
{
string linkTarget = File.ReadAllText(linkFile).Trim();
if (linkTarget.StartsWithEx("."))
linkTarget = Startup + linkTarget;
if (Directory.Exists(linkTarget))
return linkTarget.AddSep();
}
return "";
}
}
}
}

39
src/Misc/Msg.cs Normal file
View File

@@ -0,0 +1,39 @@

using System;
using System.Windows.Forms;
public class Msg
{
public static void ShowInfo(object title, object content = null)
{
Show(title, content, MessageBoxIcon.Information);
}
public static void ShowError(object title, object content = null)
{
Show(title, content, MessageBoxIcon.Error);
}
public static void ShowWarning(object title, object content = null)
{
Show(title, content, MessageBoxIcon.Warning);
}
public static DialogResult ShowQuestion(object title, object content = null,
MessageBoxButtons buttons = MessageBoxButtons.OKCancel)
{
return Show(title, content, MessageBoxIcon.Question, buttons);
}
public static void ShowException(Exception exception)
{
Show(exception, null, MessageBoxIcon.Error);
}
public static DialogResult Show(object title, object content, MessageBoxIcon icon,
MessageBoxButtons buttons = MessageBoxButtons.OK)
{
string msg = (title?.ToString().TrimEx() + "\n\n" + content?.ToString().TrimEx()).Trim();
return MessageBox.Show(msg, Application.ProductName, buttons, icon);
}
}

View File

@@ -6,8 +6,7 @@ using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;
using static mpvnet.Core;
using static mpvnet.NewLine;
using static mpvnet.Global;
namespace mpvnet
{
@@ -90,7 +89,7 @@ namespace mpvnet
var output = sender as PipelineReader<PSObject>;
while (output.Count > 0)
ConsoleHelp.Write(output.Read(), Module);
Terminal.Write(output.Read(), Module);
}
public void Error_DataReady(object sender, EventArgs e)
@@ -98,7 +97,7 @@ namespace mpvnet
var output = sender as PipelineReader<Object>;
while (output.Count > 0)
ConsoleHelp.WriteError(output.Read(), Module);
Terminal.WriteError(output.Read(), Module);
}
public void RedirectStreams(PSEventJob job)
@@ -110,25 +109,25 @@ namespace mpvnet
}
}
public void commandv(params string[] args) => core.commandv(args);
public void commandv(params string[] args) => Core.commandv(args);
public void command(string command) => core.command(command);
public void command(string command) => Core.command(command);
public bool get_property_bool(string name) => core.get_property_bool(name);
public bool get_property_bool(string name) => Core.get_property_bool(name);
public void set_property_bool(string name, bool value) => core.set_property_bool(name, value);
public void set_property_bool(string name, bool value) => Core.set_property_bool(name, value);
public int get_property_int(string name) => core.get_property_int(name);
public int get_property_int(string name) => Core.get_property_int(name);
public void set_property_int(string name, int value) => core.set_property_int(name, value);
public void set_property_int(string name, int value) => Core.set_property_int(name, value);
public double get_property_number(string name) => core.get_property_number(name);
public double get_property_number(string name) => Core.get_property_number(name);
public void set_property_number(string name, double value) => core.set_property_number(name, value);
public void set_property_number(string name, double value) => Core.set_property_number(name, value);
public string get_property_string(string name) => core.get_property_string(name);
public string get_property_string(string name) => Core.get_property_string(name);
public void set_property_string(string name, string value) => core.set_property_string(name, value);
public void set_property_string(string name, string value) => Core.set_property_string(name, value);
public void observe_property(string name, string type, ScriptBlock sb)
{
@@ -137,19 +136,19 @@ namespace mpvnet
switch (type)
{
case "bool": case "boolean":
core.observe_property_bool(name, value => App.RunTask(() => PropertyChanged.Invoke(name, value)));
Core.observe_property_bool(name, value => App.RunTask(() => PropertyChanged.Invoke(name, value)));
break;
case "string":
core.observe_property_string(name, value => App.RunTask(() => PropertyChanged.Invoke(name, value)));
Core.observe_property_string(name, value => App.RunTask(() => PropertyChanged.Invoke(name, value)));
break;
case "int": case "integer":
core.observe_property_int(name, value => App.RunTask(() => PropertyChanged.Invoke(name, value)));
Core.observe_property_int(name, value => App.RunTask(() => PropertyChanged.Invoke(name, value)));
break;
case "float": case "double":
core.observe_property_double(name, value => App.RunTask(() => PropertyChanged.Invoke(name, value)));
Core.observe_property_double(name, value => App.RunTask(() => PropertyChanged.Invoke(name, value)));
break;
case "nil": case "none": case "native":
core.observe_property(name, () => App.RunTask(() => PropertyChanged.Invoke(name, null)));
Core.observe_property(name, () => App.RunTask(() => PropertyChanged.Invoke(name, null)));
break;
default:
App.ShowError("Invalid Type", "Valid types are: bool or boolean, string, int or integer, float or double, nil or none or native");
@@ -164,59 +163,59 @@ namespace mpvnet
switch (name)
{
case "log-message":
core.LogMessageAsync += (level, msg) => Event.Invoke("log-message", new object[] { level, msg });
Core.LogMessageAsync += (level, msg) => Event.Invoke("log-message", new object[] { level, msg });
break;
case "end-file":
core.EndFileAsync += reason => Event.Invoke("end-file", new object[] { reason });
Core.EndFileAsync += reason => Event.Invoke("end-file", new object[] { reason });
break;
case "client-message":
core.ClientMessageAsync += args => Event.Invoke("client-message", args);
Core.ClientMessageAsync += args => Event.Invoke("client-message", args);
break;
case "shutdown":
core.Shutdown += () => Event.Invoke("shutdown", null);
Core.Shutdown += () => Event.Invoke("shutdown", null);
break;
case "get-property-reply":
core.GetPropertyReplyAsync += () => Event.Invoke("get-property-reply", null);
Core.GetPropertyReplyAsync += () => Event.Invoke("get-property-reply", null);
break;
case "set-property-reply":
core.SetPropertyReplyAsync += () => Event.Invoke("set-property-reply", null);
Core.SetPropertyReplyAsync += () => Event.Invoke("set-property-reply", null);
break;
case "command-reply":
core.CommandReplyAsync += () => Event.Invoke("command-reply", null);
Core.CommandReplyAsync += () => Event.Invoke("command-reply", null);
break;
case "start-file":
core.StartFileAsync += () => Event.Invoke("start-file", null);
Core.StartFileAsync += () => Event.Invoke("start-file", null);
break;
case "file-loaded":
core.FileLoadedAsync += () => Event.Invoke("file-loaded", null);
Core.FileLoadedAsync += () => Event.Invoke("file-loaded", null);
break;
case "idle":
core.IdleAsync += () => Event.Invoke("idle", null);
Core.IdleAsync += () => Event.Invoke("idle", null);
break;
case "video-reconfig":
core.VideoReconfigAsync += () => Event.Invoke("video-reconfig", null);
Core.VideoReconfigAsync += () => Event.Invoke("video-reconfig", null);
break;
case "audio-reconfig":
core.AudioReconfigAsync += () => Event.Invoke("audio-reconfig", null);
Core.AudioReconfigAsync += () => Event.Invoke("audio-reconfig", null);
break;
case "seek":
core.SeekAsync += () => Event.Invoke("seek", null);
Core.SeekAsync += () => Event.Invoke("seek", null);
break;
case "playback-restart":
core.PlaybackRestartAsync += () => Event.Invoke("playback-restart", null);
Core.PlaybackRestartAsync += () => Event.Invoke("playback-restart", null);
break;
}
}
@@ -224,13 +223,13 @@ namespace mpvnet
void Output_DataAdded(object sender, DataAddedEventArgs e)
{
var output = sender as PSDataCollection<PSObject>;
ConsoleHelp.Write(output[e.Index], Module);
Terminal.Write(output[e.Index], Module);
}
void Error_DataAdded(object sender, DataAddedEventArgs e)
{
var error = sender as PSDataCollection<ErrorRecord>;
ConsoleHelp.WriteError(error[e.Index], Module);
Terminal.WriteError(error[e.Index], Module);
}
}

View File

@@ -6,7 +6,7 @@ using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
using static mpvnet.Core;
using static mpvnet.Global;
namespace mpvnet
{
@@ -23,7 +23,7 @@ namespace mpvnet
if (App.IsStartedFromTerminal)
Native.AttachConsole(-1 /*ATTACH_PARENT_PROCESS*/);
if (core.ConfigFolder == "")
if (Core.ConfigFolder == "")
return;
string[] args = Environment.GetCommandLineArgs().Skip(1).ToArray();
@@ -31,11 +31,11 @@ namespace mpvnet
if (args.Length >= 2 && args[0] == "--reg-file-assoc")
{
if (args[1] == "audio")
FileAssociation.Register(Core.AudioTypes);
FileAssociation.Register(CorePlayer.AudioTypes);
else if (args[1] == "video")
FileAssociation.Register(Core.VideoTypes);
FileAssociation.Register(CorePlayer.VideoTypes);
else if (args[1] == "image")
FileAssociation.Register(Core.ImageTypes);
FileAssociation.Register(CorePlayer.ImageTypes);
else
FileAssociation.Register(args.Skip(1).ToArray());

50
src/Misc/Terminal.cs Normal file
View File

@@ -0,0 +1,50 @@

using System;
using System.Diagnostics;
namespace mpvnet
{
public static class Terminal
{
static int Padding { get; } = 60;
public static void WriteError(object obj, string module = "mpv.net")
{
Write(obj, module, ConsoleColor.DarkRed, false);
}
public static void Write(object obj, string module = "mpv.net")
{
Write(obj, module, ConsoleColor.Black, true);
}
public static void Write(object obj, string module, ConsoleColor color, bool useDefaultColor)
{
if (obj == null)
return;
string value = obj.ToString();
if (!string.IsNullOrEmpty(module))
module = "[" + module + "] ";
if (useDefaultColor)
Console.ResetColor();
else
Console.ForegroundColor = color;
value = module + value;
if (value.Length < Padding)
value = value.PadRight(Padding);
if (color == ConsoleColor.Red || color == ConsoleColor.DarkRed)
Console.Error.WriteLine(value);
else
Console.WriteLine(value);
Console.ResetColor();
Trace.WriteLine(obj);
}
}
}

View File

@@ -45,7 +45,7 @@ namespace mpvnet
if (!theme.Dictionary.ContainsKey(key))
{
isKeyMissing = true;
ConsoleHelp.WriteError($"Theme '{activeTheme}' misses '{key}'");
Terminal.WriteError($"Theme '{activeTheme}' misses '{key}'");
break;
}
}

View File

@@ -7,8 +7,7 @@ using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using static mpvnet.Core;
using static TaskDialog.Msg;
using static mpvnet.Global;
namespace mpvnet
{
@@ -16,7 +15,7 @@ namespace mpvnet
{
public static void DailyCheck()
{
if (App.UpdateCheck && RegistryHelp.GetInt("UpdateCheckLast")
if (App.UpdateCheck && RegistryHelp.GetInt("last-update-check")
!= DateTime.Now.DayOfYear)
CheckOnline();
@@ -28,26 +27,33 @@ namespace mpvnet
{
using (HttpClient client = new HttpClient())
{
RegistryHelp.SetValue(RegistryHelp.ApplicationKey, "UpdateCheckLast", DateTime.Now.DayOfYear);
RegistryHelp.SetValue("last-update-check", DateTime.Now.DayOfYear);
client.DefaultRequestHeaders.Add("User-Agent", "mpv.net");
var response = await client.GetAsync("https://api.github.com/repos/stax76/mpv.net/releases/latest");
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Match match = Regex.Match(content, @"""mpv\.net-([\d\.]+)-portable\.zip""");
if (!match.Success)
{
App.ShowError("Update check is currently not available.");
return;
}
Version onlineVersion = Version.Parse(match.Groups[1].Value);
Version currentVersion = Assembly.GetEntryAssembly().GetName().Version;
if (onlineVersion <= currentVersion)
{
if (showUpToDateMessage)
MsgInfo($"{Application.ProductName} is up to date.");
Msg.ShowInfo($"{Application.ProductName} is up to date.");
return;
}
if ((RegistryHelp.GetString("UpdateCheckVersion")
if ((RegistryHelp.GetString("update-check-version")
!= onlineVersion.ToString() || showUpToDateMessage) && Msg.ShowQuestion(
$"New version {onlineVersion} is available, update now?") == MsgResult.OK)
$"New version {onlineVersion} is available, update now?") == DialogResult.OK)
{
string url = $"https://github.com/stax76/mpv.net/releases/download/{onlineVersion}/mpv.net-{onlineVersion}-portable.zip";
@@ -64,16 +70,16 @@ namespace mpvnet
proc.Start();
}
core.command("quit");
Core.command("quit");
}
RegistryHelp.SetValue(RegistryHelp.ApplicationKey, "UpdateCheckVersion", onlineVersion.ToString());
RegistryHelp.SetValue("update-check-version", onlineVersion.ToString());
}
}
catch (Exception ex)
{
if (showUpToDateMessage)
Msg.ShowException(ex);
App.ShowException(ex);
}
}
}