using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft;
using FretMutations;
using System.Net;
using System.IO;
using System.Threading;
using System.Media;
namespace Fret
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
#region "Glass Rendering"
[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
public int Left;
public int Right;
public int Top;
public int Bottom;
}
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern bool DwmIsCompositionEnabled();
private MARGINS margins;
/*
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (DwmIsCompositionEnabled() && Environment.OSVersion.Version.Major >= 6)
{
margins = new MARGINS();
margins.Top = Screen.PrimaryScreen.Bounds.Height;
margins.Left = Screen.PrimaryScreen.Bounds.Width;
DwmExtendFrameIntoClientArea(this.Handle, ref margins);
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaint(e);
if (DwmIsCompositionEnabled())
{
e.Graphics.Clear(Color.Black);
Rectangle clientArea = new Rectangle(
margins.Left,
margins.Top,
this.ClientRectangle.Width - margins.Left - margins.Right,
this.ClientRectangle.Height - margins.Top - margins.Bottom
);
Brush b = new SolidBrush(this.BackColor);
e.Graphics.FillRectangle(b, clientArea);
}
}
*/
#endregion
class MusicSheetDownloader
{
private static String scriptUrl = "http://clef.cs.ubc.ca/scripts/salieri/gifserv.pl";
public SizeF SheetSize { get; set; }
public Single Zoom { get; set; }
public MusicSheetDownloader()
{
this.
SheetSize = new SizeF
(16.0f, 12.0f
);
this.Zoom = 1.0f;
}
private Stream GetResponseStream(String musicData)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(scriptUrl);
Byte[] data = ASCIIEncoding.ASCII.GetBytes(
String.Format("defpw={0:N1}cm;defph={1:N1}cm;zoom={2:N1};markvoice=;rtp=;crop=yes;mode=gif;gmndata={3}",
this.SheetSize.Width, this.SheetSize.Height, this.Zoom, Uri.EscapeDataString(musicData)));
Stream requestStream;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
return response.GetResponseStream();
}
public void DownloadSheet(String musicData, String path)
{
Stream reader = this.GetResponseStream(musicData);
FileStream writer
= new FileStream
(path, FileMode.
Create, FileAccess.
Write);
Int32 b;
b = reader.ReadByte();
while (b > -1)
{
writer.WriteByte((Byte)b);
b = reader.ReadByte();
}
reader.Close();
writer.Close();
}
public Image GetSheet(String musicData)
{
return Image.FromStream(this.GetResponseStream(musicData));
}
}
struct MusicSheetThreadData
{
public PictureBox ImageContainer;
public String MusicData;
}
struct MutationGuiData
{
public FretMutation Mutation;
public Color Color;
public Int32 ImageIndex;
}
private MusicSheetDownloader downloader
= new MusicSheetDownloader
();
private FretPiece currentTheme
= new FretPiece
();
private Process gmnProcess;
private StreamReader gmnProcessOutput;
private FretMutationGenerator mutationGenerator;
private MutationGuiData[] defaultMutationsData;
private Fret result;
private const String tmpGmnFile = "tmp.gmn";
private const String tmpMidFile = "tmp.mid";
private void DownloadAndDisplay(Object threadData)
{
MusicSheetThreadData data = (MusicSheetThreadData)threadData;
try
{
data.ImageContainer.Image = downloader.GetSheet(data.MusicData);
data.ImageContainer.SizeMode = PictureBoxSizeMode.Zoom;
}
catch
{
MessageBox.Show("Impossibile renderizzare il tema proposto. E' possibile che vi siano errori di sintassi nel codice.", "Errore", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void GatherGuiData()
{
currentTheme.
Meter = new Meter
(Convert.
ToInt32(lblMeterNum.
Text), Convert.
ToInt32(lblMeterDen.
Text));
currentTheme.
Tempo.
BeatDuration = new Fraction
(1,
(Int32
)Math.
Pow(2.0,
(Double)cmbUnitBeat.
SelectedIndex));
currentTheme.Tempo.BeatsPerMinute = (Int32)nudBeatsPerMinute.Value;
currentTheme.Key.Accidentals = (SByte)(dudKey.SelectedIndex - 6);
currentTheme.Key.IsMajor = !chbMinor.Checked;
}
private Bitmap GetMutationsChart()
{
Bitmap result
= new Bitmap
(200, 200
);
Graphics g = Graphics.FromImage(result);
Double totalWeight = defaultMutationsData.Sum(data => data.Mutation.Weight);
Rectangle bounds
= new Rectangle
(5, 5, 190, 190
);
Single angle = 0.0f;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
foreach (MutationGuiData data in defaultMutationsData)
{
Single span = (Single)(360 * data.Mutation.Weight / totalWeight);
g.
FillPie(new SolidBrush
(data.
Color), bounds, angle, span
);
g.DrawPie(Pens.Black, bounds, angle, span);
angle += span;
}
g.Flush();
return result;
}
private Boolean RunDefaultConversionProcess()
{
gmnProcess.Start();
gmnProcessOutput = gmnProcess.StandardOutput;
gmnProcess.WaitForExit();
gmnProcess.Close();
String line;
while ((line = gmnProcessOutput.ReadLine()) != null)
if (line.Contains("ERROR"))
{
MessageBox.Show("Il programma di conversione ha rilevato un errore:\n\n" + line + "\n\nImpossibile terminare il salvataggio. Ricontrollare la sintassi.",
"Errore di conversione", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
return File.Exists(tmpMidFile);
}
private void Form1_Load(object sender, EventArgs e)
{
if (!File.Exists("gmn2midi.exe"))
{
MessageBox.Show("Impossibile avviare all'applicazione. Il programma di encoding (gmn2midi.exe) non è stato trovato nella cartella attuale.", "Impossibile iniziare",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
dudKey.SelectedIndex = 6;
imgKeyPreview.Image = imgKeys.Images[6];
cmbUnitBeat.SelectedIndex = 2;
gmnProcess
= new Process
();
gmnProcess.StartInfo.UseShellExecute = false;
gmnProcess.StartInfo.RedirectStandardOutput = true;
gmnProcess.StartInfo.CreateNoWindow = true;
gmnProcess.StartInfo.FileName = "gmn2midi.exe";
gmnProcess.StartInfo.Arguments = tmpGmnFile;
mutationGenerator
= new FretMutationGenerator
();
FretMutation[] tempMutations =
new FretMutation
[] {new NoteVariation
(),
new ChordAddition
(),
new OctaveTransposition
(),
new NoteSplitting
(),
new HarmonicSymmetry
(),
new VerticalTranslation
(),
new RelativeTransposition
(),
new RagtimeTransformation
()};
Color[] tempColors =
new Color
[] { Color.
Black, Color.
DodgerBlue, Color.
ForestGreen, Color.
Orange,
Color.Magenta, Color.SeaGreen, Color.Red, Color.Aquamarine };
defaultMutationsData
= new MutationGuiData
[tempMutations.
Length];
for (Int32 i = 0; i < tempMutations.Length; i++)
{
ListViewItem item
= new ListViewItem
();
item.ImageIndex = i;
defaultMutationsData[i].ImageIndex = i;
defaultMutationsData[i].Mutation = tempMutations[i];
defaultMutationsData[i].Color = tempColors[i];
item.Text = tempMutations[i].GetType().Name;
item.Tag = tempMutations[i];
item.ForeColor = tempColors[i];
lstMutations.Items.Add(item);
}
AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
}
private void button1_Click(object sender, EventArgs e)
{
Thread background
= new Thread
(DownloadAndDisplay
);
String completeData;
this.GatherGuiData();
completeData = "{[" + String.Format("{0} {1} {2} {3}", currentTheme.Meter.ToGuidoNotation(),
currentTheme.Key.ToGuidoNotation(), currentTheme.Tempo.ToGuidoNotation(), txtOriginalTheme.Text) + "]}";
background.
Start(new MusicSheetThreadData
() { ImageContainer
= imgSheetPreview, MusicData
= completeData
});
imgSheetPreview.Image = imgSheetPreview.ErrorImage;
imgKeyPreview.SizeMode = PictureBoxSizeMode.CenterImage;
}
private void cmbUnitBeat_DrawItem(object sender, DrawItemEventArgs e)
{
Rectangle bounds = e.Bounds;
Brush brush = Brushes.Black;
if ((e.State & (DrawItemState.Focus)) != 0)
{
e.Graphics.FillRectangle(Brushes.DodgerBlue, bounds);
brush = Brushes.White;
}
else
e.Graphics.FillRectangle(Brushes.White, bounds);
if (e.Index > -1)
{
e.Graphics.DrawImage(imgNotes.Images[e.Index], bounds.X + 5, bounds.Y + 1);
e.Graphics.DrawString(cmbUnitBeat.Items[e.Index].ToString(), e.Font, Brushes.Black, bounds.X + 35.0f, bounds.Y + 13.0f);
}
}
private void trkMeterNum_Scroll(object sender, EventArgs e)
{
lblMeterNum.Text = trkMeterNum.Value.ToString();
}
private void trkMeterDen_Scroll(object sender, EventArgs e)
{
lblMeterDen.Text = Math.Pow(2.0, (Double)trkMeterDen.Value).ToString("N0");
trkMeterNum.Maximum = (Int32)Math.Pow(2.0, (Double)trkMeterDen.Value);
lblMeterNum.Text = trkMeterNum.Value.ToString();
}
private void dudKey_SelectedItemChanged(object sender, EventArgs e)
{
imgKeyPreview.Image = imgKeys.Images[dudKey.SelectedIndex];
}
private void btnConvert2Midi_Click(object sender, EventArgs e)
{
if (fSave.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
GatherGuiData();
File.WriteAllText(tmpGmnFile, "{[" + String.Format("{0} {1} {2} {3}", currentTheme.Meter.ToGuidoNotation(),
currentTheme.Key.ToGuidoNotation(), currentTheme.Tempo.ToGuidoNotation(), txtOriginalTheme.Text) + "]}");
if (RunDefaultConversionProcess())
{
if (File.Exists(fSave.FileName))
File.Delete(fSave.FileName);
File.Move(tmpMidFile, fSave.FileName);
}
}
}
private void lstMutations_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstMutations.SelectedIndices.Count < 1)
return;
pgMutationProperties.SelectedObject = lstMutations.SelectedItems[0].Tag;
}
private void lstMutations_ItemChecked(object sender, ItemCheckedEventArgs e)
{
(e.
Item.
Tag as FretMutation
).
Weight = (e.
Item.
Checked ? 1.0
: 0.0
);
imgMutationsChart.Image = GetMutationsChart();
}
private void pgMutationProperties_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
if (e.ChangedItem.Label == "Weight")
imgMutationsChart.Image = GetMutationsChart();
}
private void btnGo_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(txtOriginalTheme.Text))
{
MessageBox.Show("Nessuna melodia presente come tema principale!", "Nessuna melodia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
lblGeneratorStatus.Text = "Fine";
return;
}
lblGeneratorStatus.Text = "Controllo mutazioni";
mutationGenerator.Mutations.Clear();
foreach (ListViewItem item in lstMutations.Items)
mutationGenerator.Mutations.Add(item.Tag as FretMutation);
if (mutationGenerator.Mutations.Count == 0)
{
MessageBox.Show("Nessuna mutazione selezionata!", "Nessuna mutazione", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
lblGeneratorStatus.Text = "Fine";
return;
}
lblGeneratorStatus.Text = "Generazione melodia";
currentTheme.Clear();
try
{
currentTheme.AddFromGuidoString(txtOriginalTheme.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\nSi è verificato un errore nel parsing della melodia principale. Impossibile continuare.", "Errore di parsing",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
GatherGuiData();
if (fSave.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
lblGeneratorStatus.Text = "Applicazione mutazioni...";
bgMutate.RunWorkerAsync(fSave.FileName);
}
}
private void bgMutate_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
String savePath = e.Argument as String;
try
{
result = mutationGenerator.ApplyIncrementalMutations(currentTheme, (Int32)nudIterations.Value);
else
result = mutationGenerator.ApplyMutations(currentTheme, (Int32)nudIterations.Value);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
result.SaveGuidoNotationFile(tmpGmnFile);
if (RunDefaultConversionProcess())
{
if (File.Exists(savePath))
File.Delete(savePath);
File.Move(tmpMidFile, savePath);
{
String sheetPath = Path.GetDirectoryName(savePath) + "\\" + Path.GetFileNameWithoutExtension(savePath) + ".gif";
downloader.DownloadSheet(File.ReadAllText(tmpGmnFile), sheetPath);
}
}
else
MessageBox.Show("Si è verificato un errore di natura sconosiuta nell'encoder.", "Errore gmn2midi", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
{
Int32 i = 1;
foreach (FretPiece piece in result)
{
piece.SaveGuidoNotationFile(tmpGmnFile);
if (RunDefaultConversionProcess())
{
String path = Path.GetDirectoryName(savePath) + "\\" + Path.GetFileNameWithoutExtension(savePath) + (i++).ToString() + ".mid";
if (File.Exists(path))
File.Delete(path);
File.Move(tmpMidFile, path);
}
bgMutate.ReportProgress((Int32)(100 * (Double)i / result.Count));
}
}
}
private void bgMutate_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
lblGeneratorStatus.Text = "Salvataggio singole tracce " + e.ProgressPercentage.ToString() + "%";
}
private void bgMutate_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
lblGeneratorStatus.Text = "Fine";
}
private void imgSheetPreview_Click(object sender, EventArgs e)
{
Form preview
= new Form
();
preview.BackgroundImage = imgSheetPreview.Image;
preview.BackgroundImageLayout = ImageLayout.Zoom;
preview.Show();
}
private void strSaveSheetPreviewAs_Click(object sender, EventArgs e)
{
if (saveSheetDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
imgSheetPreview.Image.Save(saveSheetDialog.FileName);
}
private void chbIncremental_CheckedChanged(object sender, EventArgs e)
{
}
private void chbSingleMutation_CheckedChanged(object sender, EventArgs e)
{
}
private void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.
ExceptionObject.
GetType().
IsSubclassOf(typeof(Exception
)))
{
Exception ex = e.ExceptionObject as Exception;
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);
}
else
MessageBox.Show("Si è verificata un'eccezione di natura sconosciuta.", "WTF???", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}