using System.Reflection; using System.Security.Cryptography; using System.Windows.Documents; using System.Windows.Media.Imaging; namespace QuikDawEditor.EDITING; public class MiscMethods { public void RelRes() { ReleaseResources(); } public static string errMess; static bool oneMess = false; public static void ReleaseResources() { if (!oneMess) { oneMess = true; try { MessageBox.Show("Error occurred: Releasing resources"); } catch { } } projPlayer?.AudioPlayerStop(); projPlayer?.Dispose(); } public static void ShowProcessingMessage(string message) { ((EditorWindow)Application.Current.MainWindow).ShowProcessingMessage(message); } public static void HideProcessingMessage() { ((EditorWindow)Application.Current.MainWindow).HideProcessingMessage(); } //public static double editingProject.ViewXZoomFac = 1; public static int GetNearestSnapMs(double val, decimal snapto) { if (snapto == 2) return (int)val; double snapMs = GetSnapMsVal(snapto); return (int)(Math.Round(val / snapMs) * snapMs); } public static double GetMinimumSnapMs(decimal snapto) { return snapto == 2 ? 1000 : GetSnapMsVal(snapto); } public static double GetNearestSnapPix(double pixval) { return MsecToPixels(GetNearestSnapMs(PixelsToMsec(pixval), editingProject.CurrentSnapTo)); } public static double GetSnapMsVal(decimal snapto) { return snapto == 2 ? 1000 : (double)(4M * snapto * (decimal)MillisecondsPerBeat); } public static string GetBeatMeasureString(double timeCodeMs) { int totalBeats = (int)Math.Truncate(timeCodeMs / 1000 * BeatsPerMinute / 60); int MeasureCount = totalBeats / editingProject.BeatsPerMeasure + 1; int leftOverBeats = totalBeats % editingProject.BeatsPerMeasure + 1; return MeasureCount.ToString().PadLeft(2, '0') + ":" + leftOverBeats.ToString().PadLeft(2, '0'); } public static Track GetTrackFromID(string undoID) { return editingProject.GetAllTracksInProject.FirstOrDefault(t => t.UndoTrackID == undoID); } public static Clip GetClipFromID(string undoID) { return editingProject.GetAllClips.FirstOrDefault(c => c.UndoClipID == undoID); } public static event EventHandler CurrentPodRefChanged; protected static void OnCurrentPodRefChanged(EventArgs e) { EventHandler handler = CurrentPodRefChanged; if (handler != null) { handler(null, e); } } public static int SelectedAudioOutputIndex = -1; public static double TranslateMsToCurrentBPM(double msval) { return Math.Round(MillisecondsPerBeat / 1000D * msval); } public static double TranslateMsTo60BPM(double msval) { return Math.Round(1000D / MillisecondsPerBeat * msval); } //public static double TranslateMsToCurrentBPM(double msval) { return MillisecondsPerBeat / 1000 * msval; } //public static double TranslateMsTo60BPM(double msval) { return 1000D / MillisecondsPerBeat * msval; } internal static double MillisecondsPerBeat { get { return 60D / BeatsPerMinute * 1000D; } } public static float CalculateValBetweenAutoPoints(double Timems, AutomationLane autoLane) { AutoPoint gp1 = autoLane.autoPoints.LastOrDefault(gp => gp.sourcePointms < Timems); if (gp1 == null) gp1 = autoLane.autoPoints.First(); AutoPoint gp2 = autoLane.autoPoints.FirstOrDefault(gp => gp.sourcePointms > Timems); if (gp2 == null) gp2 = autoLane.autoPoints.Last(); double percBetween = (Timems - gp1.sourcePointms) / (gp2.sourcePointms - gp1.sourcePointms); return (float)(gp1.AutoValue + (gp2.AutoValue - gp1.AutoValue) * (float)percBetween); } public static float GetGainValBetweenGainPoints(double Timems, GainPoint gp1, GainPoint gp2) { double percBetween = (Timems - gp1.sourcePointms) / (gp2.sourcePointms - gp1.sourcePointms); return (float)(gp1.GainValue + (gp2.GainValue - gp1.GainValue) * (float)percBetween); } public static string GetJsonForTrack(Track thisTrack) { return JsonSerializer.Serialize(thisTrack, typeof(Track), standardJSO); } public static string GetJsonForClip(Clip thisClip) { return JsonSerializer.Serialize(thisClip, typeof(Clip), standardJSO); } public static Track CreateTrackFromJson(string trackJson) { Track makeTrack = (Track)JsonSerializer.Deserialize(trackJson, typeof(Track)); makeTrack.AddHandlers(); makeTrack.myTrackSampleProvider.myTrack = makeTrack; makeTrack.InitializeTrackAudio(); return makeTrack; } //public static Clip CreateClipFromJson(string clipJson) //{ // Clip makeClip = (Clip)JsonSerializer.Deserialize(clipJson, typeof(Clip)); // //c.myTrack = dupeTrack; // if (makeClip.IsAudioClip) // { //Create clipsampleproviders for track clips // dupeTrack.AddClipSampleProviderToClip(makeClip); // makeClip.GetWaveformFromImage(); // } // makeClip.ReverseTransformFactorX = 1 / editingProject.ViewXZoomFac; // makeClip.AddHandlers(); // return makeClip; //} public static string GetUniquePngWaveformDirGuidFromAudioFile(string audioFileName) { FileInfo fi = new FileInfo(EditingProjectClipsDirectory + "\\" + audioFileName); string filePathCreationComposite = String.Format("{0}{1}", fi.Name, fi.Length); using (MD5 md5 = MD5.Create()) { byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(filePathCreationCo‌​mposite)); Guid result = new Guid(hash); return result.ToString(); } } public static PropertyInfo dpiXProperty = typeof(SystemParameters).GetProperty("DpiX", BindingFlags.NonPublic | BindingFlags.Static); public static PropertyInfo dpiYProperty = typeof(SystemParameters).GetProperty("Dpi", BindingFlags.NonPublic | BindingFlags.Static); public static int dpiX = (int)dpiXProperty.GetValue(null, null); public static int dpiY = (int)dpiYProperty.GetValue(null, null); public readonly static double dpiXFac = dpiX / 96D; public readonly static double dpiYFac = dpiY / 96D; public static BitmapSource GetControlAsBitmapSource(FrameworkElement element) { RenderOptions.SetBitmapScalingMode(element, BitmapScalingMode.HighQuality); RenderOptions.SetEdgeMode(element, EdgeMode.Aliased); RenderTargetBitmap bmp = new RenderTargetBitmap((int)(element.ActualWidth * dpiXFac), (int)(element.ActualHeight * dpiYFac), dpiX, dpiY, PixelFormats.Pbgra32); bmp.Render(element); return bmp; } public static BitmapSource GetScreenAsBitmapSource(int x, int y, int width, int height) { int pixelX = (int)Math.Round(x * dpiXFac); int pixelY = (int)Math.Round(y * dpiXFac); int pixelWidth = (int)Math.Round(width * dpiXFac); int pixelHeight = (int)Math.Round(height * dpiXFac); using (var screenBmp = new System.Drawing.Bitmap(pixelWidth, pixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb)) { using (var bmpGraphics = System.Drawing.Graphics.FromImage(screenBmp)) { bmpGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; bmpGraphics.Clear(System.Drawing.Color.Transparent); bmpGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; bmpGraphics.CopyFromScreen(pixelX, pixelY, 0, 0, new System.Drawing.Size(pixelWidth, pixelHeight)); return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(screenBmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } } } public static string GetAppVersion() { return Assembly.GetEntryAssembly().GetCustomAttribute().InformationalVersion; } public static double MaxClipRightMs(Clip thisClip) { return thisClip.GetIndexInTrack == thisClip.myTrack.Clips.Count - 1 ? double.MaxValue : thisClip.myTrack.Clips[thisClip.GetIndexInTrack + 1].ClipLeftMs; } public static double MinClipLeftMs(Clip thisClip) { return thisClip.GetIndexInTrack == 0 ? 0 : thisClip.myTrack.Clips[thisClip.GetIndexInTrack - 1].ClipRightMs; } public static void ChangeClipVirtualStart(Clip mainClip, double newClipVirtualStartMs) { mainClip.ClipVirtualStartMs = newClipVirtualStartMs; if (mainClip.IsCurrentClip) mainClip.ResetMe(projPlayer.CurrentPlayingPosMS); } public static void ChangeClipVirtualStarts(IEnumerable selectedClips, double moveDiff) { try { if (selectedClips.Count() > 0) { foreach (Clip movClip in selectedClips) { movClip.ClipVirtualStartMs += moveDiff; if (movClip.IsCurrentClip) movClip.ResetMe(projPlayer.CurrentPlayingPosMS); } } } catch (Exception ex) { Debug.WriteLine("Error changing clip virtual starts\nselectedclispCount=" + selectedClips.Count().ToString() + "::movediff=" + moveDiff.ToString()); } } //public static BitmapCacheBrush DrawClipGeometryBrush(Rect rect, Pen pen, Brush fillBrush, Geometry geometry) //{ // rect.Offset(0, 0); //offset if necessary (trying to push image forward) // var visual = new DrawingVisual(); // using (var dc = visual.RenderOpen()) { dc.DrawGeometry(fillBrush, pen, geometry); } // BitmapCacheBrush bcb = new BitmapCacheBrush(visual); // return bcb; //} public static BitmapSource DrawMidiClipGeometry(Rect rect, Pen pen, Brush fillBrush, Geometry geometry) { rect.Offset(0, 0); //offset if necessary (trying to push image forward) int width = (int)(rect.Width * dpiX / 96D); int height = (int)(rect.Height * dpiY / 96D); RenderTargetBitmap bmp = null; try { bmp = new RenderTargetBitmap(width, height, dpiX, dpiY, PixelFormats.Pbgra32); //rectwidth + 1 because of added 0 at end var visual = new DrawingVisual(); using (var dc = visual.RenderOpen()) { dc.DrawGeometry(fillBrush, pen, geometry); } RenderOptions.SetBitmapScalingMode(visual, BitmapScalingMode.HighQuality); //RenderOptions.SetEdgeMode(visual, EdgeMode.Aliased); RenderOptions.SetEdgeMode(visual, EdgeMode.Unspecified); bmp.Render(visual); } catch (Exception ex) { MessageBox.Show("error drawing midi clip geometry:\n" + ex.Message); } return bmp; } public static void SetRangeXaml(ref TextRange trange, string xaml) { var mstream = new MemoryStream(Encoding.UTF8.GetBytes(xaml)); trange.Load(mstream, DataFormats.Xaml); } public static string GetXaml(TextRange trange) { var stream = new MemoryStream(); trange.Save(stream, DataFormats.Xaml, true); return Encoding.UTF8.GetString(stream.ToArray()); } public static string GetMinimalXaml(TextRange trange) { var stream = new MemoryStream(); trange.Save(stream, DataFormats.Xaml, true); string returnXamlString = Encoding.UTF8.GetString(stream.ToArray()); //Eliminate unnecessary boilerplate xaml string regexFind = "(TextDecorations=\"\"|NumberSubstitution.CultureSource=\"User\" NumberSubstitution.Substitution=\"AsCulture\"" + "|Typography\\..*\"(True|False|Normal|0)\"|FontWeight=\"Normal\"|FontStyle=\"Normal\"|FontStretch=\"Normal\")"; returnXamlString = Regex.Replace(returnXamlString, regexFind, ""); return returnXamlString; } }