<commit_before>﻿using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using NMaier.SimpleDlna.FileMediaServer;
using NMaier.SimpleDlna.Server;
using NMaier.SimpleDlna.Utilities;
using System.Threading.Tasks;

namespace NMaier.SimpleDlna.GUI
{
  public partial class FormMain : Form, IAppender, IDisposable
  {
    private readonly Properties.Settings Config = Properties.Settings.Default;
    private HttpServer httpServer;
    private readonly FileInfo cacheFile = new FileInfo(Path.Combine(Path.GetTempPath(), "sdlna.cache"));
    private bool canClose = false;

    public FormMain()
    {
      InitializeComponent();
      SetupLogging();
      StartPipeNotification();

      notifyIcon.Icon = Icon;
      if (!string.IsNullOrWhiteSpace(Config.cache)) {
        cacheFile = new FileInfo(Config.cache);
      }
    }

    private void SetupLogging()
    {
      BasicConfigurator.Configure(this);
      LogManager.GetRepository().Threshold = Level.Info;
    }

    private void StartPipeNotification()
    {
      new Thread(() =>
       {
         for (; ; ) {
           try {
             using (var pipe = new NamedPipeServerStream("simpledlnagui", PipeDirection.InOut)) {
               pipe.WaitForConnection();
               pipe.ReadByte();
               BeginInvoke((Action)(() =>
               {
                 notifyIcon_DoubleClick(null, null);
                 BringToFront();
               }));
             }
           }
           catch (Exception) {
           }
         }
       }) { IsBackground = true }.Start();
    }

    private void ButtonNewServer_Click(object sender, EventArgs e)
    {
      using (var ns = new FormServer()) {
        var rv = ns.ShowDialog();
        if (rv == DialogResult.OK) {
          var item = new ServerListViewItem(httpServer, cacheFile, ns.Description);
          listDescriptions.Items.Add(item);
          SaveConfig();
        }
      }
    }

    private void ListDescriptions_SelectedIndexChanged(object sender, EventArgs e)
    {
      var enable = listDescriptions.SelectedItems.Count != 0;
      buttonStartStop.Enabled = buttonRemove.Enabled = buttonEdit.Enabled = enable;
      if (enable) {
        buttonStartStop.Text = (listDescriptions.SelectedItems[0] as ServerListViewItem).Description.Active ? "Stop" : "Start";
      }
    }

    private void SaveConfig()
    {
      Config.Descriptors = (from ServerListViewItem item in listDescriptions.Items
                            select item.Description).ToList();
      Config.Save();
      SizeDescriptorColumns();
    }

    private void SizeDescriptorColumns()
    {
      var mode = listDescriptions.Items.Count == 0 ? ColumnHeaderAutoResizeStyle.HeaderSize : ColumnHeaderAutoResizeStyle.ColumnContent;
      foreach (var c in listDescriptions.Columns) {
        (c as ColumnHeader).AutoResize(mode);
      }
    }
    private void LoadConfig()
    {
      Task.Factory.StartNew(() =>
      {
        foreach (var d in Config.Descriptors) {
          var f = new ServerListViewItem(httpServer, cacheFile, d);
          Invoke((Action)(() =>
          {
            listDescriptions.Items.Add(f);
            SizeDescriptorColumns();
          }));
        }
      });
    }

    private void ButtonEdit_Click(object sender, EventArgs e)
    {
      var item = listDescriptions.SelectedItems[0] as ServerListViewItem;
      if (item == null) {
        return;
      }
      using (var ns = new FormServer(item.Description)) {
        var rv = ns.ShowDialog();
        if (rv == DialogResult.OK) {
          item.UpdateInfo(ns.Description);
          SaveConfig();
        }
      }
    }

    private void ButtonStartStop_Click(object sender, EventArgs e)
    {
      var item = listDescriptions.SelectedItems[0] as ServerListViewItem;
      if (item == null) {
        return;
      }
      item.Toggle();
      SaveConfig();

      buttonStartStop.Text = item.Description.Active ? "Stop" : "Start";
    }

    private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
    {
      httpServer.Dispose();
      Thread.Sleep(2000);
    }

    private delegate void logDelegate(string level, string logger, string msg);

    public void DoAppend(LoggingEvent loggingEvent)
    {
      var cls = loggingEvent.LoggerName;
      cls = cls.Substring(cls.LastIndexOf('.') + 1);
      BeginInvoke(new logDelegate((lvl, lg, msg) =>
      {
        if (logger.Items.Count >= 300) {
          logger.Items.RemoveAt(0);<commit_msg>GUI: Async update stuff<commit_after>﻿using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using NMaier.SimpleDlna.FileMediaServer;
using NMaier.SimpleDlna.Server;
using NMaier.SimpleDlna.Utilities;
using System.Threading.Tasks;

namespace NMaier.SimpleDlna.GUI
{
  public partial class FormMain : Form, IAppender, IDisposable
  {
    private readonly Properties.Settings Config = Properties.Settings.Default;
    private HttpServer httpServer;
    private readonly FileInfo cacheFile = new FileInfo(Path.Combine(Path.GetTempPath(), "sdlna.cache"));
    private bool canClose = false;

    public FormMain()
    {
      InitializeComponent();
      SetupLogging();
      StartPipeNotification();

      notifyIcon.Icon = Icon;
      if (!string.IsNullOrWhiteSpace(Config.cache)) {
        cacheFile = new FileInfo(Config.cache);
      }
    }

    private void SetupLogging()
    {
      BasicConfigurator.Configure(this);
      LogManager.GetRepository().Threshold = Level.Info;
    }

    private void StartPipeNotification()
    {
      new Thread(() =>
       {
         for (; ; ) {
           try {
             using (var pipe = new NamedPipeServerStream("simpledlnagui", PipeDirection.InOut)) {
               pipe.WaitForConnection();
               pipe.ReadByte();
               BeginInvoke((Action)(() =>
               {
                 notifyIcon_DoubleClick(null, null);
                 BringToFront();
               }));
             }
           }
           catch (Exception) {
           }
         }
       }) { IsBackground = true }.Start();
    }

    private void ButtonNewServer_Click(object sender, EventArgs e)
    {
      using (var ns = new FormServer()) {
        var rv = ns.ShowDialog();
        if (rv == DialogResult.OK) {
          var item = new ServerListViewItem(httpServer, cacheFile, ns.Description);
          listDescriptions.Items.Add(item);
          SaveConfig();
        }
      }
    }

    private void ListDescriptions_SelectedIndexChanged(object sender, EventArgs e)
    {
      var enable = listDescriptions.SelectedItems.Count != 0;
      buttonStartStop.Enabled = buttonRemove.Enabled = buttonEdit.Enabled = enable;
      if (enable) {
        buttonStartStop.Text = (listDescriptions.SelectedItems[0] as ServerListViewItem).Description.Active ? "Stop" : "Start";
      }
    }

    private void SaveConfig()
    {
      Config.Descriptors = (from ServerListViewItem item in listDescriptions.Items
                            select item.Description).ToList();
      Config.Save();
      SizeDescriptorColumns();
    }

    private void SizeDescriptorColumns()
    {
      var mode = listDescriptions.Items.Count == 0 ? ColumnHeaderAutoResizeStyle.HeaderSize : ColumnHeaderAutoResizeStyle.ColumnContent;
      foreach (var c in listDescriptions.Columns) {
        (c as ColumnHeader).AutoResize(mode);
      }
    }
    private void LoadConfig()
    {
      Task.Factory.StartNew(() =>
      {
        foreach (var d in Config.Descriptors) {
          var f = new ServerListViewItem(httpServer, cacheFile, d);
          Invoke((Action)(() =>
          {
            listDescriptions.Items.Add(f);
            SizeDescriptorColumns();
          }));
        }
      });
    }

    private void ButtonEdit_Click(object sender, EventArgs e)
    {
      var item = listDescriptions.SelectedItems[0] as ServerListViewItem;
      if (item == null) {
        return;
      }
      using (var ns = new FormServer(item.Description)) {
        var rv = ns.ShowDialog();
        if (rv == DialogResult.OK) {
          var desc = ns.Description;
          Task.Factory.StartNew(() =>
          {
            item.UpdateInfo(desc);
            SaveConfig();
          });
        }
      }
    }

    private void ButtonStartStop_Click(object sender, EventArgs e)
    {
      var item = listDescriptions.SelectedItems[0] as ServerListViewItem;
      if (item == null) {
        return;
      }
      Task.Factory.StartNew(() =>
      {
        item.Toggle();
        BeginInvoke((Action)(() =>
        {
          SaveConfig();
          buttonStartStop.Text = item.Description.Active ? "Stop" : "Start";
        }));
      });

    }

    private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
    {
      httpServer.Dispose();
      Thread.Sleep(2000);
    }

    private delegate void logDelegate(string level, string logger, string msg);

    public void DoAppend(LoggingEvent loggingEvent)
    {
      var cls = loggingEvent.LoggerName;
      cls = cls.Substring(cls.LastIndexOf('.') + 1);
      BeginInvoke(new logDelegate((lvl, lg, msg) =>
      {
        if (logger.Items.Count >= 300) {
          logger.Items.RemoveAt(0);
{'fraction_non_alphanumeric': 0.10666108961622922, 'fraction_numerical': 0.003764509045278678, 'mean_word_length': 2.311634349030471, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '475344', 'n_tokens_mistral': 2685, 'n_tokens_neox': 2647, 'n_words': 570}