Beispiel #1
0
        public void BindAnalyzer(IOProvider io)
        {
            this.io      = io;
            io.ByteRead += b => UART.WriteChar((byte)b);

            Action <byte> writeAction = (b =>
            {
                lock (lockObject)
                {
                    io.Write(b);
                }
            });

            var mre = new ManualResetEventSlim();

            Task.Run(() =>
            {
                lock (lockObject)
                {
                    mre.Set();
                    RepeatHistory();
                    UART.CharReceived += writeAction;
                    actionsDictionary.Add(io, writeAction);
                }
            });
            mre.Wait();
        }
Beispiel #2
0
        public UartPtyTerminal(string linkName, bool forceCreate = false)
        {
            var ptyUnixStream = new PtyUnixStream();

            io = new IOProvider {
                Backend = new StreamIOSource(ptyUnixStream)
            };
            io.ByteRead += b => CallCharReceived((byte)b);

            if (File.Exists(linkName))
            {
                if (!forceCreate)
                {
                    throw new RecoverableException(string.Format("File `{0}' already exists. Use forceCreate to overwrite it.", linkName));
                }

                try
                {
                    File.Delete(linkName);
                }
                catch (Exception e)
                {
                    throw new RecoverableException(string.Format("There was an error when removing existing `{0}' symlink: {1}", linkName, e.Message));
                }
            }
            try
            {
                var slavePtyFile = new UnixFileInfo(ptyUnixStream.SlaveName);
                symlink = slavePtyFile.CreateSymbolicLink(linkName);
            }
            catch (Exception e)
            {
                throw new RecoverableException(string.Format("There was an error when when creating a symlink `{0}': {1}", linkName, e.Message));
            }
        }
        public static Shell GenerateShell(IOProvider io, Monitor monitor, bool forceVCursor = false)
        {
            var settings = new ShellSettings {
                NormalPrompt               = new Prompt("(monitor) ", ConsoleColor.DarkRed),
                BannerProvider             = () => Enumerable.Repeat(Environment.NewLine, NumberOfDummyLines).Aggregate(String.Empty, (x, y) => x + y) + EmulationManager.Instance.VersionString,
                PreprocessSuggestionsInput = Monitor.SanitizePathSeparator,
                UseBuiltinQuit             = false,
                UseBuiltinHelp             = false,
                UseBuiltinSave             = false,
                ForceVirtualCursor         = forceVCursor,
                ClearScreen        = false,
                DirectorySeparator = '/',
                HistorySavePath    = ConfigurationManager.Instance.Get("general", "history-path", Path.Combine(Emulator.UserDirectoryPath, "history"))
            };

            var shell = new Shell(io, monitor, settings);

            var startupCommand = Environment.GetEnvironmentVariable(Monitor.StartupCommandEnv);

            if (!string.IsNullOrEmpty(startupCommand) && shell != null)
            {
                shell.StartupCommand = startupCommand;
            }

            return(shell);
        }
        public ConsoleWindowBackendAnalyzer()
        {
            preferredTerminal = ConfigurationManager.Instance.Get("general", "terminal", TerminalTypes.Termsharp);
#if EMUL8_PLATFORM_WINDOWS
            if (preferredTerminal != TerminalTypes.Termsharp)
            {
                Logger.LogAs(this, LogLevel.Warning, "Only >>Termsharp<< terminal is available on Windows - forcing to use it.");
            }
#endif
            if (preferredTerminal == TerminalTypes.Termsharp)
            {
                ApplicationExtensions.InvokeInUIThreadAndWait(() =>
                {
                    terminalWidget = new TerminalWidget(() => window.HasFocus);
                });
                IO = terminalWidget.IO;
            }
#if !EMUL8_PLATFORM_WINDOWS
            else
            {
                ptyUnixStream = new PtyUnixStream();
                IO            = new IOProvider(new StreamIOSource(ptyUnixStream));
            }
#endif
        }
Beispiel #5
0
        internal bool CreateDigitalObject(XmlNode node)
        {
            if (node == null)
            {
                return(false);
            }
            XmlNode item = node.SelectSingleNode("Digital");

            if (item == null)
            {
                return(false);
            }
            Common.DI = CreateSingleDigitalObject(item, HardwareType.DI);
            Common.DO = CreateSingleDigitalObject(item, HardwareType.DO);
            XmlNode hw = item.SelectSingleNode("Hardware");

            if (hw != null)
            {
                IOProvider provider = Serialize.XmlDeSerialize(hw) as IOProvider;
                if (provider != null)
                {
                    Common.DI.Provider = provider;
                    Common.DO.Provider = provider;
                    Common.ReportCmdKeyProgress(CmdKey.S0704, false);
                }
                else
                {
                    Common.ReportCmdKeyProgress(CmdKey.S0705);
                    return(false);
                }
            }
            return(Common.DI != null & Common.DO != null);
        }
Beispiel #6
0
        public static async Task Main(string[] args)
        {
            Console.SetWindowSize(100, 10);
            var provider = new IOProvider();

            await new InvokerService("Main", new StreamProvider(provider.Reader, provider.Writer), false, provider.PostRun).Run();
        }
Beispiel #7
0
 public void UnbindAnalyzer(IOProvider io)
 {
     lock (lockObject)
     {
         UART.CharReceived -= actionsDictionary[io];
         actionsDictionary.Remove(io);
     }
 }
        private static Shell PrepareShell(Options options, Monitor monitor)
        {
            Shell shell = null;

            if (options.Port >= 0)
            {
                var io = new IOProvider(new SocketIOSource(options.Port));
                shell = ShellProvider.GenerateShell(io, monitor, true, false);
            }
            else
            {
                ConsoleWindowBackendAnalyzer terminal = null;
                IOProvider io;
                if (options.HideMonitor)
                {
                    io = new IOProvider(new DummyIOSource());
                }
                else
                {
                    terminal = new ConsoleWindowBackendAnalyzer();
                    io       = terminal.IO;
                }

                // forcing vcursor is necessary, because calibrating will never end if the window is not shown
                shell            = ShellProvider.GenerateShell(io, monitor, forceVCursor: options.HideMonitor);
                monitor.Quitted += shell.Stop;

                if (terminal != null)
                {
                    try
                    {
                        terminal.Quitted += Emulator.Exit;
                        terminal.Show();
                    }
                    catch (InvalidOperationException ex)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Error.WriteLine(ex.Message);
                        Emulator.Exit();
                    }
                }
            }
            shell.Quitted += Emulator.Exit;

            monitor.Interaction     = shell.Writer;
            monitor.MachineChanged += emu => shell.SetPrompt(emu != null ? new Prompt(string.Format("({0}) ", emu), ConsoleColor.DarkYellow) : null);

            if (options.Execute != null)
            {
                shell.Started += s => s.InjectInput(string.Format("{0}\n", options.Execute));
            }
            else if (!string.IsNullOrEmpty(options.ScriptPath))
            {
                shell.Started += s => s.InjectInput(string.Format("i {0}{1}\n", Path.IsPathRooted(options.ScriptPath) ? "@" : "$CWD/", options.ScriptPath));
            }

            return(shell);
        }
 private void Initialize()
 {
     ptyStream = new PtyUnixStream();
     io        = new IOProvider {
         Backend = new StreamIOSource(ptyStream)
     };
     io.ByteRead += CharReceived;
     CreateSymlink(linkName);
 }
Beispiel #10
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (IO != null)
            {
                IO.Dispose();
                IO = null;
            }
        }
 public SlipRadio(string linkName)
 {
     ptyStream = new PtyUnixStream();
     io        = new IOProvider {
         Backend = new StreamIOSource(ptyStream)
     };
     buffer       = new List <byte>();
     io.ByteRead += CharReceived;
     CreateSymlink(linkName);
 }
Beispiel #12
0
        public int Read(out FieldValue[] values)
        {
            List <FieldValue> list = new List <FieldValue>();
            int localOffset        = 0;

            foreach (StructField field in _fields)
            {
                FieldValue value;

                // Perform alignment.
                localOffset = Offset.Increment(localOffset).Align(field.Alignment).Decrement(Offset).ToInt32();

                // Resolve pointer, if needed.
                if (field.IsPointer)
                {
                    IntPtr pointingTo = IOProvider.ReadBytes(Offset.Increment(localOffset), IntPtr.Size).ToIntPtr();

                    localOffset += IntPtr.Size;

                    if (pointingTo == IntPtr.Zero)
                    {
                        value = new FieldValue()
                        {
                            Name = field.Name, FieldType = field.RawType, Value = null
                        }
                    }
                    ;
                    else
                    {
                        Read(field, pointingTo, out value);
                    }

                    value.PointerValue = pointingTo;
                }
                else
                {
                    localOffset += Read(field, Offset.Increment(localOffset), out value);
                }

                if (field.SetsVarOn != null)
                {
                    _fieldsByName[field.SetsVarOn].VarLength =
                        field.SetsVarOnAdd + (int)(int.Parse(value.Value.ToString()) * (decimal)field.SetsVarOnMultiply);
                    _fieldsByName[field.SetsVarOn].VarArrayLength =
                        field.SetsVarOnAdd + (int)(int.Parse(value.Value.ToString()) * (decimal)field.SetsVarOnMultiply);
                }

                list.Add(value);
            }

            values = list.ToArray();

            return(localOffset);
        }
Beispiel #13
0
        public int Read(out FieldValue[] values)
        {
            List <FieldValue> list = new List <FieldValue>();
            int localOffset        = 0;

            foreach (StructField field in _fields)
            {
                FieldValue value;

                // resolve pointer
                if (field.IsPointer)
                {
                    int pointingTo = Utils.ToInt32(IOProvider.ReadBytes(Offset.Increment(localOffset), 4), Utils.Endianness.Little);

                    localOffset += 4;

                    if (pointingTo == 0)
                    {
                        value = new FieldValue()
                        {
                            Name = field.Name, FieldType = field.RawType, Value = null
                        }
                    }
                    ;
                    else
                    {
                        Read(field, new IntPtr(pointingTo), out value);
                    }

                    value.PointerValue = pointingTo;
                }
                else
                {
                    localOffset += Read(field, Offset.Increment(localOffset), out value);
                }

                if (field.SetsVarOn != null)
                {
                    _fieldsByName[field.SetsVarOn].VarLength =
                        field.SetsVarOnAdd + (int)(int.Parse(value.Value.ToString()) * (decimal)field.SetsVarOnMultiply);
                    _fieldsByName[field.SetsVarOn].VarArrayLength =
                        field.SetsVarOnAdd + (int)(int.Parse(value.Value.ToString()) * (decimal)field.SetsVarOnMultiply);
                }

                list.Add(value);
            }

            values = list.ToArray();

            return(localOffset);
        }
Beispiel #14
0
        public UartPtyTerminal(string linkName, bool forceCreate = false)
        {
            ptyStream = new PtyUnixStream();

            this.linkName    = linkName;
            this.forceCreate = forceCreate;

            io = new IOProvider {
                Backend = new StreamIOSource(ptyStream)
            };
            io.ByteRead += b => CallCharReceived((byte)b);

            CreateSymlink();
        }
Beispiel #15
0
        public AntCalc(Stream stream)
        {
            var sett = new ShellSettings {
                NormalPrompt   = new Prompt("ant-calc ", ConsoleColor.DarkBlue),
                BannerProvider = () => "Welcome to AntCalc - AntShell Demo!"
            };

            var io = new IOProvider {
                Backend = new StreamIOSource(stream)
            };

            shell = new Shell(io, null, sett);
            shell.RegisterCommand(new AddCommand());
            shell.RegisterCommand(new AskCommand());
            shell.RegisterCommand(new PrintCommand());
        }
Beispiel #16
0
        public void BindAnalyzer(IOProvider io)
        {
            this.io      = io;
            io.ByteRead += b =>
            {
                if (!TimeDomainsManager.Instance.TryGetVirtualTimeStamp(out var vts))
                {
                    // it happens when writing from uart analyzer
                    vts = new TimeStamp(default(TimeInterval), EmulationManager.ExternalWorld);
                }

                UART.GetMachine().HandleTimeDomainEvent(UART.WriteChar, (byte)b, vts);
            };

            Action <byte> writeAction = (b =>
            {
                lock (lockObject)
                {
                    io.Write(b);
                }
            });

            var mre = new ManualResetEventSlim();

            Task.Run(() =>
            {
                lock (lockObject)
                {
                    mre.Set();
                    RepeatHistory();
                    UART.CharReceived += writeAction;
                    actionsDictionary.Add(io, writeAction);
                }
            });
            mre.Wait();
        }
Beispiel #17
0
 public Program(IOProvider provider) : base(provider)
 {
 }
Beispiel #18
0
 public Base(IOProvider provider)
 {
     this.io = provider;
 }
Beispiel #19
0
        public TerminalWidget(Func <bool> focusProvider)
        {
            var shortcutDictionary = new Dictionary <KeyEventArgs, Action>
            {
                { CreateKey(Key.C, ModifierKeys.Shift | ModifierKeys.Control), CopyMarkedField },
                { CreateKey(Key.V, ModifierKeys.Shift | ModifierKeys.Control), PasteMarkedField },
                { CreateKey(Key.Insert, ModifierKeys.Shift), PasteMarkedField },
                { CreateKey(Key.PageUp, ModifierKeys.Shift), () => terminal.PageUp() },
                { CreateKey(Key.PageDown, ModifierKeys.Shift), () => terminal.PageDown() },
                { CreateKey(Key.Plus, ModifierKeys.Shift | ModifierKeys.Control), FontSizeUp },
                { CreateKey(Key.Minus, ModifierKeys.Control), FontSizeDown },
                { CreateKey(Key.NumPadAdd, ModifierKeys.Control), FontSizeUp },
                { CreateKey(Key.NumPadSubtract, ModifierKeys.Control), FontSizeDown },
                { CreateKey(Key.K0, ModifierKeys.Control), SetDefaultFontSize },
                { CreateKey(Key.NumPad0, ModifierKeys.Control), SetDefaultFontSize }
            };

            modifyLineEndings         = ConfigurationManager.Instance.Get("termsharp", "append-CR-to-LF", false);
            terminal                  = new Terminal(focusProvider);
            terminalInputOutputSource = new TerminalIOSource(terminal);
            IO              = new IOProvider(terminalInputOutputSource);
            IO.BeforeWrite += b =>
            {
                // we do not check if previous byte was '\r', because it should not cause any problem to
                // send it twice
                if (modifyLineEndings && b == '\n')
                {
                    IO.Write((byte)'\r');
                }
            };

            terminal.InnerMargin    = new WidgetSpacing(5, 5, 5, 5);
            terminal.Cursor.Enabled = true;
            terminal.ContextMenu    = CreatePopupMenu();

            // We set the default font as a fall-back option.
            terminal.CurrentFont = Xwt.Drawing.Font.SystemMonospaceFont;
#if EMUL8_PLATFORM_LINUX
            // Here we try to load the robot font; unfortunately it doesn't work on OSX and Windows. Moreover, on some versions of
            // OSX it passes with no error (and no effect), on the others - it hangs. That's why we try to set the font and then
            // we check if we succeeded.
            var fontFile = typeof(TerminalWidget).Assembly.FromResourceToTemporaryFile("RobotoMono-Regular.ttf");
            Xwt.Drawing.Font.RegisterFontFromFile(fontFile);
#endif
            var fontFace = ConfigurationManager.Instance.Get("termsharp", "font-face", "Roboto Mono");
            defaultFontSize = ConfigurationManager.Instance.Get("termsharp", "font-size", (int)PredefinedFontSize, x => x >= MinFontSize);
            var font = Xwt.Drawing.Font.FromName(fontFace);
            if (!font.Family.Contains(fontFace))
            {
                Logger.Log(LogLevel.Warning, "The font '{0}' defined in the config file cannot be loaded.", fontFace);
                font = terminal.CurrentFont;
            }
            terminal.CurrentFont = font.WithSize(defaultFontSize);

            if (!FirstWindowAlreadyShown)
            {
                terminal.AppendRow(new LogoRow());
                FirstWindowAlreadyShown = true;
                firstWindow             = true;
            }
            else
            {
                terminal.AppendRow(new MonospaceTextRow(""));
            }

            var encoder = new TermSharp.Vt100.Encoder(x =>
            {
                terminal.ClearSelection();
                terminal.MoveScrollbarToEnd();
                terminalInputOutputSource.HandleInput(x);
            });

            terminal.KeyPressed += (s, a) =>
            {
                a.Handled = true;

                var modifiers = a.Modifiers;
                if (!Misc.IsOnOsX)
                {
                    modifiers &= ~(ModifierKeys.Command);
                }

                foreach (var entry in shortcutDictionary)
                {
                    if (modifiers == entry.Key.Modifiers)
                    {
                        if (a.Key == entry.Key.Key)
                        {
                            entry.Value();
                            return;
                        }
                    }
                }
                encoder.Feed(a.Key, modifiers);
            };
            Content = terminal;
        }
Beispiel #20
0
 public ConsoleWindowBackendAnalyzer()
 {
     IO = new IOProvider();
 }
Beispiel #21
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
            #if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                DebugSettings.EnableFrameRateCounter = true;
            }
            #endif

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat application initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            // add needed objects to IoC container
            var locator = Resources[LocaterResource] as ViewModelLocator;
            if (locator != null)
            {
                var container = locator.Container;
                container.Register(locator);

                var dateTimeTask = new DateTimeProvider(container);
                container.Register(dateTimeTask);
                dateTimeTask.Start();

                var client = new MqttClient(MqttBrokerAddress);
                container.Register(client);

                var telemetryProvider = new TelemetryProvider(container);
                container.Register(telemetryProvider);

                var rssProvider = new RssProvider(container);
                container.Register(rssProvider);
                rssProvider.Start();

                var speechInterpreter = new SpeechInterpreter(container);
                container.Register(speechInterpreter);
                speechInterpreter.Start();

                var WeatherProvider = new WeatherProvider(container);
                container.Register(WeatherProvider);

                var ioProvider = new IOProvider(container);
                container.Register(ioProvider);
            }

            ApplicationView.GetForCurrentView().TryEnterFullScreenMode();

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(MainPage), e.Arguments);
            }
            // Ensure the current window is active
            Window.Current.Activate();
            if (locator != null)
            {
                var container = locator.Container;
                container.Register(Window.Current);
            }
        }
 public IOProviderStreamWrapper(IOProvider io)
 {
     this.io = io;
 }
Beispiel #23
0
        private unsafe int ReadOnce(StructField field, IntPtr offset, out FieldValue valueOut)
        {
            FieldValue value = new FieldValue()
            {
                FieldType = field.Type, Name = field.Name
            };
            int readSize = 0;

            switch (field.Type)
            {
            case FieldType.Bool32:
                value.Value = Utils.ToInt32(IOProvider.ReadBytes(offset, 4),
                                            Utils.Endianness.Little) != 0;
                readSize = 4;
                break;

            case FieldType.Bool8:
                value.Value = IOProvider.ReadBytes(offset, 1)[0] != 0;
                readSize    = 1;
                break;

            case FieldType.CharASCII:
                value.Value = (char)IOProvider.ReadBytes(offset, 1)[0];
                readSize    = 1;
                break;

            case FieldType.CharUTF16:
                value.Value = Encoding.Unicode.GetString(IOProvider.ReadBytes(offset, 2))[0];
                readSize    = 2;
                break;

            case FieldType.Double:
            {
                long data = Utils.ToInt64(
                    IOProvider.ReadBytes(offset, 8), Utils.Endianness.Little);

                value.Value = *(double *)&data;
                readSize    = 8;
            }
            break;

            case FieldType.Int16:
                value.Value = (short)Utils.ToUInt16(
                    IOProvider.ReadBytes(offset, 2), Utils.Endianness.Little);
                readSize = 2;
                break;

            case FieldType.Int32:
                value.Value = Utils.ToInt32(
                    IOProvider.ReadBytes(offset, 4), Utils.Endianness.Little);
                readSize = 4;
                break;

            case FieldType.Int64:
                value.Value = Utils.ToInt64(
                    IOProvider.ReadBytes(offset, 8), Utils.Endianness.Little);
                readSize = 8;
                break;

            case FieldType.Int8:
                value.Value = (sbyte)IOProvider.ReadBytes(offset, 1)[0];
                readSize    = 1;
                break;

            case FieldType.PVoid:
                value.Value = IOProvider.ReadBytes(offset, IntPtr.Size).ToIntPtr();
                readSize    = IntPtr.Size;
                break;

            case FieldType.Single:
            {
                int data = Utils.ToInt32(
                    IOProvider.ReadBytes(offset, 4), Utils.Endianness.Little);

                value.Value = *(float *)&data;
                readSize    = 4;
            }
            break;

            case FieldType.StringASCII:
            {
                StringBuilder str = new StringBuilder();

                if (field.VarLength == -1)
                {
                    int i;

                    for (i = 0; ; i++)
                    {
                        byte b = IOProvider.ReadBytes(offset.Increment(i), 1)[0];

                        if (b == 0)
                        {
                            break;
                        }

                        str.Append((char)b);
                    }

                    readSize = i;
                }
                else
                {
                    str.Append(Encoding.ASCII.GetString(
                                   IOProvider.ReadBytes(offset, field.VarLength)));
                    readSize = field.VarLength;
                }

                value.Value = str.ToString();
            }

            break;

            case FieldType.StringUTF16:
            {
                StringBuilder str = new StringBuilder();

                if (field.VarLength == -1)
                {
                    int i;

                    for (i = 0; ; i += 2)
                    {
                        byte[] b = IOProvider.ReadBytes(offset.Increment(i), 2);

                        if (Utils.IsEmpty(b))
                        {
                            break;
                        }

                        str.Append(Encoding.Unicode.GetString(b));
                    }

                    readSize = i;
                }
                else
                {
                    str.Append(Encoding.Unicode.GetString(
                                   IOProvider.ReadBytes(offset, field.VarLength * 2))); // each char is 2 bytes
                    readSize = field.VarLength;
                }

                value.Value = str.ToString();
            }

            break;

            case FieldType.Struct:
            {
                FieldValue[] valuesOut;
                StructDef    struc = Structs[field.StructName];

                struc.IOProvider = this.IOProvider;
                struc.Offset     = offset;
                struc.Structs    = this.Structs;
                readSize         = struc.Read(out valuesOut);
                value.Value      = valuesOut;
                value.StructName = field.StructName;
            }

            break;

            case FieldType.UInt16:
                value.Value = Utils.ToUInt16(
                    IOProvider.ReadBytes(offset, 2), Utils.Endianness.Little);
                readSize = 2;
                break;

            case FieldType.UInt32:
                value.Value = Utils.ToUInt32(
                    IOProvider.ReadBytes(offset, 4), Utils.Endianness.Little);
                readSize = 4;
                break;

            case FieldType.UInt64:
                value.Value = (ulong)Utils.ToInt64(
                    IOProvider.ReadBytes(offset, 8), Utils.Endianness.Little);
                readSize = 8;
                break;

            case FieldType.UInt8:
                value.Value = IOProvider.ReadBytes(offset, 1)[0];
                readSize    = 1;
                break;

            default:
                readSize = 0;
                break;
            }

            valueOut = value;

            return(readSize);
        }
 public ConsoleWindowBackendAnalyzer(bool isMonitorWindow)
 {
     IO = new IOProvider();
     this.isMonitorWindow = isMonitorWindow;
 }
Beispiel #25
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat application initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            // add needed objects to IoC container
            var locator = Resources[LocaterResource] as ViewModelLocator;
            if (locator != null)
            {
                var container = locator.Container;
                container.Register(locator);

                var dateTimeTask = new DateTimeProvider(container);
                container.Register(dateTimeTask);
                dateTimeTask.Start();

                var client = new MqttClient(MqttBrokerAddress);
                container.Register(client);

                var telemetryProvider = new TelemetryProvider(container);
                container.Register(telemetryProvider);

                var rssProvider = new RssProvider(container);
                container.Register(rssProvider);
                rssProvider.Start();

                var speechInterpreter = new SpeechInterpreter(container);
                container.Register(speechInterpreter);
                speechInterpreter.Start();

                var WeatherProvider = new WeatherProvider(container);
                container.Register(WeatherProvider);

                var ioProvider = new IOProvider(container);
                container.Register(ioProvider);
            }

            ApplicationView.GetForCurrentView().TryEnterFullScreenMode();

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(MainPage), e.Arguments);
            }
            // Ensure the current window is active
            Window.Current.Activate();
            if (locator != null)
            {
                var container = locator.Container;
                container.Register(Window.Current);
            }
        }
Beispiel #26
0
        public static void Run(string[] args)
        {
            var options = new Options();
            var optionsParser = new OptionsParser();
            if(!optionsParser.Parse(options, args))
            {
                return;
            }

            Plugins.XwtProviderPlugin.XwtProvider.StartXwtThread();
            using(var context = ObjectCreator.Instance.OpenContext())
            {
                var monitor = new Emul8.UserInterface.Monitor();
                context.RegisterSurrogate(typeof(Emul8.UserInterface.Monitor), monitor);

                // we must initialize plugins AFTER registering monitor surrogate
                // as some plugins might need it for construction
                TypeManager.Instance.PluginManager.Init("CLI");

                Logger.AddBackend(ConsoleBackend.Instance, "console");

                EmulationManager.Instance.ProgressMonitor.Handler = new CLIProgressMonitor();

                var crashHandler = new CrashHandler();
                AppDomain.CurrentDomain.UnhandledException += (sender, e) => crashHandler.HandleCrash(e);

                Shell shell = null;
                Type preferredUARTAnalyzer = null;
                if(options.Port > 0)
                {
                    var io = new IOProvider(new SocketIOSource(options.Port));
                    shell = ShellProvider.GenerateShell(io, monitor, true, false);
                }
                else
                {
                    preferredUARTAnalyzer = typeof(UARTWindowBackendAnalyzer);

                    var terminal = new UARTWindowBackendAnalyzer();
                    shell = ShellProvider.GenerateShell(terminal.IO, monitor);
                    monitor.Quitted += shell.Stop;

                    try
                    {
                        terminal.Show();
                    }
                    catch(InvalidOperationException ex)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Error.WriteLine(ex.Message);
                        Emulator.Exit();
                    }
                }
                shell.Quitted += Emulator.Exit;

                if(preferredUARTAnalyzer != null)
                {
                    EmulationManager.Instance.CurrentEmulation.BackendManager.SetPreferredAnalyzer(typeof(UARTBackend), preferredUARTAnalyzer);
                    EmulationManager.Instance.EmulationChanged += () =>
                    {
                        EmulationManager.Instance.CurrentEmulation.BackendManager.SetPreferredAnalyzer(typeof(UARTBackend), preferredUARTAnalyzer);
                    };
                }
                monitor.Interaction = shell.Writer;
                monitor.MachineChanged += emu => shell.SetPrompt(emu != null ? new Prompt(string.Format("({0}) ", emu), ConsoleColor.DarkYellow) : null);

                if(options.Execute != null)
                {
                    shell.Started += s => s.InjectInput(string.Format("{0}\n", options.Execute));
                }
                else if(!string.IsNullOrEmpty(options.ScriptPath))
                {
                    shell.Started += s => s.InjectInput(string.Format("i {0}{1}\n", Path.IsPathRooted(options.ScriptPath) ? "@" : "$CWD/", options.ScriptPath));
                }

                new Thread(x => shell.Start(true)) 
                { 
                    IsBackground = true, 
                    Name = "Shell thread" 
                }.Start();

                Emulator.BeforeExit += () =>
                {
                    Emulator.DisposeAll();
                };

                Emulator.WaitForExit();
                Plugins.XwtProviderPlugin.XwtProvider.StopXwtThread();
            }
        }