Skip to content

Commit

Permalink
chore: refactor the code
Browse files Browse the repository at this point in the history
  • Loading branch information
MrKonstantinSh committed Dec 29, 2020
1 parent 093ca1e commit 3500f59
Show file tree
Hide file tree
Showing 13 changed files with 68 additions and 73 deletions.
2 changes: 1 addition & 1 deletion OpenScreen.Core/Mjpeg/MjpegConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ public static string GetImageInfoHeaders(long contentLength)
return $"\n--boundary\nContent-Type: image/jpeg\nContent-Length: {contentLength}\n\n";
}
}
}
}
15 changes: 7 additions & 8 deletions OpenScreen.Core/Mjpeg/MjpegStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,15 @@ internal static class MjpegStream
/// <returns>An enumerated streams of images represented in MJPEG format.</returns>
internal static IEnumerable<MemoryStream> GetMjpegStream(this IEnumerable<Image> images)
{
using (var memoryStream = new MemoryStream())
using var memoryStream = new MemoryStream();

foreach (var image in images)
{
foreach (var image in images)
{
memoryStream.SetLength(0);
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
memoryStream.SetLength(0);
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);

yield return memoryStream;
}
yield return memoryStream;
}
}
}
}
}
8 changes: 4 additions & 4 deletions OpenScreen.Core/Mjpeg/MjpegWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public MjpegWriter(Stream stream)
/// </summary>
public void WriteHeaders()
{
byte[] headers = Encoding.ASCII.GetBytes(MjpegConstants.ResponseHeaders);
var headers = Encoding.ASCII.GetBytes(MjpegConstants.ResponseHeaders);

const int offset = 0;
_stream.Write(headers, offset, headers.Length);
Expand All @@ -39,15 +39,15 @@ public void WriteHeaders()
/// <param name="imageStream">Stream of images.</param>
public void WriteImage(MemoryStream imageStream)
{
byte[] headers = Encoding.ASCII.GetBytes(
var headers = Encoding.ASCII.GetBytes(
MjpegConstants.GetImageInfoHeaders(imageStream.Length));

const int offset = 0;
_stream.Write(headers, offset, headers.Length);

imageStream.WriteTo(_stream);

byte[] endOfResponse = Encoding.ASCII.GetBytes(MjpegConstants.NewLine);
var endOfResponse = Encoding.ASCII.GetBytes(MjpegConstants.NewLine);

_stream.Write(endOfResponse, offset, endOfResponse.Length);

Expand All @@ -69,4 +69,4 @@ public void Dispose()
}
}
}
}
}
2 changes: 1 addition & 1 deletion OpenScreen.Core/Screenshot/Fps.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ public enum Fps
Thirty = 33,
Fifteen = 66
}
}
}
25 changes: 10 additions & 15 deletions OpenScreen.Core/Screenshot/Resolution.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,21 +46,16 @@ public enum Resolutions
/// <returns>Width and height of resolution.</returns>
public static Size GetResolutionSize(Resolutions resolution)
{
switch (resolution)
return resolution switch
{
case Resolutions.OneThousandAndEightyP:
return new Size(OneThousandAndEightyPWidth, OneThousandAndEightyPHeight);
case Resolutions.SevenHundredAndTwentyP:
return new Size(SevenHundredAndTwentyPWidth, SevenHundredAndTwentyPHeight);
case Resolutions.FourHundredAndEightyP:
return new Size(FourHundredAndEightyPWidth, FourHundredAndEightyPHeight);
case Resolutions.ThreeHundredAndSixtyP:
return new Size(ThreeHundredAndSixtyPWidth, ThreeHundredAndSixtyPHeight);
case Resolutions.TwoHundredAndFortyP:
return new Size(TwoHundredAndFortyPWidth, TwoHundredAndFortyPHeight);
default:
throw new ArgumentOutOfRangeException(nameof(resolution), resolution, null);
}
Resolutions.OneThousandAndEightyP => new Size(OneThousandAndEightyPWidth, OneThousandAndEightyPHeight),
Resolutions.SevenHundredAndTwentyP => new Size(SevenHundredAndTwentyPWidth,
SevenHundredAndTwentyPHeight),
Resolutions.FourHundredAndEightyP => new Size(FourHundredAndEightyPWidth, FourHundredAndEightyPHeight),
Resolutions.ThreeHundredAndSixtyP => new Size(ThreeHundredAndSixtyPWidth, ThreeHundredAndSixtyPHeight),
Resolutions.TwoHundredAndFortyP => new Size(TwoHundredAndFortyPWidth, TwoHundredAndFortyPHeight),
_ => throw new ArgumentOutOfRangeException(nameof(resolution), resolution, null)
};
}
}
}
}
12 changes: 6 additions & 6 deletions OpenScreen.Core/Screenshot/Screenshot.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System;
using System.Drawing;
using System.Windows.Forms;
using OpenScreen.Core.Screenshot.WinFeatures;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using OpenScreen.Core.Screenshot.WinFeatures;
using System.Windows.Forms;

namespace OpenScreen.Core.Screenshot
{
Expand Down Expand Up @@ -89,7 +89,7 @@ public static IEnumerable<Image> TakeSeriesOfScreenshotsAppWindow(string applica
if (!ApplicationWindow.PrintWindow(windowHandle, hdc,
ApplicationWindow.DrawAllWindow))
{
var error = Marshal.GetLastWin32Error();
int error = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception($"An error occurred while creating a screenshot"
+ $" of the application window. Error Number: {error}.");
}
Expand Down Expand Up @@ -144,4 +144,4 @@ private static void AddCursorToScreenshot(Graphics graphics, Rectangle bounds)
graphics.ReleaseHdc();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,4 @@ internal static class ApplicationWindow
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
}
}
}
2 changes: 1 addition & 1 deletion OpenScreen.Core/Screenshot/WinFeatures/MouseCursor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,4 @@ public static extern bool DrawIconEx(IntPtr hdc, int xLeft, int yTop,
IntPtr hIcon, int cxWidth, int cyHeight, int istepIfAniCur,
IntPtr hbrFlickerFreeDraw, int diFlags);
}
}
}
13 changes: 7 additions & 6 deletions OpenScreen.Core/Screenshot/WinFeatures/RunningApplications.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ private enum WindowAttributes : uint
/// of the copied string, not including the terminating null character.</returns>
[DllImport("user32.dll", EntryPoint = "GetWindowText",
ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowTitile(IntPtr handle, StringBuilder buffer, int maxCount);
private static extern int GetWindowTitle(IntPtr handle, StringBuilder buffer, int maxCount);

/// <summary>
/// Retrieves information about the specified window.
Expand Down Expand Up @@ -136,18 +136,19 @@ public static IEnumerable<string> GetListOfRunningApps()
{
var runningApps = new List<string>();

bool filterCallback(IntPtr handle, int callbackParam)
bool FilterCallback(IntPtr handle, int callbackParam)
{
var stringBuilder = new StringBuilder(255);
int _ = GetWindowTitile(handle, stringBuilder, stringBuilder.Capacity + 1);
int _ = GetWindowTitle(handle, stringBuilder, stringBuilder.Capacity + 1);
string appTitle = stringBuilder.ToString();

if (IsWindowVisible(handle) && !string.IsNullOrEmpty(appTitle) && IsHasCaption(handle))
{
runningApps.Add(appTitle);
}

DwmGetWindowAttribute(handle, WindowAttributes.Cloaked, out bool windowAttribute, sizeof(int));
DwmGetWindowAttribute(handle, WindowAttributes.Cloaked, out bool windowAttribute,
sizeof(int));

if (IsIconic(handle) || windowAttribute)
{
Expand All @@ -157,9 +158,9 @@ bool filterCallback(IntPtr handle, int callbackParam)
return true;
}

EnumDesktopWindows(IntPtr.Zero, filterCallback, IntPtr.Zero);
EnumDesktopWindows(IntPtr.Zero, FilterCallback, IntPtr.Zero);

return runningApps;
}
}
}
}
2 changes: 1 addition & 1 deletion OpenScreen.Core/Server/ServerConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ public ServerConfig(IPAddress ipAddress, int port)
Port = port;
}
}
}
}
2 changes: 1 addition & 1 deletion OpenScreen.Core/Server/ServerSocketExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ public static IEnumerable<Socket> GetIncomingConnections(this Socket server)
}
}
}
}
}
25 changes: 12 additions & 13 deletions OpenScreen.Core/Server/StreamingServer.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
using OpenScreen.Core.Screenshot;
using OpenScreen.Core.Mjpeg;
using OpenScreen.Core.Screenshot;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using OpenScreen.Core.Mjpeg;
using System.Diagnostics;

namespace OpenScreen.Core.Server
{
public class StreamingServer
{
private static readonly object s_syncRoot = new object();
private static StreamingServer s_serverInstance;
private static readonly object SyncRoot = new object();
private static StreamingServer _serverInstance;

private IEnumerable<Image> _images;
private Socket _serverSocket;
Expand Down Expand Up @@ -66,12 +65,12 @@ private StreamingServer(IEnumerable<Image> images, Fps fps)
public static StreamingServer GetInstance(Resolution.Resolutions resolutions,
Fps fps, bool isDisplayCursor)
{
lock (s_syncRoot)
lock (SyncRoot)
{
s_serverInstance ??= new StreamingServer(resolutions, fps, isDisplayCursor);
_serverInstance ??= new StreamingServer(resolutions, fps, isDisplayCursor);
}

return s_serverInstance;
return _serverInstance;
}

/// <summary>
Expand All @@ -84,12 +83,12 @@ public static StreamingServer GetInstance(Resolution.Resolutions resolutions,
public static StreamingServer GetInstance(string applicationName,
Fps fps, bool isDisplayCursor)
{
lock (s_syncRoot)
lock (SyncRoot)
{
s_serverInstance ??= new StreamingServer(applicationName, fps, isDisplayCursor);
_serverInstance ??= new StreamingServer(applicationName, fps, isDisplayCursor);
}

return s_serverInstance;
return _serverInstance;
}

/// <summary>
Expand Down Expand Up @@ -134,7 +133,7 @@ public void Stop()
{
_thread = null;
_images = null;
s_serverInstance = null;
_serverInstance = null;
}
}

Expand Down Expand Up @@ -233,4 +232,4 @@ private void StartClientThread(object client)
}
}
}
}
}
31 changes: 16 additions & 15 deletions OpenScreen/OpenScreen.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)

// Filling the combo box with running applications.
var runningApps = GetInfoAboutRunningApps();
foreach (var runningApp in runningApps)
foreach (string runningApp in runningApps)
{
CbAppWindow.Items.Add(runningApp);
}
Expand Down Expand Up @@ -70,15 +70,17 @@ private void CbAppWindow_OnDropDownOpened(object sender, EventArgs e)
var appList = new string[CbAppWindow.Items.Count];
CbAppWindow.Items.CopyTo(appList, 0);

foreach (var item in appList)
var arrayOfRunningApps = runningApps as string[] ?? runningApps.ToArray();

foreach (string item in appList)
{
if (!runningApps.Contains(item))
if (!arrayOfRunningApps.Contains(item))
{
CbAppWindow.Items.Remove(item);
}
}

foreach (var runningApp in runningApps.Where(runningApp =>
foreach (string runningApp in arrayOfRunningApps.Where(runningApp =>
!CbAppWindow.Items.Contains(runningApp)))
{
CbAppWindow.Items.Add(runningApp);
Expand All @@ -102,7 +104,7 @@ private void BtnStartStopStream_Click(object sender, RoutedEventArgs e)
PrintInfo(UiConstants.ServerConfiguration);

var ipAddress = IPAddress.Parse(TbIpAddress.Text);
var port = int.Parse(TbPort.Text);
int port = int.Parse(TbPort.Text);
var fps = GetFpsFromComboBox(CbFps.Text);

CheckSocket(ipAddress, port);
Expand Down Expand Up @@ -189,11 +191,11 @@ private static void CheckSocket(IPAddress ipAddress, int port)
{
try
{
testSocket.Shutdown(SocketShutdown.Both);
testSocket?.Shutdown(SocketShutdown.Both);
}
catch
{
testSocket.Close();
testSocket?.Close();
}
}
}
Expand Down Expand Up @@ -249,7 +251,7 @@ private static Resolution.Resolutions GetResolutionFromComboBox(string selectedS
/// </summary>
private void TimerTick(object sender, EventArgs e)
{
var numberOfConnectedUsers = _streamingServer?.Clients?.Count ?? 0;
int numberOfConnectedUsers = _streamingServer?.Clients?.Count ?? 0;

LblConnectedUsers.Content = UiConstants.ConnectedUsers + numberOfConnectedUsers;
}
Expand All @@ -262,21 +264,20 @@ private void TimerTick(object sender, EventArgs e)
/// <param name="fps">FPS stream.</param>
private void StartStreamingServer(IPAddress ipAddress, int port, Fps fps)
{

if (RbFullScreen.IsChecked == true)
{
var resolution = GetResolutionFromComboBox(CbScreenResolution.Text);
var isDisplayCursor = ChBFullScreenShowCursor.IsChecked != null
&& (bool)ChBFullScreenShowCursor.IsChecked;
bool isDisplayCursor = ChBFullScreenShowCursor.IsChecked != null
&& (bool)ChBFullScreenShowCursor.IsChecked;

_streamingServer = StreamingServer.GetInstance(resolution, fps, isDisplayCursor);
_streamingServer.Start(ipAddress, port);
}
else if (RbAppWindow.IsChecked == true)
{
var applicationName = CbAppWindow.Text;
var isDisplayCursor = ChBAppWindowShowCursor.IsChecked != null
&& (bool)ChBAppWindowShowCursor.IsChecked;
string applicationName = CbAppWindow.Text;
bool isDisplayCursor = ChBAppWindowShowCursor.IsChecked != null
&& (bool)ChBAppWindowShowCursor.IsChecked;

_streamingServer = StreamingServer.GetInstance(applicationName, fps, isDisplayCursor);
_streamingServer.Start(ipAddress, port);
Expand Down Expand Up @@ -332,4 +333,4 @@ private void PrintInfo(string serverInfo)
};
}
}
}
}

0 comments on commit 3500f59

Please sign in to comment.