Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
Fret - Form1.cs

Form1.cs

Caricato da: Totem
Scarica il programma completo

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Text;
  5. using System.Linq;
  6. using System.Windows.Forms;
  7. using System.Diagnostics;
  8. using System.Runtime.InteropServices;
  9. using Microsoft;
  10. using FretMutations;
  11. using System.Net;
  12. using System.IO;
  13. using System.Threading;
  14. using System.Media;
  15.  
  16. namespace Fret
  17. {
  18.     public partial class Form1 : Form
  19.     {
  20.         public Form1()
  21.         {
  22.             InitializeComponent();
  23.         }
  24.  
  25.         #region "Glass Rendering"
  26.  
  27.         [StructLayout(LayoutKind.Sequential)]
  28.         public struct MARGINS
  29.         {
  30.             public int Left;
  31.             public int Right;
  32.             public int Top;
  33.             public int Bottom;
  34.         }
  35.  
  36.         [DllImport("dwmapi.dll", PreserveSig = false)]
  37.         public static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);
  38.  
  39.         [DllImport("dwmapi.dll", PreserveSig = false)]
  40.         public static extern bool DwmIsCompositionEnabled();
  41.  
  42.         private MARGINS margins;
  43.         /*
  44.         protected override void OnLoad(EventArgs e)
  45.         {
  46.             base.OnLoad(e);
  47.             if (DwmIsCompositionEnabled() && Environment.OSVersion.Version.Major >= 6)
  48.             {
  49.                 margins = new MARGINS();
  50.                 margins.Top = Screen.PrimaryScreen.Bounds.Height;
  51.                 margins.Left = Screen.PrimaryScreen.Bounds.Width;
  52.                 DwmExtendFrameIntoClientArea(this.Handle, ref margins);
  53.             }
  54.         }
  55.         protected override void OnPaintBackground(PaintEventArgs e)
  56.         {
  57.             base.OnPaint(e);
  58.             if (DwmIsCompositionEnabled())
  59.             {
  60.                 e.Graphics.Clear(Color.Black);
  61.                 Rectangle clientArea = new Rectangle(
  62.                         margins.Left,
  63.                         margins.Top,
  64.                         this.ClientRectangle.Width - margins.Left - margins.Right,
  65.                         this.ClientRectangle.Height - margins.Top - margins.Bottom
  66.                     );
  67.                 Brush b = new SolidBrush(this.BackColor);
  68.                 e.Graphics.FillRectangle(b, clientArea);
  69.             }
  70.         }
  71.         */
  72.         #endregion
  73.  
  74.         class MusicSheetDownloader
  75.         {
  76.             private static String scriptUrl = "http://clef.cs.ubc.ca/scripts/salieri/gifserv.pl";
  77.  
  78.             public SizeF SheetSize { get; set; }
  79.             public Single Zoom { get; set; }
  80.  
  81.             public MusicSheetDownloader()
  82.             {
  83.                 this.SheetSize = new SizeF(16.0f, 12.0f);
  84.                 this.Zoom = 1.0f;
  85.             }
  86.  
  87.             private Stream GetResponseStream(String musicData)
  88.             {
  89.                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(scriptUrl);
  90.                 Byte[] data = ASCIIEncoding.ASCII.GetBytes(
  91.                     String.Format("defpw={0:N1}cm;defph={1:N1}cm;zoom={2:N1};markvoice=;rtp=;crop=yes;mode=gif;gmndata={3}",
  92.                     this.SheetSize.Width, this.SheetSize.Height, this.Zoom, Uri.EscapeDataString(musicData)));
  93.                 Stream requestStream;
  94.                 request.Method = "POST";
  95.                 request.ContentType = "application/x-www-form-urlencoded";
  96.                 request.ContentLength = data.Length;
  97.                 requestStream = request.GetRequestStream();
  98.                 requestStream.Write(data, 0, data.Length);
  99.                 requestStream.Close();
  100.  
  101.                 WebResponse response = request.GetResponse();
  102.                 return response.GetResponseStream();
  103.             }
  104.  
  105.             public void DownloadSheet(String musicData, String path)
  106.             {
  107.                 Stream reader = this.GetResponseStream(musicData);
  108.                 FileStream writer = new FileStream(path, FileMode.Create, FileAccess.Write);
  109.                 Int32 b;
  110.                 b = reader.ReadByte();
  111.                 while (b > -1)
  112.                 {
  113.                     writer.WriteByte((Byte)b);
  114.                     b = reader.ReadByte();
  115.                 }
  116.                 reader.Close();
  117.                 writer.Close();
  118.             }
  119.  
  120.             public Image GetSheet(String musicData)
  121.             {
  122.                 return Image.FromStream(this.GetResponseStream(musicData));
  123.             }
  124.         }
  125.  
  126.         struct MusicSheetThreadData
  127.         {
  128.             public PictureBox ImageContainer;
  129.             public String MusicData;
  130.         }
  131.  
  132.         struct MutationGuiData
  133.         {
  134.             public FretMutation Mutation;
  135.             public Color Color;
  136.             public Int32 ImageIndex;
  137.         }
  138.  
  139.         private MusicSheetDownloader downloader = new MusicSheetDownloader();
  140.         private FretPiece currentTheme = new FretPiece();
  141.         private Process gmnProcess;
  142.         private StreamReader gmnProcessOutput;
  143.         private FretMutationGenerator mutationGenerator;
  144.         private MutationGuiData[] defaultMutationsData;
  145.         private Fret result;
  146.  
  147.         private const String tmpGmnFile = "tmp.gmn";
  148.         private const String tmpMidFile = "tmp.mid";
  149.  
  150.         private void DownloadAndDisplay(Object threadData)
  151.         {
  152.             MusicSheetThreadData data = (MusicSheetThreadData)threadData;
  153.             try
  154.             {
  155.                 data.ImageContainer.Image = downloader.GetSheet(data.MusicData);
  156.                 data.ImageContainer.SizeMode = PictureBoxSizeMode.Zoom;
  157.             }
  158.             catch
  159.             {
  160.                 MessageBox.Show("Impossibile renderizzare il tema proposto. E' possibile che vi siano errori di sintassi nel codice.", "Errore", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  161.             }
  162.         }
  163.  
  164.         private void GatherGuiData()
  165.         {
  166.             currentTheme.Meter = new Meter(Convert.ToInt32(lblMeterNum.Text), Convert.ToInt32(lblMeterDen.Text));
  167.             currentTheme.Tempo.BeatDuration = new Fraction(1, (Int32)Math.Pow(2.0, (Double)cmbUnitBeat.SelectedIndex));
  168.             currentTheme.Tempo.BeatsPerMinute = (Int32)nudBeatsPerMinute.Value;
  169.             currentTheme.Key.Accidentals = (SByte)(dudKey.SelectedIndex - 6);
  170.             currentTheme.Key.IsMajor = !chbMinor.Checked;
  171.         }
  172.  
  173.         private Bitmap GetMutationsChart()
  174.         {
  175.             Bitmap result = new Bitmap(200, 200);
  176.             Graphics g = Graphics.FromImage(result);
  177.             Double totalWeight = defaultMutationsData.Sum(data => data.Mutation.Weight);
  178.             Rectangle bounds = new Rectangle(5, 5, 190, 190);
  179.             Single angle = 0.0f;
  180.  
  181.             g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
  182.             foreach (MutationGuiData data in defaultMutationsData)
  183.             {
  184.                 Single span = (Single)(360 * data.Mutation.Weight / totalWeight);
  185.                 g.FillPie(new SolidBrush(data.Color), bounds, angle, span);
  186.                 g.DrawPie(Pens.Black, bounds, angle, span);
  187.                 angle += span;
  188.             }
  189.  
  190.             g.Flush();
  191.             return result;
  192.         }
  193.  
  194.         private Boolean RunDefaultConversionProcess()
  195.         {
  196.             gmnProcess.Start();
  197.             gmnProcessOutput = gmnProcess.StandardOutput;
  198.             gmnProcess.WaitForExit();
  199.             gmnProcess.Close();
  200.  
  201.             String line;
  202.             while ((line = gmnProcessOutput.ReadLine()) != null)
  203.                 if (line.Contains("ERROR"))
  204.                 {
  205.                     MessageBox.Show("Il programma di conversione ha rilevato un errore:\n\n" + line + "\n\nImpossibile terminare il salvataggio. Ricontrollare la sintassi.",
  206.                         "Errore di conversione", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  207.                     return false;
  208.                 }
  209.  
  210.             return File.Exists(tmpMidFile);
  211.         }
  212.  
  213.         private void Form1_Load(object sender, EventArgs e)
  214.         {
  215.             if (!File.Exists("gmn2midi.exe"))
  216.             {
  217.                 MessageBox.Show("Impossibile avviare all'applicazione. Il programma di encoding (gmn2midi.exe) non è stato trovato nella cartella attuale.", "Impossibile iniziare",
  218.                     MessageBoxButtons.OK, MessageBoxIcon.Error);
  219.                 Application.Exit();
  220.             }
  221.             dudKey.SelectedIndex = 6;
  222.             imgKeyPreview.Image = imgKeys.Images[6];
  223.             cmbUnitBeat.SelectedIndex = 2;
  224.  
  225.             gmnProcess = new Process();
  226.             gmnProcess.StartInfo.UseShellExecute = false;
  227.             gmnProcess.StartInfo.RedirectStandardOutput = true;
  228.             gmnProcess.StartInfo.CreateNoWindow = true;
  229.             gmnProcess.StartInfo.FileName = "gmn2midi.exe";
  230.             gmnProcess.StartInfo.Arguments = tmpGmnFile;
  231.  
  232.             mutationGenerator = new FretMutationGenerator();
  233.             FretMutation[] tempMutations =
  234.                 new FretMutation[] {new NoteVariation(), new ChordAddition(), new OctaveTransposition(),
  235.                 new NoteSplitting(), new HarmonicSymmetry(), new VerticalTranslation(), new RelativeTransposition(),
  236.                 new RagtimeTransformation()};
  237.             Color[] tempColors =
  238.                 new Color[] { Color.Black, Color.DodgerBlue, Color.ForestGreen, Color.Orange,
  239.                 Color.Magenta, Color.SeaGreen, Color.Red, Color.Aquamarine };
  240.             defaultMutationsData = new MutationGuiData[tempMutations.Length];
  241.             for (Int32 i = 0; i < tempMutations.Length; i++)
  242.             {
  243.                 ListViewItem item = new ListViewItem();
  244.                 item.ImageIndex = i;
  245.                 defaultMutationsData[i].ImageIndex = i;
  246.                 defaultMutationsData[i].Mutation = tempMutations[i];
  247.                 defaultMutationsData[i].Color = tempColors[i];
  248.                 item.Text = tempMutations[i].GetType().Name;
  249.                 item.Tag = tempMutations[i];
  250.                 item.ForeColor = tempColors[i];
  251.                 item.Checked = true;
  252.                 lstMutations.Items.Add(item);
  253.             }
  254.  
  255.             AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
  256.         }
  257.  
  258.         private void button1_Click(object sender, EventArgs e)
  259.         {
  260.             Thread background = new Thread(DownloadAndDisplay);
  261.             String completeData;
  262.             this.GatherGuiData();
  263.             completeData = "{[" + String.Format("{0} {1} {2} {3}", currentTheme.Meter.ToGuidoNotation(),
  264.                 currentTheme.Key.ToGuidoNotation(), currentTheme.Tempo.ToGuidoNotation(), txtOriginalTheme.Text) + "]}";
  265.             background.Start(new MusicSheetThreadData() { ImageContainer = imgSheetPreview, MusicData = completeData });
  266.             imgSheetPreview.Image = imgSheetPreview.ErrorImage;
  267.             imgKeyPreview.SizeMode = PictureBoxSizeMode.CenterImage;
  268.         }
  269.  
  270.         private void cmbUnitBeat_DrawItem(object sender, DrawItemEventArgs e)
  271.         {
  272.             Rectangle bounds = e.Bounds;
  273.             Brush brush = Brushes.Black;
  274.             if ((e.State & (DrawItemState.Focus)) != 0)
  275.             {
  276.                 e.Graphics.FillRectangle(Brushes.DodgerBlue, bounds);
  277.                 brush = Brushes.White;
  278.             }
  279.             else
  280.                 e.Graphics.FillRectangle(Brushes.White, bounds);
  281.             if (e.Index > -1)
  282.             {
  283.                 e.Graphics.DrawImage(imgNotes.Images[e.Index], bounds.X + 5, bounds.Y + 1);
  284.                 e.Graphics.DrawString(cmbUnitBeat.Items[e.Index].ToString(), e.Font, Brushes.Black, bounds.X + 35.0f, bounds.Y + 13.0f);
  285.             }
  286.         }
  287.  
  288.         private void trkMeterNum_Scroll(object sender, EventArgs e)
  289.         {
  290.             lblMeterNum.Text = trkMeterNum.Value.ToString();
  291.         }
  292.  
  293.         private void trkMeterDen_Scroll(object sender, EventArgs e)
  294.         {
  295.             lblMeterDen.Text = Math.Pow(2.0, (Double)trkMeterDen.Value).ToString("N0");
  296.             trkMeterNum.Maximum = (Int32)Math.Pow(2.0, (Double)trkMeterDen.Value);
  297.             lblMeterNum.Text = trkMeterNum.Value.ToString();
  298.         }
  299.  
  300.         private void dudKey_SelectedItemChanged(object sender, EventArgs e)
  301.         {
  302.             imgKeyPreview.Image = imgKeys.Images[dudKey.SelectedIndex];
  303.         }
  304.  
  305.         private void btnConvert2Midi_Click(object sender, EventArgs e)
  306.         {
  307.             if (fSave.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  308.             {
  309.                 GatherGuiData();
  310.                 File.WriteAllText(tmpGmnFile, "{[" + String.Format("{0} {1} {2} {3}", currentTheme.Meter.ToGuidoNotation(),
  311.                     currentTheme.Key.ToGuidoNotation(), currentTheme.Tempo.ToGuidoNotation(), txtOriginalTheme.Text) + "]}");
  312.                 if (RunDefaultConversionProcess())
  313.                 {
  314.                     if (File.Exists(fSave.FileName))
  315.                         File.Delete(fSave.FileName);
  316.                     File.Move(tmpMidFile, fSave.FileName);
  317.                 }
  318.             }
  319.         }
  320.  
  321.         private void lstMutations_SelectedIndexChanged(object sender, EventArgs e)
  322.         {
  323.             if (lstMutations.SelectedIndices.Count < 1)
  324.                 return;
  325.             pgMutationProperties.SelectedObject = lstMutations.SelectedItems[0].Tag;
  326.         }
  327.  
  328.         private void lstMutations_ItemChecked(object sender, ItemCheckedEventArgs e)
  329.         {
  330.             (e.Item.Tag as FretMutation).Weight = (e.Item.Checked ? 1.0 : 0.0);
  331.             imgMutationsChart.Image = GetMutationsChart();
  332.         }
  333.  
  334.         private void pgMutationProperties_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
  335.         {
  336.             if (e.ChangedItem.Label == "Weight")
  337.                 imgMutationsChart.Image = GetMutationsChart();
  338.         }
  339.  
  340.         private void btnGo_Click(object sender, EventArgs e)
  341.         {
  342.             if (String.IsNullOrEmpty(txtOriginalTheme.Text))
  343.             {
  344.                 MessageBox.Show("Nessuna melodia presente come tema principale!", "Nessuna melodia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  345.                 lblGeneratorStatus.Text = "Fine";
  346.                 return;
  347.             }
  348.  
  349.             lblGeneratorStatus.Text = "Controllo mutazioni";
  350.             mutationGenerator.Mutations.Clear();
  351.             foreach (ListViewItem item in lstMutations.Items)
  352.                 if (item.Checked)
  353.                     mutationGenerator.Mutations.Add(item.Tag as FretMutation);
  354.             if (mutationGenerator.Mutations.Count == 0)
  355.             {
  356.                 MessageBox.Show("Nessuna mutazione selezionata!", "Nessuna mutazione", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  357.                 lblGeneratorStatus.Text = "Fine";
  358.                 return;
  359.             }
  360.  
  361.             lblGeneratorStatus.Text = "Generazione melodia";
  362.             currentTheme.Clear();
  363.             try
  364.             {
  365.                 currentTheme.AddFromGuidoString(txtOriginalTheme.Text);
  366.             }
  367.             catch (Exception ex)
  368.             {
  369.                 MessageBox.Show(ex.Message + "\n\nSi è verificato un errore nel parsing della melodia principale. Impossibile continuare.", "Errore di parsing",
  370.                         MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  371.                 return;
  372.             }
  373.             GatherGuiData();
  374.  
  375.             if (fSave.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  376.             {
  377.                 lblGeneratorStatus.Text = "Applicazione mutazioni...";
  378.                 bgMutate.RunWorkerAsync(fSave.FileName);
  379.             }
  380.         }
  381.  
  382.         private void bgMutate_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
  383.         {
  384.             String savePath = e.Argument as String;
  385.             try
  386.             {
  387.                 if (chbIncremental.Checked)
  388.                     result = mutationGenerator.ApplyIncrementalMutations(currentTheme, (Int32)nudIterations.Value);
  389.                 else
  390.                     result = mutationGenerator.ApplyMutations(currentTheme, (Int32)nudIterations.Value);
  391.             }
  392.             catch (Exception ex)
  393.             {
  394.                 MessageBox.Show(ex.Message, ex.GetType().Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
  395.                 return;
  396.             }
  397.             result.SaveGuidoNotationFile(tmpGmnFile);
  398.  
  399.             if (RunDefaultConversionProcess())
  400.             {
  401.                 if (File.Exists(savePath))
  402.                     File.Delete(savePath);
  403.                 File.Move(tmpMidFile, savePath);
  404.  
  405.                 if (chbSaveSheet.Checked)
  406.                 {
  407.                     String sheetPath = Path.GetDirectoryName(savePath) + "\\" + Path.GetFileNameWithoutExtension(savePath) + ".gif";
  408.                     downloader.DownloadSheet(File.ReadAllText(tmpGmnFile), sheetPath);
  409.                 }
  410.             }
  411.             else
  412.                 MessageBox.Show("Si è verificato un errore di natura sconosiuta nell'encoder.", "Errore gmn2midi", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  413.  
  414.             if (chbSingleMutation.Checked)
  415.             {
  416.                 Int32 i = 1;
  417.                 foreach (FretPiece piece in result)
  418.                 {
  419.                     piece.SaveGuidoNotationFile(tmpGmnFile);
  420.                     if (RunDefaultConversionProcess())
  421.                     {
  422.                         String path = Path.GetDirectoryName(savePath) + "\\" + Path.GetFileNameWithoutExtension(savePath) + (i++).ToString() + ".mid";
  423.                         if (File.Exists(path))
  424.                             File.Delete(path);
  425.                         File.Move(tmpMidFile, path);
  426.                     }
  427.                     bgMutate.ReportProgress((Int32)(100 * (Double)i / result.Count));
  428.                 }
  429.             }
  430.         }
  431.  
  432.         private void bgMutate_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
  433.         {
  434.             lblGeneratorStatus.Text = "Salvataggio singole tracce " + e.ProgressPercentage.ToString() + "%";
  435.         }
  436.  
  437.         private void bgMutate_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
  438.         {
  439.             lblGeneratorStatus.Text = "Fine";
  440.         }
  441.  
  442.         private void imgSheetPreview_Click(object sender, EventArgs e)
  443.         {
  444.             Form preview = new Form();
  445.             preview.BackgroundImage = imgSheetPreview.Image;
  446.             preview.BackgroundImageLayout = ImageLayout.Zoom;
  447.             preview.Show();
  448.         }
  449.  
  450.         private void strSaveSheetPreviewAs_Click(object sender, EventArgs e)
  451.         {
  452.             if (saveSheetDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  453.                 imgSheetPreview.Image.Save(saveSheetDialog.FileName);
  454.         }
  455.  
  456.         private void chbIncremental_CheckedChanged(object sender, EventArgs e)
  457.         {
  458.             if (chbIncremental.Checked)
  459.                 chbSingleMutation.Checked = false;
  460.         }
  461.  
  462.         private void chbSingleMutation_CheckedChanged(object sender, EventArgs e)
  463.         {
  464.             if (chbSingleMutation.Checked)
  465.                 chbIncremental.Checked = false;
  466.         }
  467.  
  468.         private void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  469.         {
  470.             if (e.ExceptionObject.GetType().IsSubclassOf(typeof(Exception)))
  471.             {
  472.                 Exception ex = e.ExceptionObject as Exception;
  473.                 MessageBox.Show("Si è verificata un'eccezione non gestita. Il messaggio di errore è il seguente: \n\n" + ex.Message, ex.GetType().Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
  474.             }
  475.             else
  476.                 MessageBox.Show("Si è verificata un'eccezione di natura sconosciuta.", "WTF???", MessageBoxButtons.OK, MessageBoxIcon.Error);
  477.         }
  478.     }
  479. }