This commit is contained in:
Frank Skare
2020-03-20 01:22:26 +01:00
parent 6f7fa6c9d6
commit 42b0cc1a64
28 changed files with 439 additions and 351 deletions

View File

@@ -1,4 +1,11 @@
### 5.4.4.2
- new: flag cli switches support now --no-flag in addition to --flag=no
- new: cli switches can also start with single - instead of double --
- new: the PowerShell script host was completely rewritten, events can
can be assigned to using `Register-ObjectEvent`
### 5.4.4.1
- new: external console replaced with internal console

View File

@@ -245,7 +245,7 @@ Before making a support request for a particular issue, please try if it was alr
[Issue tracker](https://github.com/stax76/mpv.net/issues), feel free to use for anything mpv.net related.
Supporting the development of mpv.net possible via PayPal donation:
You can support the development of mpv.net with a PayPal donation:
<https://www.paypal.me/stax76>

View File

@@ -1,4 +1,5 @@
using System.IO;

using System.IO;
using mpvnet;
@@ -9,7 +10,7 @@ class Script
mp.Shutdown += Shutdown;
}
private void Shutdown()
void Shutdown()
{
foreach (string file in Directory.GetFiles(@"C:\Users\frank\Desktop\aaa"))
File.Delete(file);

View File

@@ -1,4 +1,5 @@
using System;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
@@ -113,7 +114,7 @@ namespace DynamicGUI
public OptionSetting OptionSetting { get; set; }
private string _Text;
string _Text;
public string Text
{
@@ -144,7 +145,7 @@ namespace DynamicGUI
public class HyperlinkEx : Hyperlink
{
private void HyperLinkEx_RequestNavigate(object sender, RequestNavigateEventArgs e)
void HyperLinkEx_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(e.Uri.AbsoluteUri);
}

View File

@@ -1,35 +1,42 @@
using System.Windows;

using System.Windows;
using System.Windows.Controls;
namespace DynamicGUI
{
public partial class OptionSettingControl : UserControl, ISettingControl
{
private OptionSetting OptionSetting;
OptionSetting OptionSetting;
public OptionSettingControl(OptionSetting optionSetting)
{
OptionSetting = optionSetting;
InitializeComponent();
TitleTextBox.Text = optionSetting.Name;
if (string.IsNullOrEmpty(optionSetting.Help))
HelpTextBox.Visibility = Visibility.Collapsed;
HelpTextBox.Text = optionSetting.Help;
ItemsControl.ItemsSource = optionSetting.Options;
if (string.IsNullOrEmpty(optionSetting.URL))
LinkTextBlock.Visibility = Visibility.Collapsed;
Link.SetURL(optionSetting.URL);
}
private string _SearchableText;
string _SearchableText;
public string SearchableText {
get {
if (_SearchableText is null)
{
_SearchableText = TitleTextBox.Text + HelpTextBox.Text;
foreach (var i in OptionSetting.Options)
_SearchableText += i.Text + i.Help + i.Name;
_SearchableText = _SearchableText.ToLower();
}
return _SearchableText;

View File

@@ -1,5 +1,5 @@
using System;
using System.Diagnostics;

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
@@ -10,7 +10,7 @@ namespace DynamicGUI
{
public partial class StringSettingControl : UserControl, ISettingControl
{
private StringSetting StringSetting;
StringSetting StringSetting;
public StringSettingControl(StringSetting stringSetting)
{
@@ -19,21 +19,26 @@ namespace DynamicGUI
TitleTextBox.Text = stringSetting.Name;
HelpTextBox.Text = stringSetting.Help;
ValueTextBox.Text = StringSetting.Value;
if (StringSetting.Width > 0)
ValueTextBox.Width = StringSetting.Width;
if (StringSetting.Type != "folder" && StringSetting.Type != "color")
Button.Visibility = Visibility.Hidden;
Link.SetURL(StringSetting.URL);
if (string.IsNullOrEmpty(stringSetting.URL))
LinkTextBlock.Visibility = Visibility.Collapsed;
}
private string _SearchableText;
string _SearchableText;
public string SearchableText {
get {
if (_SearchableText is null)
_SearchableText = (TitleTextBox.Text + HelpTextBox.Text +ValueTextBox.Text).ToLower();
return _SearchableText;
}
}
@@ -47,7 +52,7 @@ namespace DynamicGUI
set => StringSetting.Value = value;
}
private void Button_Click(object sender, RoutedEventArgs e)
void Button_Click(object sender, RoutedEventArgs e)
{
switch (StringSetting.Type)
{
@@ -56,6 +61,7 @@ namespace DynamicGUI
{
d.Description = "Choose a folder.";
d.SelectedPath = ValueTextBox.Text;
if (d.ShowDialog() == WinForms.DialogResult.OK)
ValueTextBox.Text = d.SelectedPath;
}
@@ -65,7 +71,8 @@ namespace DynamicGUI
{
dialog.FullOpen = true;
try {
try
{
if (!string.IsNullOrEmpty(ValueTextBox.Text))
{
Color col = GetColor(ValueTextBox.Text);
@@ -80,7 +87,7 @@ namespace DynamicGUI
}
}
private void ValueTextBox_TextChanged(object sender, TextChangedEventArgs e) => Update();
void ValueTextBox_TextChanged(object sender, TextChangedEventArgs e) => Update();
Color GetColor(string value)
{
@@ -104,7 +111,10 @@ namespace DynamicGUI
if (StringSetting.Type == "color")
{
Color c = Colors.Transparent;
if (ValueTextBox.Text != "") try { c = GetColor(ValueTextBox.Text); } catch {}
if (ValueTextBox.Text != "")
try { c = GetColor(ValueTextBox.Text); } catch {}
ValueTextBox.Background = new SolidColorBrush(c);
}
}

View File

@@ -1,10 +1,15 @@
using System;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using UI;
using static libmpv;
using static Common;
using System.Threading.Tasks;
namespace mpvnet
{
@@ -84,16 +89,48 @@ namespace mpvnet
mp.Shutdown += Shutdown;
mp.Initialized += Initialized;
mp.LogMessage += LogMessage;
mp.LogMessage += ShowFatalError;
}
private static void LogMessage(mpv_log_level level, string msg)
static void ShowFatalError(mpv_log_level level, string msg)
{
if (!App.IsStartedFromTerminal && level == mpv_log_level.MPV_LOG_LEVEL_FATAL)
Msg.ShowError(msg);
}
private static void Initialized()
public static void RunAction(Action action)
{
Task.Run(() => {
try
{
action.Invoke();
}
catch (Exception e)
{
ShowException(e);
}
});
}
public static void ShowException(object obj)
{
if (obj is Exception e)
{
if (App.IsStartedFromTerminal)
ConsoleHelp.WriteError(e.ToString(), "mpv.net");
else
Msg.ShowException(e);
}
else
{
if (App.IsStartedFromTerminal)
ConsoleHelp.WriteError(obj.ToString(), "mpv.net");
else
Msg.ShowError(obj.ToString());
}
}
static void Initialized()
{
if (RememberVolume)
{
@@ -102,7 +139,7 @@ namespace mpvnet
}
}
private static void Shutdown()
static void Shutdown()
{
if (RememberVolume)
{
@@ -149,7 +186,7 @@ namespace mpvnet
case "light-theme": LightTheme = value.Trim('\'', '"'); return true;
default:
if (writeError)
ConsoleHelp.WriteError($"unknown mpvnet.conf property: {name}");
ConsoleHelp.WriteError($"unknown mpvnet.conf property: {name}", "mpv.net");
return false;
}
}

8
mpv.net/Misc/Common.cs Normal file
View File

@@ -0,0 +1,8 @@

using System;
public static class Common
{
public static string BR = Environment.NewLine;
public static string BR2 = Environment.NewLine + Environment.NewLine;
}

View File

@@ -2,12 +2,43 @@
using System;
using System.Diagnostics;
class ConsoleHelp
public static class ConsoleHelp
{
public static void WriteError(object obj)
public static int Padding { get; set; }
public static void WriteError(object obj, string module = null) => Write(obj, module, ConsoleColor.Red, false);
public static void Write(object obj, string module)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[mpvnet] " + obj);
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);
Console.WriteLine(value);
Console.ResetColor();
Trace.WriteLine(obj);
}

View File

@@ -119,12 +119,12 @@ namespace mpvnet
public CommandItem(SerializationInfo info, StreamingContext context) { }
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string _Input = "";
string _Input = "";
public string Input {
get => _Input;
@@ -175,14 +175,13 @@ namespace mpvnet
if (item.Command.ToLower() == "ignore")
item.Command = "";
MigrateCommands(item);
items.Add(item);
}
}
return items;
}
private static ObservableCollection<CommandItem> _Items;
static ObservableCollection<CommandItem> _Items;
public static ObservableCollection<CommandItem> Items {
get {
@@ -192,26 +191,6 @@ namespace mpvnet
return _Items;
}
}
// last change 2019
public static void MigrateCommands(CommandItem item)
{
switch (item.Command)
{
case "script-message mpv.net show-prefs":
item.Command = "script-message mpv.net show-conf-editor";
break;
case "script-message mpv.net show-keys":
item.Command = "script-message mpv.net show-input-editor";
break;
case "script-message mpv.net history":
item.Command = "script-message mpv.net show-history";
break;
case "script-message mpv.net open-config-folder":
item.Command = "script-message open-conf-folder";
break;
}
}
}
public class CursorHelp

View File

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

View File

@@ -42,10 +42,10 @@ public class WinAPI
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
[DllImport("user32.dll", EntryPoint = "GetWindowLong")]
private static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex);
static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", EntryPoint = "GetWindowLongPtr")]
private static extern IntPtr GetWindowLong64(IntPtr hWnd, int nIndex);
static extern IntPtr GetWindowLong64(IntPtr hWnd, int nIndex);
public static IntPtr GetWindowLong(IntPtr hWnd, int nIndex)
{

View File

@@ -12,7 +12,7 @@ using System.Windows.Forms;
public class Msg
{
private static string ShownMessages;
static string ShownMessages;
public static string SupportURL { get; set; }
@@ -67,7 +67,7 @@ public class Msg
td.MainInstruction = exception.GetType().Name;
td.Content = exception.Message;
td.MainIcon = MsgIcon.Error;
td.ExpandedInformation = exception.ToString();
td.ExpandedInformation = exception.StackTrace;
td.Footer = "[Copy Message](copymsg)";
if (!string.IsNullOrEmpty(Msg.SupportURL))
@@ -78,8 +78,7 @@ public class Msg
}
catch (Exception e)
{
MessageBox.Show(e.GetType().Name + "\n\n" + e.Message + "\n\n" + e,
Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(e.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@@ -96,24 +95,24 @@ public class Msg
Msg.ShownMessages += mainInstruction + content;
}
public static MsgResult ShowQuestion(string mainInstruction,
MsgButtons buttons = MsgButtons.OkCancel)
public static MsgResult ShowQuestion(
string mainInstruction, MsgButtons buttons = MsgButtons.OkCancel)
{
return Msg.Show(mainInstruction, null, MsgIcon.None, buttons, MsgResult.None);
}
public static MsgResult ShowQuestion(string mainInstruction,
string content,
MsgButtons buttons = MsgButtons.OkCancel)
public static MsgResult ShowQuestion(
string mainInstruction, string content, MsgButtons buttons = MsgButtons.OkCancel)
{
return Msg.Show(mainInstruction, content, MsgIcon.None, buttons, MsgResult.None);
}
public static MsgResult Show(string mainInstruction,
string content,
MsgIcon icon,
MsgButtons buttons,
MsgResult defaultButton = MsgResult.None)
public static MsgResult Show(
string mainInstruction,
string content,
MsgIcon icon,
MsgButtons buttons,
MsgResult defaultButton = MsgResult.None)
{
try
{
@@ -155,14 +154,20 @@ public class Msg
public class TaskDialog<T> : TaskDialogNative, IDisposable
{
private Dictionary<int, T> IdValueDic;
private Dictionary<int, string> IdTextDic;
private List<int> CommandLinkShieldList;
private IntPtr ButtonArray;
private IntPtr RadioButtonArray;
private List<TaskDialogNative.TASKDIALOG_BUTTON> Buttons;
private List<TaskDialogNative.TASKDIALOG_BUTTON> RadioButtons;
private TaskDialogNative.TASKDIALOGCONFIG Config;
Dictionary<int, T> IdValueDic;
Dictionary<int, string> IdTextDic;
List<int> CommandLinkShieldList;
IntPtr ButtonArray;
IntPtr RadioButtonArray;
T SelectedValueValue;
string SelectedTextValue;
int TimeoutValue;
int ExitTickCount;
bool Disposed;
List<TaskDialogNative.TASKDIALOG_BUTTON> Buttons;
List<TaskDialogNative.TASKDIALOG_BUTTON> RadioButtons;
TaskDialogNative.TASKDIALOGCONFIG Config;
const int TDE_CONTENT = 0;
const int TDE_EXPANDED_INFORMATION = 1;
const int TDE_FOOTER = 2;
@@ -193,11 +198,6 @@ public class TaskDialog<T> : TaskDialogNative, IDisposable
const int TDM_UPDATE_ELEMENT_TEXT = 1138;
const int TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE = 1139;
const int TDM_UPDATE_ICON = 1140;
private T SelectedValueValue;
private string SelectedTextValue;
private int TimeoutValue;
private int ExitTickCount;
private bool disposed;
public TaskDialog()
{
@@ -285,13 +285,14 @@ public class TaskDialog<T> : TaskDialogNative, IDisposable
set => Config.MainIcon = new TaskDialogNative.TASKDIALOGCONFIG_ICON_UNION((int)value);
}
private int _SelectedID;
int _SelectedID;
public int SelectedID {
get => _SelectedID;
set {
foreach (var i in IdValueDic)
if (i.Key == value) _SelectedID = value;
if (i.Key == value)
_SelectedID = value;
}
}
@@ -299,6 +300,7 @@ public class TaskDialog<T> : TaskDialogNative, IDisposable
get {
if (IdValueDic.ContainsKey(SelectedID))
return IdValueDic[SelectedID];
return SelectedValueValue;
}
set => SelectedValueValue = value;
@@ -308,13 +310,15 @@ public class TaskDialog<T> : TaskDialogNative, IDisposable
get {
if (IdTextDic.ContainsKey(SelectedID))
return IdTextDic[SelectedID];
return SelectedTextValue;
}
set => SelectedTextValue = value;
}
public bool CheckBoxChecked {
get => (Config.dwFlags & TaskDialogNative.TASKDIALOG_FLAGS.TDF_VERIFICATION_FLAG_CHECKED) == TaskDialogNative.TASKDIALOG_FLAGS.TDF_VERIFICATION_FLAG_CHECKED;
get => (Config.dwFlags & TaskDialogNative.TASKDIALOG_FLAGS.TDF_VERIFICATION_FLAG_CHECKED)
== TaskDialogNative.TASKDIALOG_FLAGS.TDF_VERIFICATION_FLAG_CHECKED;
set {
if (value)
Config.dwFlags |= TaskDialogNative.TASKDIALOG_FLAGS.TDF_VERIFICATION_FLAG_CHECKED;
@@ -355,6 +359,7 @@ public class TaskDialog<T> : TaskDialogNative, IDisposable
value = regex.Replace(value, "<a href=\"$2\">$1</a>");
}
}
return value;
}
@@ -371,8 +376,13 @@ public class TaskDialog<T> : TaskDialogNative, IDisposable
{
int n = 1000 + IdValueDic.Count + 1;
IdValueDic[n] = value;
if (setShield) CommandLinkShieldList.Add(n);
if (!string.IsNullOrEmpty(description)) text += "\n" + description;
if (setShield)
CommandLinkShieldList.Add(n);
if (!string.IsNullOrEmpty(description))
text += "\n" + description;
Buttons.Add(new TaskDialogNative.TASKDIALOG_BUTTON(n, text));
Config.dwFlags |= TaskDialogNative.TASKDIALOG_FLAGS.TDF_USE_COMMAND_LINKS;
}
@@ -388,10 +398,17 @@ public class TaskDialog<T> : TaskDialogNative, IDisposable
{
MarshalDialogControlStructs();
TaskDialogNative.TASKDIALOGCONFIG config = Config;
int errorCode = TaskDialogNative.TaskDialogIndirect(config, out int dummy1, out int dummy2, out bool isChecked);
if (errorCode < 0) Marshal.ThrowExceptionForHR(errorCode);
int hr = TaskDialogNative.TaskDialogIndirect(
config, out int dummy1, out int dummy2, out bool isChecked);
if (hr < 0)
Marshal.ThrowExceptionForHR(hr);
CheckBoxChecked = isChecked;
if (SelectedValue is MsgResult) SelectedValue = (T)(object)SelectedID;
if (SelectedValue is MsgResult)
SelectedValue = (T)(object)SelectedID;
return SelectedValue;
}
@@ -412,8 +429,10 @@ public class TaskDialog<T> : TaskDialogNative, IDisposable
break;
case 3: //TDN_HYPERLINK_CLICKED
string stringUni = Marshal.PtrToStringUni(lParam);
if (stringUni.StartsWith("mailto") || stringUni.StartsWith("http"))
Process.Start(stringUni);
if (stringUni == "copymsg")
{
Thread thread = new Thread((ThreadStart)(() => {
@@ -475,8 +494,10 @@ public class TaskDialog<T> : TaskDialogNative, IDisposable
protected void Dispose(bool disposing)
{
if (disposed) return;
disposed = true;
if (Disposed)
return;
Disposed = true;
if (ButtonArray != IntPtr.Zero)
{
@@ -493,36 +514,27 @@ public class TaskDialog<T> : TaskDialogNative, IDisposable
}
public delegate int PFTASKDIALOGCALLBACK(
IntPtr hwnd,
uint msg,
IntPtr wParam,
IntPtr lParam,
IntPtr lpRefData);
IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam, IntPtr lpRefData);
public class TaskDialogNative
{
[DllImport("comctl32", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int TaskDialogIndirect(
[In] TaskDialogNative.TASKDIALOGCONFIG pTaskConfig,
TaskDialogNative.TASKDIALOGCONFIG pTaskConfig,
out int pnButton,
out int pnRadioButton,
[MarshalAs(UnmanagedType.Bool)] out bool pVerificationFlagChecked);
out bool pVerificationFlagChecked);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern uint GetWindowModuleFileName(
IntPtr hwnd,
StringBuilder lpszFileName,
uint cchFileNameMax);
IntPtr hwnd, StringBuilder lpszFileName, uint cchFileNameMax);
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(
IntPtr handle,
int message,
IntPtr wParam,
IntPtr lParam);
IntPtr handle, int message, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Unicode)]
public class TASKDIALOGCONFIG
@@ -532,12 +544,9 @@ public class TaskDialogNative
public IntPtr hInstance;
public TaskDialogNative.TASKDIALOG_FLAGS dwFlags;
public MsgButtons dwCommonButtons;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszWindowTitle;
public TaskDialogNative.TASKDIALOGCONFIG_ICON_UNION MainIcon;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszMainInstruction;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszContent;
public uint cButtons;
public IntPtr pButtons;
@@ -545,16 +554,11 @@ public class TaskDialogNative
public uint cRadioButtons;
public IntPtr pRadioButtons;
public int nDefaultRadioButton;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszVerificationText;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszExpandedInformation;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszExpandedControlText;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszCollapsedControlText;
public TaskDialogNative.TASKDIALOGCONFIG_ICON_UNION FooterIcon;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszFooter;
public PFTASKDIALOGCALLBACK pfCallback;
public IntPtr lpCallbackData;

View File

@@ -4,15 +4,15 @@ using System.Runtime.InteropServices;
public class Taskbar
{
private ITaskbarList3 Instance = (ITaskbarList3)new TaskBarCommunication();
public IntPtr Handle { get; set; }
public Taskbar(IntPtr handle) => Handle = handle;
ITaskbarList3 Instance = (ITaskbarList3)new TaskBarCommunication();
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("EA1AFB91-9E28-4B86-90E9-9E9F8A5EEFAF")]
private interface ITaskbarList3
interface ITaskbarList3
{
// ITaskbarList
[PreserveSig] void HrInit();
@@ -30,7 +30,9 @@ public class Taskbar
[ComImport]
[ClassInterface(ClassInterfaceType.None)]
[Guid("56FDF344-FD6D-11d0-958A-006097C9A090")]
private class TaskBarCommunication { }
class TaskBarCommunication
{
}
public void SetState(TaskbarStates taskbarState)
{

View File

@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("5.4.4.1")]
[assembly: AssemblyFileVersion("5.4.4.1")]
[assembly: AssemblyVersion("5.4.4.2")]
[assembly: AssemblyFileVersion("5.4.4.2")]

View File

@@ -295,13 +295,13 @@ help = "<int> Initial window height in percent. Default: 50"
name = "autofit-smaller"
file = "mpv"
filter = "Screen"
help = "<int> Minimum window height in percent. Default: 40"
help = "<int> Minimum window height in percent. Default: 30"
[[settings]]
name = "autofit-larger"
file = "mpv"
filter = "Screen"
help = "<int> Maximum window height in percent. Default: 75"
help = "<int> Maximum window height in percent. Default: 80"
[[settings]]
name = "start-size"

View File

@@ -0,0 +1,107 @@

using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;
namespace ScriptHost
{
public class PowerShell
{
public Runspace Runspace { get; set; }
public Pipeline Pipeline { get; set; }
public string Module { get; set; }
public bool Print { get; set; }
public List<string> Scripts { get; } = new List<string>();
public string[] Parameters { get; }
public static List<PowerShell> Instances { get; } = new List<PowerShell>();
string BR = Environment.NewLine;
public object Invoke()
{
try
{
Runspace = RunspaceFactory.CreateRunspace();
Runspace.ApartmentState = ApartmentState.STA;
Runspace.Open();
Pipeline = Runspace.CreatePipeline();
foreach (string script in Scripts)
Pipeline.Commands.AddScript(script);
if (Parameters != null)
foreach (string param in Parameters)
foreach (Command command in Pipeline.Commands)
command.Parameters.Add(null, param);
Runspace.SessionStateProxy.SetVariable("ScriptHost", this);
if (Print)
{
Pipeline.Output.DataReady += Output_DataReady;
Pipeline.Error.DataReady += Error_DataReady;
}
return Pipeline.Invoke();
}
catch (RuntimeException e)
{
string message = e.Message + BR + BR + e.ErrorRecord.ScriptStackTrace.Replace(
" <ScriptBlock>, <No file>", "") + BR + BR + Module + BR;
throw new PowerShellException(message);
}
catch (Exception e)
{
throw e;
}
}
public void Output_DataReady(object sender, EventArgs e)
{
var output = sender as PipelineReader<PSObject>;
while (output.Count > 0)
ConsoleHelp.Write(output.Read().ToString(), Module);
}
public void Error_DataReady(object sender, EventArgs e)
{
var output = sender as PipelineReader<Object>;
while (output.Count > 0)
ConsoleHelp.WriteError(output.Read().ToString(), Module);
}
public void RedirectEventJobStreams(PSEventJob job)
{
if (Print)
{
job.Output.DataAdded += Output_DataAdded;
job.Error.DataAdded += Error_DataAdded;
}
}
void Output_DataAdded(object sender, DataAddedEventArgs e)
{
var output = sender as PSDataCollection<PSObject>;
ConsoleHelp.Write(output[e.Index], Module);
}
void Error_DataAdded(object sender, DataAddedEventArgs e)
{
var error = sender as PSDataCollection<ErrorRecord>;
ConsoleHelp.WriteError(error[e.Index], Module);
}
}
public class PowerShellException : Exception
{
public PowerShellException(string message) : base(message)
{
}
}
}

View File

@@ -1,130 +0,0 @@

using System;
using System.IO;
using System.Threading;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Management.Automation;
namespace mpvnet
{
public class PowerShellScript
{
public static void Execute(string filepath, params string[] parameters)
{
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.ApartmentState = ApartmentState.STA;
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline())
{
pipeline.Commands.AddScript(
"Using namespace mpvnet\n" +
"Using namespace System\n" +
"[System.Reflection.Assembly]::LoadWithPartialName(\"mpvnet\")\n");
pipeline.Commands.AddScript(File.ReadAllText(filepath));
if (parameters != null)
foreach (string i in parameters)
pipeline.Commands[1].Parameters.Add(null, i);
PowerShellOutput output = new PowerShellOutput();
output.ModuleName = Path.GetFileName(filepath);
pipeline.Output.DataReady += output.Output_DataReady;
pipeline.Error.DataReady += output.Error_DataReady;
runspace.SessionStateProxy.SetVariable("Output", output);
try {
pipeline.Invoke();
}
catch (RuntimeException e) {
Msg.ShowError("PowerShell Exception", e.Message + "\n\n" +
e.ErrorRecord.ScriptStackTrace.Replace(" <ScriptBlock>, <No file>", "") +
"\n\n" + Path.GetFileName(filepath));
}
catch (Exception e) {
Msg.ShowException(e);
}
pipeline.Output.DataReady -= output.Output_DataReady;
pipeline.Error.DataReady -= output.Error_DataReady;
}
}
}
public static void Init(string filepath)
{
foreach (var eventInfo in typeof(mp).GetEvents())
{
if (eventInfo.Name.ToLower() ==
Path.GetFileNameWithoutExtension(filepath).ToLower().Replace("-", ""))
{
PowerShellEventObject eventObject = new PowerShellEventObject();
MethodInfo mi;
eventObject.Filepath = filepath;
if (eventInfo.EventHandlerType == typeof(Action))
mi = eventObject.GetType().GetMethod(nameof(PowerShellEventObject.Invoke));
else if (eventInfo.EventHandlerType == typeof(Action<EndFileEventMode>))
mi = eventObject.GetType().GetMethod(nameof(PowerShellEventObject.InvokeEndFile));
else if (eventInfo.EventHandlerType == typeof(Action<string[]>))
mi = eventObject.GetType().GetMethod(nameof(PowerShellEventObject.InvokeStrings));
else
throw new Exception();
eventObject.EventInfo = eventInfo;
Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, eventObject, mi);
eventObject.Delegate = handler;
eventInfo.AddEventHandler(eventObject, handler);
return;
}
}
Execute(filepath);
}
class PowerShellOutput
{
public string ModuleName { get; set; }
public bool WriteStandard { get; set; } = true;
public bool WriteError { get; set; } = true;
public void Output_DataReady(object sender, EventArgs e)
{
if (!WriteStandard)
return;
var output = sender as PipelineReader<PSObject>;
while (output.Count > 0)
Console.WriteLine("[" + ModuleName + "] " + output.Read().ToString());
}
public void Error_DataReady(object sender, EventArgs e)
{
if (!WriteError)
return;
var output = sender as PipelineReader<Object>;
while (output.Count > 0)
ConsoleHelp.WriteError("[" + ModuleName + "] " + output.Read().ToString());
}
}
}
public class PowerShellEventObject
{
public EventInfo EventInfo { get; set; }
public Delegate Delegate { get; set; }
public string Filepath { get; set; }
public void Invoke() => PowerShellScript.Execute(Filepath);
public void InvokeEndFile(EndFileEventMode arg) => PowerShellScript.Execute(Filepath, arg.ToString());
public void InvokeStrings(string[] args) => PowerShellScript.Execute(Filepath, args);
}
}

View File

@@ -1,13 +1,10 @@
using Microsoft.Win32;

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
namespace mpvnet
{
@@ -29,16 +26,22 @@ namespace mpvnet
{
if (item.Command == "" || item.Path == "")
return false;
string filter = FilterTextBox.Text.ToLower();
if (filter == "") return true;
if (filter == "")
return true;
if (item.Command.ToLower().Contains(filter) ||
item.Input.ToLower().Contains(filter) ||
item.Path.ToLower().Contains(filter))
return true;
return false;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
void Window_Loaded(object sender, RoutedEventArgs e)
{
HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
source.AddHook(new HwndSourceHook(WndProc));
@@ -52,14 +55,15 @@ namespace mpvnet
ListView.SelectedIndex = 0;
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == 0x200 /*WM_MOUSEMOVE*/ && Mouse.LeftButton != MouseButtonState.Pressed)
handled = true;
return IntPtr.Zero;
}
private void FilterTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
void FilterTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
@@ -67,7 +71,10 @@ namespace mpvnet
{
int index = ListView.SelectedIndex;
index -= 1;
if (index < 0) index = 0;
if (index < 0)
index = 0;
ListView.SelectedIndex = index;
ListView.ScrollIntoView(ListView.SelectedItem);
}
@@ -76,7 +83,10 @@ namespace mpvnet
{
int index = ListView.SelectedIndex;
index += 1;
if (index > ListView.Items.Count - 1) index = ListView.Items.Count - 1;
if (index > ListView.Items.Count - 1)
index = ListView.Items.Count - 1;
ListView.SelectedIndex = index;
ListView.ScrollIntoView(ListView.SelectedItem);
}
@@ -100,12 +110,12 @@ namespace mpvnet
}
}
private void ListView_MouseUp(object sender, MouseButtonEventArgs e)
void ListView_MouseUp(object sender, MouseButtonEventArgs e)
{
Execute();
}
private void FilterTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
void FilterTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
CollectionView.Refresh();
SelectFirst();

View File

@@ -33,7 +33,7 @@ namespace mpvnet
SearchControl.Text = RegistryHelp.GetString(App.RegPath, "ConfigEditorSearch");
}
private void LoadSettings()
void LoadSettings()
{
foreach (SettingBase setting in SettingsDefinitions)
{
@@ -247,7 +247,7 @@ namespace mpvnet
return "\r\n" + sb.ToString().Trim() + "\r\n";
}
private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string activeFilter = "";
@@ -275,7 +275,7 @@ namespace mpvnet
MainScrollViewer.ScrollToTop();
}
private void ConfWindow1_Loaded(object sender, RoutedEventArgs e)
void ConfWindow1_Loaded(object sender, RoutedEventArgs e)
{
SearchControl.SearchTextBox.SelectAll();
Keyboard.Focus(SearchControl.SearchTextBox);
@@ -284,27 +284,27 @@ namespace mpvnet
i.Update();
}
private void FilterListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
void FilterListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0) SearchControl.Text = e.AddedItems[0] + ":";
}
private void OpenSettingsTextBlock_MouseUp(object sender, MouseButtonEventArgs e)
void OpenSettingsTextBlock_MouseUp(object sender, MouseButtonEventArgs e)
{
Process.Start(Path.GetDirectoryName(mp.ConfPath));
}
private void PreviewTextBlock_MouseUp(object sender, MouseButtonEventArgs e)
void PreviewTextBlock_MouseUp(object sender, MouseButtonEventArgs e)
{
Msg.Show("mpv.conf Preview", GetContent("mpv"));
}
private void ShowManualTextBlock_MouseUp(object sender, MouseButtonEventArgs e)
void ShowManualTextBlock_MouseUp(object sender, MouseButtonEventArgs e)
{
Process.Start("https://mpv.io/manual/master/");
}
private void SupportTextBlock_MouseUp(object sender, MouseButtonEventArgs e)
void SupportTextBlock_MouseUp(object sender, MouseButtonEventArgs e)
{
Process.Start("https://github.com/stax76/mpv.net#Support");
}

View File

@@ -43,7 +43,7 @@ namespace mpvnet
[DllImport("Everything.dll")]
public static extern UInt32 Everything_GetNumResults();
private void Window_Loaded(object sender, RoutedEventArgs e)
void Window_Loaded(object sender, RoutedEventArgs e)
{
HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
source.AddHook(new HwndSourceHook(WndProc));
@@ -56,7 +56,7 @@ namespace mpvnet
ListView.SelectedIndex = 0;
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == 0x200 /*WM_MOUSEMOVE*/ && Mouse.LeftButton != MouseButtonState.Pressed)
handled = true;
@@ -64,7 +64,7 @@ namespace mpvnet
return IntPtr.Zero;
}
private void FilterTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
void FilterTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
@@ -91,7 +91,7 @@ namespace mpvnet
}
}
private void ListView_PreviewKeyDown(object sender, KeyEventArgs e)
void ListView_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
Close();
@@ -108,9 +108,9 @@ namespace mpvnet
Keyboard.Focus(FilterTextBox);
}
private void ListView_MouseUp(object sender, MouseButtonEventArgs e) => Execute();
void ListView_MouseUp(object sender, MouseButtonEventArgs e) => Execute();
private void FilterTextBox_TextChanged(object sender, TextChangedEventArgs e)
void FilterTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string searchtext = FilterTextBox.Text;
Task.Run(() => Search(searchtext));

View File

@@ -28,7 +28,7 @@ namespace mpvnet
DataGrid.ItemsSource = CollectionView;
}
private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
CollectionView.Refresh();
@@ -70,7 +70,7 @@ namespace mpvnet
return false;
}
private void ButtonClick(object sender, RoutedEventArgs e)
void ButtonClick(object sender, RoutedEventArgs e)
{
CommandItem item = ((Button)e.Source).DataContext as CommandItem;
if (item is null) return;
@@ -88,7 +88,7 @@ namespace mpvnet
items[i.Input] = i;
}
private void Window_Loaded(object sender, RoutedEventArgs e) => Keyboard.Focus(SearchControl.SearchTextBox);
void Window_Loaded(object sender, RoutedEventArgs e) => Keyboard.Focus(SearchControl.SearchTextBox);
string GetInputConfContent()
{
@@ -120,14 +120,14 @@ namespace mpvnet
return text;
}
private void Window_Closed(object sender, EventArgs e)
void Window_Closed(object sender, EventArgs e)
{
if (InitialInputConfContent == GetInputConfContent()) return;
File.WriteAllText(mp.InputConfPath, GetInputConfContent());
Msg.Show("Changes will be available on next mpv.net startup.");
}
private void DataGrid_PreviewCanExecute(object sender, CanExecuteRoutedEventArgs e)
void DataGrid_PreviewCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
DataGrid grid = (DataGrid)sender;

View File

@@ -17,7 +17,7 @@ namespace mpvnet
public LearnWindow() => InitializeComponent();
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
WinForms.Message m = new WinForms.Message();
m.HWnd = hwnd;
@@ -317,26 +317,26 @@ namespace mpvnet
out uint lpChar,
uint flags);
private void Window_Loaded(object sender, RoutedEventArgs e)
void Window_Loaded(object sender, RoutedEventArgs e)
{
HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
source.AddHook(new HwndSourceHook(WndProc));
SetKey(InputItem.Input);
}
private void ConfirmButton_Click(object sender, RoutedEventArgs e)
void ConfirmButton_Click(object sender, RoutedEventArgs e)
{
InputItem.Input = NewKey;
Close();
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
void ClearButton_Click(object sender, RoutedEventArgs e)
{
InputItem.Input = "_";
Close();
}
private void Window_MouseWheel(object sender, MouseWheelEventArgs e)
void Window_MouseWheel(object sender, MouseWheelEventArgs e)
{
if (e.Delta > 0)
SetKey("WHEEL_UP");
@@ -344,7 +344,7 @@ namespace mpvnet
SetKey("WHEEL_DOWN");
}
private void Window_MouseUp(object sender, MouseButtonEventArgs e)
void Window_MouseUp(object sender, MouseButtonEventArgs e)
{
switch (e.ChangedButton)
{
@@ -368,7 +368,7 @@ namespace mpvnet
bool BlockMBTN_LEFT;
private void Window_MouseDoubleClick(object sender, MouseButtonEventArgs e)
void Window_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
@@ -377,7 +377,7 @@ namespace mpvnet
}
}
private void Window_TextInput(object sender, TextCompositionEventArgs e)
void Window_TextInput(object sender, TextCompositionEventArgs e)
{
KeyChar = e.Text;
}

View File

@@ -1,4 +1,5 @@
using System.Windows;

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
@@ -13,7 +14,7 @@ namespace Controls
public string Text { get => SearchTextBox.Text; set => SearchTextBox.Text = value; }
private string _HintText;
string _HintText;
public string HintText {
get => _HintText;
@@ -23,13 +24,13 @@ namespace Controls
}
}
private void SearchClearButton_Click(object sender, RoutedEventArgs e)
void SearchClearButton_Click(object sender, RoutedEventArgs e)
{
SearchTextBox.Text = "";
Keyboard.Focus(SearchTextBox);
}
private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
UpdateControls();
}

View File

@@ -27,13 +27,13 @@ namespace mpvnet
} catch {}
}
private void RegisterVideo_Click(object sender, RoutedEventArgs e) => RegisterFileAssociations("video");
private void RegisterAudio_Click(object sender, RoutedEventArgs e) => RegisterFileAssociations("audio");
private void RegisterImage_Click(object sender, RoutedEventArgs e) => RegisterFileAssociations("image");
void RegisterVideo_Click(object sender, RoutedEventArgs e) => RegisterFileAssociations("video");
void RegisterAudio_Click(object sender, RoutedEventArgs e) => RegisterFileAssociations("audio");
void RegisterImage_Click(object sender, RoutedEventArgs e) => RegisterFileAssociations("image");
private void UnregisterFileAssociations_Click(object sender, RoutedEventArgs e) => RegisterFileAssociations("unreg");
void UnregisterFileAssociations_Click(object sender, RoutedEventArgs e) => RegisterFileAssociations("unreg");
private void AddToPathEnvVar_Click(object sender, RoutedEventArgs e)
void AddToPathEnvVar_Click(object sender, RoutedEventArgs e)
{
string var = WinForms.Application.StartupPath + ";";
string path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);
@@ -47,7 +47,7 @@ namespace mpvnet
}
}
private void RemoveFromPathEnvVar_Click(object sender, RoutedEventArgs e)
void RemoveFromPathEnvVar_Click(object sender, RoutedEventArgs e)
{
string var = WinForms.Application.StartupPath + ";";
string path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);

View File

@@ -43,6 +43,7 @@ namespace mpvnet
Instance = this;
Hwnd = Handle;
ConsoleHelp.Padding = 60;
mp.Init();
mp.Shutdown += Shutdown;
@@ -64,8 +65,8 @@ namespace mpvnet
if (mp.GPUAPI != "vulkan")
mp.ProcessCommandLine(false);
AppDomain.CurrentDomain.UnhandledException += (sender, e) => Msg.ShowError(e.ExceptionObject.ToString());
Application.ThreadException += (sender, e) => Msg.ShowException(e.Exception);
AppDomain.CurrentDomain.UnhandledException += (sender, e) => App.ShowException(e.ExceptionObject);
Application.ThreadException += (sender, e) => App.ShowException(e.Exception);
Msg.SupportURL = "https://github.com/stax76/mpv.net#support";
Text = "mpv.net " + Application.ProductVersion;
TaskbarButtonCreatedMessage = WinAPI.RegisterWindowMessage("TaskbarButtonCreated");
@@ -413,7 +414,7 @@ namespace mpvnet
}
}
private void FileLoaded()
void FileLoaded()
{
string path = mp.get_property_string("path");
@@ -572,9 +573,8 @@ namespace mpvnet
CursorHelp.Hide();
}
private void ProgressTimer_Tick(object sender, EventArgs e) => UpdateProgressBar();
void ProgressTimer_Tick(object sender, EventArgs e) => UpdateProgressBar();
// TODO: why is this in mainform?
void UpdateProgressBar()
{
if (mp.TaskbarProgress && Taskbar != null)
@@ -686,6 +686,9 @@ namespace mpvnet
if (!mp.ShutdownAutoResetEvent.WaitOne(10000))
Msg.ShowError("Shutdown thread failed to complete within 10 seconds.");
//foreach (var i in PowerShell1.Instances)
// i.RS.Close();
}
protected override void OnMouseDown(MouseEventArgs e)

View File

@@ -118,6 +118,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Misc\App.cs" />
<Compile Include="Misc\Common.cs" />
<Compile Include="Misc\Extension.cs" />
<Content Include="..\License.txt">
<Link>License.txt</Link>
@@ -155,6 +156,7 @@
<Compile Include="Misc\UpdateCheck.cs" />
<Compile Include="Misc\RegistryHelp.cs" />
<Compile Include="Misc\Theme.cs" />
<Compile Include="Scripting\PowerShell.cs" />
<Compile Include="WPF\SearchTextBoxUserControl.xaml.cs">
<DependentUpon>SearchTextBoxUserControl.xaml</DependentUpon>
</Compile>
@@ -172,7 +174,6 @@
<Compile Include="WinForms\Menu.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Scripting\PowerShellScript.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>

View File

@@ -13,10 +13,13 @@ using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ScriptHost;
using WinForms = System.Windows.Forms;
using static libmpv;
using static WinAPI;
using static Common;
namespace mpvnet
{
@@ -86,9 +89,9 @@ namespace mpvnet
public static int Screen { get; set; } = -1;
public static int Edition { get; set; }
public static float Autofit { get; set; } = 0.5f;
public static float AutofitSmaller { get; set; } = 0.4f;
public static float AutofitLarger { get; set; } = 0.75f;
public static float Autofit { get; set; } = 0.6f;
public static float AutofitSmaller { get; set; } = 0.3f;
public static float AutofitLarger { get; set; } = 0.8f;
public static void Init()
{
@@ -253,7 +256,7 @@ namespace mpvnet
}
}
public static string[] KnownScripts { get; } = { "osc-visibility.js", "show-playlist.js", "seek-show-position.py" };
public static string[] KnownScripts { get; } = { "show-playlist.js", "seek-show-position.py" };
public static void LoadScripts()
{
@@ -264,21 +267,36 @@ namespace mpvnet
if (KnownScripts.Contains(Path.GetFileName(scriptPath)))
{
if (scriptPath.EndsWith(".py"))
Task.Run(() => PythonScripts.Add(new PythonScript(scriptPath)));
App.RunAction(() => PythonScripts.Add(new PythonScript(scriptPath)));
else if (scriptPath.EndsWith(".ps1"))
Task.Run(() => PowerShellScript.Init(scriptPath));
App.RunAction(() => InvokePowerShellScript(scriptPath));
}
else
Msg.ShowError("Failed to load script", scriptPath + "\n\nOnly scripts that ship with mpv.net are allowed in <startup>\\scripts\n\nUser scripts have to use <config folder>\\scripts\n\nNever copy or install a new mpv.net version over a old mpv.net version.");
Msg.ShowError("Failed to load script", scriptPath + BR + "Only scripts that ship with mpv.net are allowed in <startup>\\scripts\n\nUser scripts have to use <config folder>\\scripts\n\nNever copy or install a new mpv.net version over a old mpv.net version.");
}
}
if (Directory.Exists(ConfigFolder + "scripts"))
foreach (string scriptPath in Directory.GetFiles(ConfigFolder + "scripts"))
if (scriptPath.EndsWith(".py"))
Task.Run(() => PythonScripts.Add(new PythonScript(scriptPath)));
App.RunAction(() => PythonScripts.Add(new PythonScript(scriptPath)));
else if (scriptPath.EndsWith(".ps1"))
Task.Run(() => PowerShellScript.Init(scriptPath));
App.RunAction(() => InvokePowerShellScript(scriptPath));
}
public static void InvokePowerShellScript(string file)
{
PowerShell ps = new PowerShell();
ps.Scripts.Add("Using namespace mpvnet" + BR +
"[Reflection.Assembly]::LoadWithPartialName('mpvnet')" + BR);
ps.Scripts.Add(File.ReadAllText(file));
ps.Module = Path.GetFileName(file);
ps.Print = true;
lock (PowerShell.Instances)
PowerShell.Instances.Add(ps);
ps.Invoke();
}
public static void EventLoop()
@@ -626,10 +644,10 @@ namespace mpvnet
if (throwException)
{
foreach (string msg in messages)
ConsoleHelp.WriteError(msg);
ConsoleHelp.WriteError(msg, "mpv.net");
ConsoleHelp.WriteError(GetError(err));
throw new Exception(string.Join("\r\r", messages) + "\r\r"+ GetError(err));
ConsoleHelp.WriteError(GetError(err), "mpv.net");
throw new Exception(string.Join(BR2, messages) + BR2 + GetError(err));
}
}
@@ -637,20 +655,30 @@ namespace mpvnet
{
var args = Environment.GetCommandLineArgs().Skip(1);
//Msg.Show(string.Join("\n", args));
string[] preInitProperties = { "input-terminal", "terminal", "input-file", "config", "config-dir", "input-conf", "load-scripts", "scripts", "player-operation-mode" };
string[] preInitProperties = { "input-terminal", "terminal", "input-file", "config",
"config-dir", "input-conf", "load-scripts", "scripts", "player-operation-mode" };
foreach (string i in args)
{
string arg = i;
if (arg.StartsWith("--"))
if (arg.StartsWith("-"))
{
try
{
if (!arg.StartsWith("--"))
arg = "-" + arg;
if (!arg.Contains("="))
arg += "=yes";
{
if (arg.Contains("--no-"))
{
arg = arg.Replace("--no-", "--");
arg += "=no";
}
else
arg += "=yes";
}
string left = arg.Substring(2, arg.IndexOf("=") - 2);
string right = arg.Substring(left.Length + 3);
@@ -667,13 +695,10 @@ namespace mpvnet
}
else if (!preInit && !preInitProperties.Contains(left))
{
if (!PrintCommandLineArgument(arg))
{
mp.ProcessProperty(left, right);
mp.ProcessProperty(left, right);
if (!App.ProcessProperty(left, right))
set_property_string(left, right, true);
}
if (!App.ProcessProperty(left, right))
set_property_string(left, right, true);
}
}
catch (Exception e)
@@ -707,22 +732,6 @@ namespace mpvnet
}
}
static bool PrintCommandLineArgument(string argument)
{
switch (argument)
{
case "--list-properties=yes":
{
var list = get_property_string("property-list").Split(',').ToList();
list.Sort();
Console.WriteLine(string.Join("\n", list.ToArray()));
return true;
}
}
return false;
}
public static DateTime LastLoad;
public static void Load(string[] files, bool loadFolder, bool append)