static IEnumerable <VideoEdit> _GetRaceEdits(this IEnumerable <OverlayData.RaceEvent> raceEvents) { var totalRaceEvents = GetInterestingRaceEvents(raceEvents); var previousEvent = totalRaceEvents.First(); foreach (var re in totalRaceEvents.Skip(1)) { if (re.StartTime - previousEvent.EndTime >= 10d / Settings.AppliedTimingFactor) { TraceDebug.WriteLine("Applying edit between {0}:{1}:{2} and {3}:{4}:{5}", previousEvent.Interest, previousEvent.Position, previousEvent.EndTime, re.Interest, re.Position, re.StartTime); yield return(new VideoEdit { StartTime = previousEvent.EndTime - 1, EndTime = re.StartTime + 1 }); } else { TraceDebug.WriteLine("Not apply edit between {0}:{1}:{2} and {3}:{4}:{5}", previousEvent.Interest, previousEvent.Position, previousEvent.EndTime, re.Interest, re.Position, re.StartTime); } previousEvent = re; } }
public void _AnalyseRace(Action onComplete) { var hwnd = Win32.Messages.FindWindow(null, "iRacing.com Simulator"); Win32.Messages.ShowWindow(hwnd, Win32.Messages.SW_SHOWNORMAL); Win32.Messages.SetForegroundWindow(hwnd); Thread.Sleep(Settings.Default.PeriodWaitForIRacingSwitch); var data = iRacing.GetDataFeed() .WithCorrectedPercentages() .AtSpeed(16) .RaceOnly() .First(d => d.Telemetry.SessionState == SessionState.Racing); raceStartFrameNumber = data.Telemetry.ReplayFrameNum - (60 * 20); if (raceStartFrameNumber < 0) { TraceInfo.WriteLine("Unable to start capturing at 20 seconds prior to race start. Starting at start of replay file."); raceStartFrameNumber = 0; } TraceDebug.WriteLine(data.Telemetry.ToString()); AnalyseIncidents(); //Analyse incidents AnalyseRaceSituations(new iRacingConnection().GetBufferedDataFeed()); //Analyse race situation (all) by playing out replay at 16x speed. onComplete(); }
/// <summary> /// If the supplied function returns true for the period, then iteration stops /// </summary> /// <param name="condition"></param> /// <returns></returns> public IEnumerable <DataSample> Of(Func <DataSample, bool> condition) { bool conditionMet = false; TimeSpan conditionMetAt = new TimeSpan(); foreach (var data in samples) { if (condition(data)) { if (!conditionMet) { TraceDebug.WriteLine("{0}: Condition met".F(data.Telemetry.SessionTimeSpan)); conditionMet = true; conditionMetAt = data.Telemetry.SessionTimeSpan; } } else { if (conditionMet) { TraceDebug.WriteLine("{0}: Condition unmet".F(data.Telemetry.SessionTimeSpan)); } conditionMet = false; } if (conditionMet && conditionMetAt + period < data.Telemetry.SessionTimeSpan) { break; } yield return(data); } }
public void Process(DataSample data, TimeSpan relativeTime) { try { var cameraGroupName = ""; var cameraName = ""; var cameraGroup = data.SessionData.CameraInfo.Groups.FirstOrDefault(g => g.GroupNum == data.Telemetry.CamGroupNumber); if (cameraGroup != null) { cameraGroupName = cameraGroup.GroupName; var camera = cameraGroup.Cameras.FirstOrDefault(c => c.CameraNum == data.Telemetry.CamCameraNumber); if (camera != null) { cameraName = camera.CameraName; } } TraceDebug.WriteLine("{0} Camera: Driver: {1}, GroupNumber: {2}, Number: {3}, State: {4}, GroupName: {5}, Name: {6}", data.Telemetry.SessionTimeSpan, data.Telemetry.CamCar.Details.Driver.UserName, data.Telemetry.CamGroupNumber, data.Telemetry.CamCameraNumber, data.Telemetry.CamCameraState, cameraGroupName, cameraName); } catch (Exception e) { TraceError.WriteLine(e.Message); TraceError.WriteLine(e.StackTrace); } }
/// <summary> /// Stops this instance of Krento and dispose Krento context. /// </summary> internal void Stop() { TraceDebug.Trace("Stop Krento"); if (context != null) { try { if (splashScreen != null) { splashScreen.Dispose(); splashScreen = null; } context.StopServer(); context.UnloadKrentoPlugins(); context.UnloadKrentoToys(); context.UnloadKrentoDocklets(); context.UnloadRingImage(); context.Dispose(); context = null; } catch (Exception ex) { TraceDebug.Trace("Exception in Startup.Stop: " + ex.Message); context = null; } } }
void LogSystemInformation() { var StringBuilder1 = new StringBuilder(string.Empty); try { var config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoamingAndLocal); TraceDebug.WriteLine("Local user config path: {0}", config.FilePath); TraceDebug.WriteLine("Application Version: {0}", AboutBox1.AssemblyVersion); TraceDebug.WriteLine(Environment.Is64BitOperatingSystem ? "OS: 64x" : "OS: 32x"); TraceDebug.WriteLine("ProcessorCount: {0}".F(Environment.ProcessorCount)); foreach (DriveInfo DriveInfo1 in DriveInfo.GetDrives()) { TraceDebug.WriteLine("Drive: {0}, Type: {1}, Format: {2}, Size: {3}, AvailableFreeSpace: {4}".F( GetValue(() => DriveInfo1.Name), GetValue(() => DriveInfo1.DriveType.ToString()), GetValue(() => DriveInfo1.DriveFormat), GetValue(() => DriveInfo1.TotalSize.ToString()), GetValue(() => DriveInfo1.AvailableFreeSpace.ToString()))); } TraceDebug.WriteLine("SystemPageSize: {0}".F(Environment.SystemPageSize)); TraceDebug.WriteLine("Version: {0}".F(Environment.Version)); LogDeviceInformation("Win32_Processor"); LogDeviceInformation("Win32_VideoController"); } catch { } }
static List <DataSample> GetIncidentsForward(IEnumerable <DataSample> samples, int sampleScanSettle, int maxTotalIncidents) { TraceDebug.WriteLine("Scanning for incidents forwards from start"); return(IncidentsSupport.FindIncidents( samples.TakeWhile(data => data.Telemetry.SessionState != SessionState.CoolDown), sampleScanSettle, maxTotalIncidents)); }
public SourceReaderExtra CreateSourceReader(ReadWriteClassFactory readWriteFactory, Attributes attributes) { TraceDebug.WriteLine("Attempting to open file {0}".F(this.FileName)); var reader = readWriteFactory.CreateSourceReaderFromURL(this.FileName, attributes); TraceDebug.WriteLine("Opened file {0}. Duration: {1}".F(this.FileName, reader.Duration.FromNanoToSeconds())); return(new SourceReaderExtra(this.FileName, this.State, reader)); }
private void Default_SettingChanging(object sender, System.Configuration.SettingChangingEventArgs e) { try { TraceDebug.WriteLine("Setting Changed: key: {0}, name: {1}, value: {2}".F(e.SettingKey, e.SettingName, e.NewValue)); } catch (Exception ex) { TraceDebug.WriteLine("Unable to log setting change"); TraceDebug.WriteLine(ex.Message); } }
void LogDeviceInformation(string stringIn) { var mc = new ManagementClass(stringIn); var instances = mc.GetInstances(); var properties = mc.Properties; foreach (var instance in instances) { foreach (var property in properties) { TraceDebug.WriteLine("{0}: {1}".F(property.Name, GetValue(() => instance.Properties[property.Name].Value.ToString()))); } } }
internal void UnloadAll() { try { SaveAll(); } catch (Exception ex) { //do not raise an exception here because Krento wants to shutdown TraceDebug.Trace(ex); } UnloadMouseHook(); UnloadKeyboardHook(); context.FreeAllResources(); }
private static void CopyFromOldSettings(Settings settings) { var pp = settings.Providers.OfType <IracingReplayDirectorProvider>().First(); var currentValues = new Dictionary <string, object>(); foreach (SettingsProperty p in settings.Properties) { currentValues[p.Name] = settings[p.Name]; TraceDebug.WriteLine("Capturing settings -- {0}: {1}", p.Name, currentValues[p.Name]); p.Provider = pp; } settings.Reload(); foreach (var kv in currentValues) { settings[kv.Key] = kv.Value; } settings.NewSettings = true; settings.Save(); }
MediaType CreateTargetAudioMediaType(MediaType nativeMediaType) { var numberOfChannels = nativeMediaType.AudioNumberOfChannels; var sampleRate = nativeMediaType.AudioSamplesPerSecond; var availableTypes = MFSystem.TranscodeGetAudioOutputAvailableTypes(TARGET_AUDIO_FORMAT, MFT_EnumFlag.All); TraceDebug.WriteLine("Searching for audio transcoding for sampleRate of {0}khz and {1} channels".F(sampleRate / 1000, numberOfChannels)); var type = availableTypes .OrderByDescending(t => t.AudioAverageBytesPerSecond) .ThenByDescending(t => t.AudioNumberOfChannels) .FirstOrDefault(t => t.AudioSamplesPerSecond == sampleRate && t.AudioNumberOfChannels == numberOfChannels); if (type == null) { TraceDebug.WriteLine("No audio transcoder found. Searching for transcoding with 2 or fewer channels at any sample rate"); type = availableTypes .OrderByDescending(t => t.AudioAverageBytesPerSecond) .ThenByDescending(t => t.AudioNumberOfChannels) .FirstOrDefault(t => t.AudioNumberOfChannels <= 2); } if (type == null) { TraceDebug.WriteLine("No audio transcoder found. Search for first compatible transcoder"); type = availableTypes .OrderByDescending(t => t.AudioAverageBytesPerSecond) .ThenByDescending(t => t.AudioNumberOfChannels) .FirstOrDefault(); } if (type != null) { TraceDebug.WriteLine("Found audio track. SampleRate: {0}, Channels: {1}, BitRate: {2}kbs".F(type.AudioSamplesPerSecond / 1000, type.AudioNumberOfChannels, type.AudioAverageBytesPerSecond * 8 / 1000)); return(new MediaType(type)); } throw new Exception("Unable to find target audio format"); }
/// <summary> /// Stops this instance of Krento and dispose Krento context. /// </summary> internal void Stop() { TraceDebug.Trace("Stop Krento"); if (context != null) { try { context.StopServer(); context.UnloadKrentoPlugins(); context.UnloadKrentoToys(); context.UnloadKrentoDocklets(); context.UnloadRingImage(); context.Dispose(); context = null; } catch (Exception ex) { TraceDebug.Trace("Exception in Startup.Stop: " + ex.Message); context = null; } } CentralPoint.Shutdown(); }
//worker thread to switch cameras. private void CameraSwitcherWorkerTask() { for (var iCamDriverIndex = 0; iCamDriverIndex < overlayData.CamDrivers.Count; iCamDriverIndex++) { //get object of current CamDriver var curCamDriver = overlayData.CamDrivers[iCamDriverIndex]; //Set camera to current camDriver Object ReplayControl.cameraControl.CameraOnDriver(short.Parse(curCamDriver.CurrentDriver.CarNumber), (short)curCamDriver.camGroupNumber); //remember start-time of current camers double startTimeCurCamera = curCamDriver.StartTime; try { double startTimeNextCamera = overlayData.CamDrivers[iCamDriverIndex + 1].StartTime; int camDuration = (int)(1000 * (startTimeNextCamera - startTimeCurCamera)); TraceDebug.WriteLine("Camera switched to driver {0} using camera-group {1}. Remaining Time: {2}".F(curCamDriver.CurrentDriver.UserName, curCamDriver.camGroupNumber, camDuration)); Thread.Sleep(camDuration); } catch { TraceDebug.Write("No more entries in list of CamDriver -> no more camera switches"); } } }
private void Load() { try { iniFile = new MemIniFile(FileName); try { iniFile.Load(); LoadIniFileData(); } finally { iniFile.Dispose(); iniFile = null; } LoadLogo(logoFile); } catch (Exception ex) { TraceDebug.Trace(ex); } }
static bool IsAPerferredDriver(GapMetric d) { TraceDebug.WriteLine("IsAPreferred Driver called for carIdx {0} Preferred: {1}, Leader: {2} : return: {3}", d.CarIdx, preferredCarIdxs.Contains(d.CarIdx), preferredCarIdxs.Contains(d.LeaderCarIdx), preferredCarIdxs.Contains(d.CarIdx) || preferredCarIdxs.Contains(d.LeaderCarIdx)); return(preferredCarIdxs.Contains(d.CarIdx)); /* || preferredCarIdxs.Contains(d.LeaderCarIdx);*/ }
//Analyse race situations at maximum replay speed w/o recording. void AnalyseRaceSituations(IEnumerable <DataSample> samples) { int iReplaySpeedForAnalysis = (int)replaySpeeds.FF16x; //set speed for analysis phase to FF16x //Start iRacing Replay from the beginning with maximum speed (16x) iRacing.Replay.MoveToFrame(raceStartFrameNumber); //---------------------------- // copied from iRacing.Capturing because race events in app V1.0.x.x are identified during capturing the whole video. // necessity of classes in analysis phase to be reviewed //---------------------------- //var overlayData = new OverlayData(); removalEdits = new RemovalEdits(overlayData.RaceEvents); commentaryMessages = new CommentaryMessages(overlayData); recordPitStop = new RecordPitStop(commentaryMessages); fastestLaps = new RecordFastestLaps(overlayData); replayControl = new ReplayControl(samples.First().SessionData, incidents, removalEdits, TrackCameras); sessionDataCapture = new SessionDataCapture(overlayData); //CAPTURING LEADERBOARD, CAMERAS will be done at FF16x. TO BE DETERMINED WHETHER STANDARD INTERVALS HAVE TO BE REDUCED BY FACTOR OF 16?! captureLeaderBoardEveryHalfSecond = new SampleFilter(TimeSpan.FromSeconds(0.5), new CaptureLeaderBoard(overlayData, commentaryMessages, removalEdits).Process); captureCamDriverEveryQuaterSecond = new SampleFilter(TimeSpan.FromSeconds(0.25), new CaptureCamDriver(overlayData).Process); captureCamDriverEvery4Seconds = new SampleFilter(TimeSpan.FromSeconds(4), new LogCamDriver().Process); //---------------------------- //end copy / end review //---------------------------- ApplyFirstLapCameraDirection(samples, replayControl); samples = samples .VerifyReplayFrames() .WithCorrectedPercentages() .WithCorrectedDistances() .WithFastestLaps() .WithFinishingStatus() .WithPitStopCounts() .TakeUntil(3.Seconds()).Of(d => d.Telemetry.LeaderHasFinished && d.Telemetry.RaceCars.All(c => c.HasSeenCheckeredFlag || c.HasRetired || c.TrackSurface != TrackLocation.OnTrack)) .TakeUntil(3.Seconds()).AfterReplayPaused(); samples = samples.AtSpeed(iReplaySpeedForAnalysis); overlayData.CapturedVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); ulong numberOfDataProcessed = 0; var startTime = DateTime.Now; foreach (var data in samples) { var relativeTime = (DateTime.Now - startTime).Multiply(iReplaySpeedForAnalysis); //calculate relative time in Replay taking into account replay speed (FF) replayControl.Process(data); sessionDataCapture.Process(data); captureLeaderBoardEveryHalfSecond.Process(data, relativeTime); captureCamDriverEveryQuaterSecond.Process(data, relativeTime); recordPitStop.Process(data, relativeTime); fastestLaps.Process(data, relativeTime); removalEdits.Process(data, relativeTime); captureCamDriverEvery4Seconds.Process(data, relativeTime); numberOfDataProcessed += 1; } removalEdits.Stop(); TraceDebug.WriteLine("Race analysis phase completed. {0} data samples processed with replay speed {1}".F(numberOfDataProcessed, iReplaySpeedForAnalysis)); //save OverlayData into target folder for video ("working folder") SaveReplayScript(overlayData); TraceDebug.WriteLine("Replay Script saved to disk"); iRacing.Replay.SetSpeed(0); }
void ReplaySearch(ReplaySearchMode mode) { TraceDebug.WriteLine("Replay Search {0}", mode.ToString()); SendMessage(BroadcastMessage.ReplaySearch, (short)mode); }
internal static void UnhandledException(Exception ex) { if (!busyException) { try { busyException = true; #if !DEBUG try { #endif InteropHelper.OutputDebugString(ex.Message); BroadcastShutdownMessage(); string message = string.Empty; ErrorHandleDialog ehd = new ErrorHandleDialog(); try { if (ex is HookException) { ehd.ErrorText.Text = SR.KrentoHookMissing; } else { while (ex.InnerException != null) { message = message + ex.Message + Environment.NewLine; ex = ex.InnerException; } message = message + ex.Message + Environment.NewLine; StackTrace st = new StackTrace(ex); message = message + "Call stack:"; ehd.ErrorText.Text = message + Environment.NewLine + st.ToString(); InteropHelper.OutputDebugString(ehd.ErrorText.Text); } DialogResult ok = DialogResult.Cancel; ThreadWindows threadWindows; threadWindows = DisableTaskWindows(); try { ok = ehd.ShowDialog(MainForm); } finally { EnableTaskWindows(threadWindows); } if (ok == DialogResult.OK) { #if DEBUG if (Debugger.IsAttached) { throw ex; } else { Killer.KillSelf(); } #else Killer.KillSelf(); #endif } else { #if DEBUG if (Debugger.IsAttached) { throw ex; } else { Killer.KillSelf(); } #else Application.Restart(); Killer.KillSelf(); #endif } } finally { ehd.Dispose(); } #if !DEBUG } catch { //Exception happens in exception handler //Can't do anything now TraceDebug.Trace(ex.Message); MessageBox.Show(ex.ToString()); Killer.KillSelf(); } } #endif }
/// <summary> /// Assumes the game is in paused mode /// Filters the samples to just single frame numbers, that the game moves after invoking the moveReplay action (eg: which sends message to the game - MoveToNextIncident) /// If the game does not advance to another frame within about 1second, it will stop enumerating /// </summary> /// <param name="samples"></param> /// <param name="moveReplay"></param> /// <param name="sampleScanSettle">The number of samples to take, which must all have the same frame number - to identify that iRacing has paused.</param> /// <returns></returns> static IEnumerable <DataSample> PositionsOf(this IEnumerable <DataSample> samples, int sampleScanSettle) { var lastSamples = new List <int>(); var lastFrameNumber = -2; Func <DataSample, states> waitForMessage = ignored => states.RequestPaceCar; foreach (var dx in samples) { switch (waitForMessage(dx)) { case states.Continue: break; case states.RequestPaceCar: iRacing.Replay.NoWait.CameraOnDriver(0, 0); waitForMessage = d => d.Telemetry.CamCarIdx == 0 ? states.RequestNextIncident : states.Continue; break; case states.RequestNextIncident: iRacing.Replay.NoWait.MoveToNextIncident(); waitForMessage = d => { lastSamples.Add(d.Telemetry.ReplayFrameNum); if (lastSamples.Count == sampleScanSettle) { lastSamples.RemoveAt(0); } if (lastSamples.Count == (sampleScanSettle - 1) && lastSamples.All(f => f == d.Telemetry.ReplayFrameNum)) { if (d.Telemetry.ReplayFrameNum == lastFrameNumber) { TraceDebug.WriteLine("Incidents: Frame number did not change - asuming no more incidents. Current Frame: {0}", d.Telemetry.ReplayFrameNum); return(states.Break); } if (d.Telemetry.CamCarIdx == 0) //Pace Car { TraceWarning.WriteLine("Incident scan aborted - iRacing has not progressed to incident. Frame Number: {0}", d.Telemetry.ReplayFrameNum); return(states.Break); } lastFrameNumber = d.Telemetry.ReplayFrameNum; TraceDebug.WriteLine("Incidents: last {0} samples have settled on frame number {1}", sampleScanSettle, d.Telemetry.ReplayFrameNum); lastSamples.Add(-1); lastSamples.RemoveAt(0); return(states.Yield); } ; return(states.Continue); }; break; case states.Yield: yield return(dx); waitForMessage = ignored => states.RequestPaceCar; break; case states.Break: yield break; } } }
private static void HandleDomainException(object sender, UnhandledExceptionEventArgs e) { TraceDebug.Trace("DEBUG: Current Domain unhandled exception"); UnhandledException((Exception)e.ExceptionObject); }
private static void HandleApplicationException(object sender, ThreadExceptionEventArgs e) { TraceDebug.Trace("DEBUG: Application thread exception"); UnhandledException(e.Exception); }
public void ActivateEngine() { TraceDebug.Trace("Activate Engine"); bool doCheck = GlobalSettings.CheckUpdate; bool disableCheck = false; Visible = false; NativeMethods.ShowWindow(this.Handle, 0); NativeMethods.RemoveSystemMenu(this.Handle); #region First Instance Execution if (context.FirstInstance) { if (!string.IsNullOrEmpty(GlobalSettings.IconName)) { Icon customIcon = null; if (FileOperations.FileExists(GlobalSettings.IconName)) { Icon loadIcon = new Icon(FileOperations.StripFileName(GlobalSettings.IconName)); try { customIcon = (Icon)loadIcon.Clone(); } finally { loadIcon.Dispose(); loadIcon = null; } notifyIcon.Icon = customIcon; //this.Icon = customIcon; } } if (splashScreen != null) { splashScreen.Show(); } if (!string.IsNullOrEmpty(GlobalSettings.GlyphName)) { if (FileOperations.FileExists(GlobalSettings.GlyphName)) { Bitmap tmp = FastBitmap.FromFile(GlobalSettings.GlyphName); notifier.Glyph = BitmapPainter.ResizeBitmap(tmp, notifier.GlyphSize, notifier.GlyphSize, true); } } if (notifier.Glyph == null) { notifier.Glyph = NativeThemeManager.Load("BigKrento.png"); } context.Manager.SetHookMessage(context); ReloadAll(); PreparePulsar(); context.Manager.Rotate(0); if (!GlobalSettings.ShowManagerButtons) { context.Manager.DrawText(SR.KrentoWelcome); } context.Manager.Update(); context.Manager.Visible = false; notifyIcon.Visible = GlobalSettings.ShowTrayIcon; if (splashScreen != null) { if (KrentoContext.FirstRun) { splashScreen.Hide(); NativeMethods.PostMessage(InteropHelper.MainWindow, NativeMethods.CM_SPLASHCLOSE, IntPtr.Zero, IntPtr.Zero); } else { splashScreen.Close(200); } } systemReady = true; string keyMessage = HotKeyMessage; notifier.Caption = SR.KrentoWelcome; if (GlobalSettings.MouseHook == MouseHookButton.None) { notifier.Text = SR.WelcomeMessage(keyMessage, "", ""); } else { string mouseText = ""; switch (GlobalSettings.MouseHook) { case MouseHookButton.Wheel: mouseText = MouseKeyMessage + SR.MouseWheelButton; break; case MouseHookButton.XButton1: mouseText = MouseKeyMessage + SR.MouseXButton1; break; case MouseHookButton.XButton2: mouseText = MouseKeyMessage + SR.MouseXButton2; break; default: mouseText = ""; break; } notifier.Text = SR.WelcomeMessage(keyMessage, SR.OrClick, mouseText); } //Only show popup window when asked if (GlobalSettings.ShowPopupAlerts) { if (GlobalConfig.LowMemory) { notifyIcon.BalloonTipTitle = notifier.Caption; notifyIcon.BalloonTipText = notifier.Text; notifyIcon.BalloonTipIcon = ToolTipIcon.Info; notifyIcon.ShowBalloonTip(5000); } else { notifier.Show(); } } Manager.ClearUnusedMemory(); #region manage autoupdate DateTime lastCheck = Settings.Default.LastCheck; TimeSpan ts = DateTime.Now - lastCheck; if (ts.Days >= 7) { Settings.Default.LastCheck = DateTime.Now; Settings.Default.Save(); if (Settings.Default.AskForCheck) { UpdateDialog upd = new UpdateDialog(); try { upd.ShowDialog(); doCheck = (upd.DialogResult == DialogResult.OK); disableCheck = (upd.btnDisable.Checked); if (disableCheck) { GlobalSettings.CheckUpdate = doCheck; Settings.Default.AskForCheck = false; Settings.Default.Save(); } } finally { upd.Dispose(); } } if ((GlobalSettings.CheckUpdate) && (doCheck)) { checker.CheckNewVersion(); } } #endregion if (GlobalSettings.StartVisible || KrentoContext.FirstRun) { InteropHelper.ShowDesktop(); if (!Manager.Visible) { if (KrentoContext.FirstRun) { Manager.ShowAndExecute(Manager.SimulateWheelRotation); } else { ChangeVisibility(); } } } } #endregion else { systemReady = false; context.FirstInstance = false; } }
internal void Start() { string ApplicationPrefix = GlobalConfig.ProductName.ToUpperInvariant(); TraceDebug.Trace("Start {0}", GlobalConfig.ProductName); #if PORTABLE Environment.SetEnvironmentVariable(ApplicationPrefix + "_PORTABLE", GlobalConfig.MainFolder, EnvironmentVariableTarget.Process); Environment.SetEnvironmentVariable(ApplicationPrefix + "_DRIVE", GlobalConfig.ApplicationDrive, EnvironmentVariableTarget.Process); #endif Environment.SetEnvironmentVariable(ApplicationPrefix + "_DATA", GlobalConfig.MainFolder, EnvironmentVariableTarget.Process); messageID = NativeMethods.RegisterWindowMessage("KrentoStop"); //Do not localize!!! NativeMethods.AddRemoveMessageFilter(messageID, ChangeWindowMessageFilterFlags.Add); PrepareStandardProperties(); showSplashScreen = true; ApplyGUILanguage(); GlobalSettings.LoadGlobalSettings(); GlobalSettings.ManagerLeft = Settings.Default.ManagerLeft; GlobalSettings.ManagerTop = Settings.Default.ManagerTop; #region Parse command line foreach (string param in args) { if (TextHelper.SameText(param, @"/low")) { GlobalConfig.LowMemory = true; } if (TextHelper.SameText(param, @"/ns")) { showSplashScreen = false; } if (TextHelper.SameText(param, @"/nd")) { KrentoContext.SkipDocklets = true; } if (TextHelper.SameText(param, @"/nt")) { KrentoContext.SkipToys = true; } if (TextHelper.SameText(param, @"/desktop")) { KrentoContext.CreateDesktopCircle = true; } if (param.IndexOf(@".circle", StringComparison.OrdinalIgnoreCase) > 0) { KrentoContext.CircleParameter = param; } if (FileOperations.IsKrentoPackage(param)) { KrentoContext.PackageParameter = param; } } #endregion this.context = new KrentoContext(); #region FirstRun if (NativeMethods.GlobalCheckAtom("krento_first_run")) { KrentoContext.FirstRun = true; NativeMethods.GlobalKillAtom("krento_first_run"); } #if PORTABLE string firstRunFile = Path.Combine(GlobalConfig.ApplicationFolder, "first.run"); if (NativeMethods.FileExists(firstRunFile)) { KrentoContext.FirstRun = true; NativeMethods.FileDelete(firstRunFile); } #endif if (KrentoContext.FirstRun) { GlobalSettings.SaveGlobalSettings(); } #endregion #region First Instance if (context.FirstInstance) { if ((showSplashScreen) && GlobalSettings.ShowSplashScreen) { splashScreen = new SplashScreen(); } else { splashScreen = null; } this.mainForm = new MainForm(context); mainForm.Text = GlobalConfig.ProductName; InteropHelper.MainWindow = mainForm.Handle; if (showSplashScreen) { if (splashScreen != null) { mainForm.SplashScreen = splashScreen; } } if (NativeMethods.StartEngineEx(mainForm.Handle)) { if (GlobalSettings.ActivateServer) { if (NetworkOperations.PortAvailable(GlobalSettings.PortNumber)) { context.StartServer(); } } appContext = new ApplicationContext(); //Load plugins. If the instance is the first instance and //engine is activated, then plugins are loaded try { context.LoadKrentoPlugins(); } catch (Exception) { //do not stop on wrong plugins TraceDebug.Trace("Exception on loading Krento plugin"); } try { context.LoadKrentoToys(); } catch (Exception) { //do not stop on wrong plugins TraceDebug.Trace("Exception on loading Krento toy"); } try { context.LoadKrentoDocklets(); } catch { //do not stop on wrong docklet TraceDebug.Trace("Exception on loading docklet"); } NativeThemeManager.MakeSound("#110"); Application.Run(appContext); } } #endregion }
internal void PrepareKeyboardHook() { KeyModifiers mod = KeyModifiers.None; try { if (hotKeys != null) { hotKeys.Dispose(); hotKeys = null; } if (ringKeys != null) { ringKeys.Dispose(); ringKeys = null; } if (GlobalSettings.UseKeyboardActivation) { try { if ((GlobalSettings.Modifiers & Keys.LWin) != 0) { mod |= KeyModifiers.Windows; } if ((GlobalSettings.Modifiers & Keys.Shift) != 0) { mod |= KeyModifiers.Shift; } if ((GlobalSettings.Modifiers & Keys.Alt) != 0) { mod |= KeyModifiers.Alt; } if ((GlobalSettings.Modifiers & Keys.Control) != 0) { mod |= KeyModifiers.Control; } hotKeys = new Hotkeys(mod, GlobalSettings.Shortcut, this); } catch (ArgumentException) { hotKeys = null; RtlAwareMessageBox.Show(SR.HotkeyCollision(HotKeyMessage), SR.KrentoShortName, MessageBoxButtons.OK, MessageBoxIcon.Error); } if (GlobalSettings.CircleSelector) { try { ringKeys = new Hotkeys(KeyModifiers.Windows, Keys.N, this); } catch { ringKeys = null; } } } } catch (Exception ex) { TraceDebug.Trace("PrepareKeyboardHook: ", ex); throw; } }
protected override void WndProc(ref Message m) { try { if (wasException) { base.WndProc(ref m); return; } if (!systemReady) { if (m.Msg == NativeMethods.CM_STARTENGINE) { ActivateEngine(); return; } if ((m.Msg == NativeMethods.WM_CLOSE) || (m.Msg == NativeMethods.WM_QUIT) || (m.Msg == NativeMethods.WM_QUERYENDSESSION)) { UnloadAll(); } base.WndProc(ref m); return; } else //do it only if the system is ready { if (context.Dispatch(ref m)) { return; } int code = m.Msg; switch (code) { case NativeMethods.WM_ACTIVATEAPP: // The WParam value identifies what is occurring. bool appActive = (((int)m.WParam != 0)); { if (GlobalSettings.HideOnClick) { if (!appActive) { if (Manager.Visible && (!Manager.Fading)) { if (!context.HookActive) { ChangeVisibility(); } } } } } break; case NativeMethods.WM_CLOSE: case NativeMethods.WM_QUIT: this.UnloadAll(); break; case NativeMethods.WM_QUERYENDSESSION: this.UnloadAll(); break; case NativeMethods.CM_CHECKUPDATE: ShowNewVersion(); break; case NativeMethods.WM_POWERBROADCAST: if (m.WParam == (IntPtr)NativeMethods.PBT_APMRESUMEAUTOMATIC) { context.HidePulsar(); if (Settings.Default.ShowPulsar) { Pulsar.RestoreAlpha(); Pulsar.Alpha = 60; context.ShowPulsar(); Pulsar.DeactivatePulsar(); } } break; case NativeMethods.CM_RBUTTONDOWN: { if (GlobalSettings.UseMouseActivation) { if (GlobalSettings.UseRightClick) { TraceDebug.Trace("CM_RBUTTONDOWN"); if (!trackRightDown) { trackRightDown = true; if (!context.Manager.Visible) { timerIntercept.Enabled = true; } } } } break; } case NativeMethods.CM_RBUTTONUP: { if (GlobalSettings.UseMouseActivation) { if (GlobalSettings.UseRightClick) { TraceDebug.Trace("CM_RBUTTONUP"); timerIntercept.Enabled = false; if (trackRightDown) { trackRightDown = false; if (!trackRightUp) { trackRightUp = true; MouseHook.PauseIntercept(); VirtualMouse.RightClick(); } else { trackRightUp = false; MouseHook.ResumeIntercept(); } } } } break; } case NativeMethods.CM_MBUTTONUP: case NativeMethods.CM_XBUTTONUP: if (GlobalSettings.UseMouseActivation) { int xButton = (int)m.WParam; MouseHookButton hookButton = MouseHookButton.None; if (m.Msg == NativeMethods.CM_MBUTTONUP) { hookButton = MouseHookButton.Wheel; } else { switch (xButton) { case NativeMethods.XBUTTON1: hookButton = MouseHookButton.XButton1; break; case NativeMethods.XBUTTON2: hookButton = MouseHookButton.XButton2; break; default: hookButton = MouseHookButton.None; break; } } if (GlobalSettings.MouseHook != hookButton) { return; } Keys modifiers = (Keys)m.LParam; if (GlobalSettings.MouseModifiers != modifiers) { return; } ActivateUsingMouse(true); } return; case NativeMethods.CM_DESKTOPCLICK: if (GlobalSettings.UseMouseActivation) { if (Manager != null) { if (context.HookActive) { return; } if (GlobalSettings.DesktopClick) { ActivateUsingMouse(true); } } } return; case NativeMethods.WM_HOTKEY: if (NativeMethods.IsMetroActive()) { return; } if (GlobalSettings.UseKeyboardActivation) { if (Manager != null) { if (context.HookActive) { return; } if (GlobalSettings.CircleSelector) { if (ringKeys != null) { if (((int)m.WParam) == (ringKeys.Id)) { Manager.SwitchRing(); } } } if (hotKeys != null) { if (((int)m.WParam) == (hotKeys.Id)) { if (Manager.Visible) { if (NativeMethods.GetForegroundWindow() != Manager.Handle) { Manager.Visible = false; Manager.Rotate(0); ChangeVisibility(); return; } } ChangeVisibility(); } } } } return; case NativeMethods.CM_SPLASHCLOSE: if (splashScreen != null) { splashScreen.Dispose(); splashScreen = null; } break; default: break; } base.WndProc(ref m); } } catch (Exception ex) { TraceDebug.Trace(ex); if (!wasException) { wasException = true; throw new KrentoEngineException("Krento Engine Error: ", ex); } } }
internal void InstallKrentoPart(string fileName) { string destination = null; bool compressed = false; bool loadNewToy = false; bool loadNewDocklet = false; bool reloadStones = false; string mainFolderName = null; string ext = Path.GetExtension(fileName); if (TextHelper.SameText(ext, ".toy")) { destination = GlobalConfig.ToysFolder; compressed = true; loadNewToy = true; } else if (TextHelper.SameText(ext, ".kmenu")) { destination = GlobalConfig.MenusFolder; compressed = true; } else if (TextHelper.SameText(ext, ".kskin")) { destination = GlobalConfig.SkinsFolder; compressed = true; } else if (TextHelper.SameText(ext, ".stone")) { destination = GlobalConfig.StoneClasses; compressed = true; reloadStones = true; } else if (TextHelper.SameText(ext, ".lng")) { destination = GlobalConfig.LanguagesFolder; compressed = false; } else if (TextHelper.SameText(ext, ".kadd")) { destination = GlobalConfig.AddInRootFolder; compressed = true; } else if (TextHelper.SameText(ext, ".docklet")) { destination = GlobalConfig.DockletsFolder; compressed = true; loadNewDocklet = true; } else if (TextHelper.SameText(ext, ".circle")) { destination = GlobalConfig.RollingStonesFolder; compressed = false; } if (string.IsNullOrEmpty(destination)) { return; } if (!compressed) { string destinationName = Path.Combine(destination, Path.GetFileName(fileName)); try { FileOperations.CopyFile(fileName, destinationName); if (TextHelper.SameText(destination, GlobalConfig.RollingStonesFolder)) { if (FileOperations.FileExists(destinationName)) { Manager.HistoryAdd(destinationName); } } } catch (Exception ex) { TraceDebug.Trace(ex); } } else { try { destination = Path.Combine(destination, Path.GetFileNameWithoutExtension(fileName)); if (!Directory.Exists(destination)) { Directory.CreateDirectory(destination); } } catch (Exception ex) { TraceDebug.Trace(ex); } NativeMethods.ExtractArchive(fileName, destination); FileOperations.CopyFile(fileName, Path.Combine(GlobalConfig.DownloadsFolder, Path.GetFileName(fileName))); if (reloadStones) { try { string newStonePath; if (!string.IsNullOrEmpty(mainFolderName)) { newStonePath = Path.Combine(destination, mainFolderName); } else { newStonePath = destination; } Language.Merge(Path.Combine(newStonePath, GlobalSettings.Language + ".lng")); } catch (Exception ex) { //Toy load error happens TraceDebug.Trace(ex); } //Loading of the new stone must be AFTER merging of the language Manager.LoadStoneClasses(); } else if (loadNewToy) { try { string newToyPath; if (!string.IsNullOrEmpty(mainFolderName)) { newToyPath = Path.Combine(destination, mainFolderName); } else { newToyPath = destination; } context.LoadKrentoToys(newToyPath); } catch (Exception ex) { //Toy load error happens TraceDebug.Trace(ex); } } else if (loadNewDocklet) { try { string newDockletPath; if (!string.IsNullOrEmpty(mainFolderName)) { newDockletPath = Path.Combine(destination, mainFolderName); } else { newDockletPath = destination; } context.LoadKrentoDocklets(newDockletPath); } catch (Exception ex) { //Toy load error happens TraceDebug.Trace(ex); } } } }
private void ExecuteAsync() { Version clientVersion; try { AssemblyName krentoName = new AssemblyName(Assembly.GetEntryAssembly().FullName); if (krentoName != null) { clientVersion = krentoName.Version; } else { clientVersion = new Version(Application.ProductVersion); } } catch { clientVersion = new Version("3.0"); TraceDebug.Trace("Error in getting the Krento assembly version. By default assume 3.0"); } Version serverVersion = null; #if DEBUG string configFile = "http://localhost:8080"; #else string configFile = Settings.Default.Website; #endif if (!configFile.EndsWith("/", StringComparison.OrdinalIgnoreCase)) { configFile = configFile + "/"; } configFile = configFile + "app_version.xml"; XmlTextReader reader = null; try { try { // provide the XmlTextReader with the URL of // our xml document string xmlURL = configFile; reader = new XmlTextReader(xmlURL); // simply (and easily) skip the junk at the beginning reader.MoveToContent(); // internal - as the XmlTextReader moves only // forward, we save current xml element name // in elementName variable. When we parse a // text node, we refer to elementName to check // what was the node name string elementName = ""; // we check if the xml starts with a proper // "ourfancyapp" element node if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "krento")) { while (reader.Read()) { // when we find an element node, // we remember its name if (reader.NodeType == XmlNodeType.Element) { elementName = reader.Name; } else { // for text nodes... if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue)) { // we check what the name of the node was switch (elementName) { case "version": // thats why we keep the version info // in xxx.xxx.xxx.xxx format // the Version class does the // parsing for us serverVersion = new Version(reader.Value); break; case "url": url = reader.Value; break; } } } } } } finally { if (reader != null) { reader.Close(); } } } catch { serverVersion = null; } if (serverVersion != null) { version = serverVersion.ToString(); if (clientVersion < serverVersion) { NativeMethods.PostMessage(InteropHelper.MainWindow, NativeMethods.CM_CHECKUPDATE, IntPtr.Zero, IntPtr.Zero); } } }
internal void _CaptureRaceTest(Action <string> onComplete, IEnumerable <DataSample> samples) { var overlayData = new OverlayData(); var removalEdits = new RemovalEdits(overlayData.RaceEvents); var commentaryMessages = new CommentaryMessages(overlayData); var videoCapture = new VideoCapture(); var recordPitStop = new RecordPitStop(commentaryMessages); var fastestLaps = new RecordFastestLaps(overlayData); var replayControl = new ReplayControl(samples.First().SessionData, incidents, removalEdits, TrackCameras); var sessionDataCapture = new SessionDataCapture(overlayData); var captureLeaderBoardEveryHalfSecond = new SampleFilter(TimeSpan.FromSeconds(0.5), new CaptureLeaderBoard(overlayData, commentaryMessages, removalEdits).Process); var captureCamDriverEveryQuaterSecond = new SampleFilter(TimeSpan.FromSeconds(0.25), new CaptureCamDriver(overlayData).Process); var captureCamDriverEvery4Seconds = new SampleFilter(TimeSpan.FromSeconds(4), new LogCamDriver().Process); TraceDebug.WriteLine("Cameras:"); TraceDebug.WriteLine(TrackCameras.ToString()); ApplyFirstLapCameraDirection(samples, replayControl); samples = samples .VerifyReplayFrames() .WithCorrectedPercentages() .WithCorrectedDistances() .WithFastestLaps() .WithFinishingStatus() .WithPitStopCounts() .TakeUntil(3.Seconds()).Of(d => d.Telemetry.LeaderHasFinished && d.Telemetry.RaceCars.All(c => c.HasSeenCheckeredFlag || c.HasRetired || c.TrackSurface != TrackLocation.OnTrack)) .TakeUntil(3.Seconds()).AfterReplayPaused(); if (shortTestOnly) { samples = samples.AtSpeed(Settings.Default.TimingFactorForShortTest); Settings.AppliedTimingFactor = 1.0 / Settings.Default.TimingFactorForShortTest; } videoCapture.Activate(workingFolder); var startTime = DateTime.Now; overlayData.CapturedVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); foreach (var data in samples) { var relativeTime = DateTime.Now - startTime; replayControl.Process(data); sessionDataCapture.Process(data); captureLeaderBoardEveryHalfSecond.Process(data, relativeTime); captureCamDriverEveryQuaterSecond.Process(data, relativeTime); recordPitStop.Process(data, relativeTime); fastestLaps.Process(data, relativeTime); removalEdits.Process(data, relativeTime); captureCamDriverEvery4Seconds.Process(data, relativeTime); } var files = videoCapture.Deactivate(); removalEdits.Stop(); var overlayFile = SaveOverlayData(overlayData, files); //terminate iRacing after video capture completed try { //ToBe added: Option to select/deselect termination of iRacing after capturing video in new settings Dialog Process[] iRacingProc = Process.GetProcessesByName("iRacingSim64DX11"); iRacingProc[0].Kill(); } catch { throw new Exception("Could not terminate iRacing Simulator".F(workingFolder)); } iRacing.Replay.SetSpeed(0); AltTabBackToApp(); if (files.Count == 0) { throw new Exception("Unable to find video files in '{0}' - possible wrong working folder".F(workingFolder)); } _WithOverlayFile(overlayFile); onComplete(overlayFile); }