상속: MonoBehaviour
        public MainWindow()
        {
            InitializeComponent();
            cm = new ClipboardMonitor();
            cm.ClipboardChanged += cm_ClipboardChanged;

            hk = new Hotkey();
            hk.KeyCode = Keys.D1;
            hk.Windows = false;
            hk.Control = true;
            hk.Pressed += delegate { Console.WriteLine("Windows+1 pressed!"); };

            if (!hk.GetCanRegister(this))
            {
                Console.WriteLine("Whoops, looks like attempts to register will fail or throw an exception, show an error/visual user feedback");
            }
            else
            {
                hk.Register(this);
            }

            //// .. later, at some point
            //if (hk.Registered)
            //{ hk.Unregister(); }
        }
예제 #2
0
        public GBGMain()
        {
            InitializeComponent();
            ttUpdater.Interval = 500;
            ttUpdater.Tick += new EventHandler((o, e) =>
            {
                long mil = totalRunTime.ElapsedMilliseconds,
                     seconds = mil / 1000,
                     minutes = seconds / 60 % 60,
                     hours = minutes / 60,
                     days = hours / 24;

                lblTotalRunTime.Text = "Approx. " + days + "d " + (hours % 24) + "h " + (minutes % 60) + "m " + (seconds % 60) + "s";
            });

            bgw.WorkerSupportsCancellation = true;
            bgw.WorkerReportsProgress = true;
            bgw.DoWork += new DoWorkEventHandler(RunBot_Work);
            bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
            bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);

            Hotkey hkRunBot = new Hotkey(Keys.F12, false, true, true, false);

            hkRunBot.Pressed += delegate
            {
                if(btnStopBot.Enabled)
                    StopBot();
                else if(btnRunBot.Enabled)
                    RunBot();
            };

            hkRunBot.Register(this);
        }
예제 #3
0
 private void Register()
 {
     if(hotkey != null)
         hotkey.Dispose();
     hotkey = new Hotkey(ModifierKey, Key, window);
     hotkey.HotkeyPressed += (k) => action(window);
 }
예제 #4
0
 public FormMain()
 {
     InitializeComponent();
     hotKey = new Hotkey(Handle);
     hotKey.RegisterHotkey(Keys.R, Hotkey.KeyFlags.MOD_CONTROL);
     hotKey.OnHotkey+=new Hotkey.HotkeyEventHandler(hotKey_OnHotkey);
 }
예제 #5
0
파일: Hotkey.cs 프로젝트: Roger-luo/OpenRA
		public static bool TryParse(string s, out Hotkey result)
		{
			result = Invalid;
			if (string.IsNullOrWhiteSpace(s))
				return false;

			var parts = s.Split(' ');

			Keycode key;
			if (!Enum<Keycode>.TryParse(parts[0], true, out key))
			{
				int c;
				if (!int.TryParse(parts[0], out c))
					return false;
				key = (Keycode)c;
			}

			var mods = Modifiers.None;
			if (parts.Length >= 2)
			{
				var modString = s.Substring(s.IndexOf(' '));
				if (!Enum<Modifiers>.TryParse(modString, true, out mods))
					return false;
			}

			result = new Hotkey(key, mods);
			return true;
		}
예제 #6
0
        static void Main(string[] args)
        {
            ContextMenu menu = new ContextMenu();
            menu.MenuItems.Add("Exit", new System.EventHandler(exit_click));
            if (args.Length == 0 || args[0] != "runas")
            {
                menu.MenuItems.Add("Run as Administrator", new System.EventHandler(uac_click));
            }

            Hotkey minimizeHotkey = new Hotkey();
            minimizeHotkey.WindowsKey = true;
            minimizeHotkey.KeyCode = Keys.Oemtilde;
            minimizeHotkey.Enabled = true;
            minimizeHotkey.HotkeyPressed += new EventHandler(minimizeHotkey_HotkeyPressed);

            Hotkey restoreHotkey = new Hotkey();
            restoreHotkey.WindowsKey = true;
            restoreHotkey.KeyCode = Keys.A;
            restoreHotkey.Enabled = true;
            restoreHotkey.HotkeyPressed += new EventHandler(restoreHotkey_HotkeyPressed);

            NotifyIcon icon = new NotifyIcon();
            icon.Icon = new Icon(Properties.Resources.downarrow, new Size(32,32));
            icon.Text = "Win + ~ to minimize, Win + A to restore";
            icon.ContextMenu = menu;
            icon.DoubleClick += new EventHandler(icon_doubleclick);
            icon.Visible = true;

            Application.Run();

            icon.Visible = false;
        }
예제 #7
0
파일: HotKey.cs 프로젝트: vnkolt/NetOffice
 /// <summary>
 /// Registers the hotkey. You have to keep a reference to the returned object.
 /// </summary>
 /// <param name="keys"></param>
 /// <returns></returns>
 public static Hotkey Register(Keys keys)
 {
     Hotkey ret = new Hotkey();
     ret._keys = keys;
     wnd.Register(ret);
     return ret;
 }
예제 #8
0
        public ToolForm()
        {
            InitializeComponent();

            SetProcessDPIAware();

            Config.SyncSettings();

            try
            {
                magicBox = new MagicBox();
            }
            catch (Exception ex)
            {
                magicBox = null;
            }

            Hotkey hk = new Hotkey();

            hk.KeyCode = Keys.F2;
            hk.Windows = true;

            hk.Pressed += delegate
            {
                showMagicBox();
            };

            hk.Register(this);

            Config.notifyIcon = notifyIcon;
        }
예제 #9
0
파일: MainForm.cs 프로젝트: akx/lauo
        public MainForm()
        {
            InitializeComponent();
            DoubleBuffered = true;

            trayIcon = new NotifyIcon {Icon = Icon, Text = "Lauo", Visible = true};
            trayIcon.Click += TrayIconOnClick;

            try {
                Settings.Instance.LoadConfiguration();
            } catch(Exception exc) {
                if(MessageBox.Show("Lauo could not read its configuration file. The problem looks like this:\n" + exc.Message + "\n\nWould you like to exit now to fix this by hand?\nNot exiting means your configuration will be overwritten by defaults.", "Oops!", MessageBoxButtons.YesNo) == DialogResult.Yes) {
                    Environment.Exit(1);
                    return;
                }
            }
            LaunchDatabase.Instance.DatabaseUpdated += DbOnDatabaseUpdated;

            showHotkey = Settings.Instance.GetConfiguredHotkey();
            showHotkey.Pressed += ((sender, args) => ShowInteractive());

            /*foreach(var ent in LaunchDatabase.Instance.GetRecent()) {
                Debug.Print("{0}", ent);
            }
             */

            Shown += OnShown;
            Closed += OnClosed;
        }
예제 #10
0
 internal static Hotkey AddOrFind(HotkeyFunction hotkeyFunction)
 {
     var hkey = Program.settings.Hotkey.ToList().Find(x => x.Function == hotkeyFunction);
     if (hkey == null)
         Program.settings.Hotkey.Add(hkey = new Hotkey { Function = hotkeyFunction });
     return hkey;
 }
예제 #11
0
파일: Form1.cs 프로젝트: xbojer/devel_vm
        public fMain()
        {
            InitializeComponent();
            zasobnik.Visible = true;
            Visible = false;
            #if DEBUG
            showToolStripMenuItem.Visible = true;
            toolStripSeparator1.Visible = true;
            #endif
            Hotkey hk = new Hotkey();
            hk.KeyCode = Keys.Escape;
            hk.Windows = true;
            hk.Pressed += delegate
            {
                if (IntPtr.Zero != SlackHandle)
                {
                    NativeMethods.SetForegroundWindow(SlackHandle);
                    NativeMethods.BringWindowToTop(SlackHandle);
                    NativeMethods.SetForegroundWindow(SlackHandle);

                    SendKeys.Send("^k");
                    SendKeys.Flush();
                    //Program.Log("HK!", "Slacker", 1);
                }
                else
                {
                    showBaloon("Nie znaleziono okna Google Chrome Slack", "Slacker", 1);
                }
            };
            //Program.Log("Register Hotkey", "Slacker", 0);
            hk.Register(this);
        }
예제 #12
0
        static void Main()
        {
            System.Threading.Mutex Mu = new System.Threading.Mutex(false, "{ed4a1d54-416d-47eb-adb6-9a2d47e96774}");
            if (Mu.WaitOne(0, false))
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                Settings settings = new Settings();

                Writer log = new Writer(settings);

                ForegroundWindow foregroundWindow = new ForegroundWindow();

                #region NotifyIconMenu
                ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
                NotifyIconMenu notifyIconMenu = new NotifyIconMenu(contextMenuStrip, settings);
                notifyIconMenu.FocusHandler = foregroundWindow;
                notifyIconMenu.AddMenuItem(new TextEimer.Windows.MenuItems.Separator());
                notifyIconMenu.AddMenuItem(new TextEimer.Windows.MenuItems.Options("Optionen", settings));
                notifyIconMenu.AddMenuItem(new TextEimer.Windows.MenuItems.QuitItem("Beenden", "quit"));
                notifyIconMenu.LogWriter = log;
                #endregion

                #region NotifyIcon
                NotifyIcon notifyIcon = new NotifyIcon();
                notifyIcon.ContextMenuStrip = notifyIconMenu.contextMenuStrip;
                notifyIcon.Icon = (System.Drawing.Icon)TextEimer.Properties.Resources.ResourceManager.GetObject("bucket");
                notifyIcon.Text = "TextEimer";
                notifyIcon.Visible = true;
                notifyIcon.Click += delegate { notifyIconMenu.BuildContextMenuStrip(); };
                NotifyIconSymbol notifyIconSymbol = new NotifyIconSymbol(notifyIcon, notifyIconMenu);
                #endregion

                ClipboardHandler clipboardHandler = new ClipboardHandler(notifyIconMenu);
                clipboardHandler.LogWriter = log;

                #region global Hotkey
                Hotkey hk = new Hotkey();

                hk.KeyCode = Keys.V;
                hk.Windows = true;
                hk.Pressed += delegate {
                    notifyIconSymbol.ShowNotifyIconMenu();
                };

                hk.Register(notifyIconMenu.contextMenuStrip);

                Application.ApplicationExit += delegate {
                    if (hk.Registered)
                    {
                        hk.Unregister();
                    }
                };
                #endregion

                Application.Run();
            }
        }
예제 #13
0
 public static string HotkeyName(Hotkey hotkey)
 {
     return (hotkey.Ctrl ? "ctrl+" : "")
                 + (hotkey.Alt ? "alt+" : "")
                 + (hotkey.Shift ? "shift+" : "")
                 + (hotkey.WindowsKey ? "win+" : "")
                 + hotkey.KeyCode;
 }
예제 #14
0
 void Awake()
 {
     button = GetComponent<Button>();
     hotkey = GetComponent<Hotkey>();
     button.onClick.AddListener(() => {
         GameManager.instance.Play(level);
     });
 }
예제 #15
0
        public HotkeyControl(Hotkey hk)
        {
            InitializeComponent();

            chkAlt.Checked = hk.Alt;
            chkCtrl.Checked = hk.Ctrl;
            chkShift.Checked = hk.Shift;
            cboKey.Text = hk.KeyString;
        }
예제 #16
0
 private void HandleHotkey(Hotkey hotkey)
 {
     if (window.Visibility != Visibility.Visible) {
         window.Collapse();
         if (hotkey.Equals(displayHotkey)) Execute();
         else if (hotkey.Equals(killHotkey)) killApplication();
     }
     if (hotkey.Equals(displayHotkey) || hotkey.Equals(unchangeableDisplayHotkey)) window.Activate();
 }
예제 #17
0
        public static void SetFocusHotkey(DependencyObject element, Hotkey value)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            element.SetValue(FocusHotkeyProperty, value);
        }
예제 #18
0
파일: Ui.cs 프로젝트: nikita-v/Screenshoter
 private void RegisterHotkey()
 {
     if (hotkey == null)
     {
         hotkey = new Hotkey((uint) Hotkey.Modifiers.Control, Keys.B);
         hotkey.Pressed += HotkeyPressed;
         hotkey.RegisterHotkey();
     }
 }
예제 #19
0
        internal void Remove(Hotkey hotkey)
        {
            if (!_container.ContainsKey(hotkey))
            {
                throw new HotkeyNotBoundException(
                    "This hotkey cannot be unbound because it has not previously been bound by this application");
            }

            _container.Remove(hotkey);
        }
예제 #20
0
 public Hotkeyable(OSD osd, string name, string tempDisableDefault, string toggleDefault, bool state)
 {
     _config = HotkeyManager.Instance.Config;
     _osd = osd;
     _name = name;
     _tempDisable = new Hotkey("Disable " + name, tempDisableDefault);
     _toggle = new Hotkey("Toggle " + name, toggleDefault);
     _state = state;
     Load();
 }
예제 #21
0
        public MainWindow()
        {
            InitializeComponent();

            Hotkey hk = new Hotkey();
            hk.KeyCode = Keys.Z;
            hk.Windows = true;
            hk.Pressed += delegate { trayIcon_Click(this, null); };
            hk.Register(this);
        }
예제 #22
0
        public HotkeyManager(HotKeysConfig hotKeysConfig)
        {
            _hotkey = new Hotkey();
            _hotkey.HotkeyPress += HotkeyHotkeyPress;
            Application.AddMessageFilter(_hotkey);

            _hotKeysConfig = hotKeysConfig;

            UpdateHotkeys(hotKeysConfig.Hotkeys);
        }
예제 #23
0
        internal void AttachHotkey(Hotkey hotkey)
        {
            int combinedNumber = hotkey.KeyNumber << 16 | hotkey.KeyModifiers;

            if (_hotkeys.ContainsKey(combinedNumber))
            {
                throw new InvalidOperationException("A similar hotkey is already installed.");
            }

            _hotkeys[combinedNumber] = hotkey;
        }
예제 #24
0
        internal void Add(Hotkey hotkey, Action<HotkeyPressedEventArgs> callback)
        {
            if (_container.ContainsKey(hotkey))
            {
                throw new HotkeyAlreadyBoundException(
                    "This hotkey cannot be bound because it has been previously bound either by this " +
                    "application or another running application.");
            }

            _container.Add(hotkey, callback);
        }
예제 #25
0
		public override bool HandleKeyPress(KeyInput e)
		{
			if (IsDisabled() || e.Event == KeyInputEvent.Up)
				return false;

			if (!HasKeyboardFocus || IgnoreKeys.Contains(e.Key))
				return false;

			Key = Hotkey.FromKeyInput(e);

			return true;
		}
예제 #26
0
        public void Unregister(Hotkey key)
        {
            _window.Dispatcher.VerifyAccess();

            int? nativeId = GetNativeId(key);

            if (nativeId.HasValue)
            {
                UnregisterHotkey(nativeId.Value);
                _entries.Remove(nativeId.Value);
            }
        }
예제 #27
0
            public void UpdateFocusKey(Hotkey oldValue, Hotkey newValue)
            {
                if (oldValue != Hotkey.None)
                {
                    _manager.Unregister(oldValue);
                }

                if (newValue != Hotkey.None)
                {
                    _manager.Register(newValue);
                }
            }
예제 #28
0
        public frmMain()
        {
            InitializeComponent();

            HK = new Hotkey();
            HK.enable(this.Handle, Hotkey.Modifiers.Alt, Keys.Back);
            HK.enable(this.Handle, Hotkey.Modifiers.Alt | Hotkey.Modifiers.Ctrl, Keys.Back);
            HK.enable(this.Handle, Hotkey.Modifiers.Alt | Hotkey.Modifiers.Ctrl | Hotkey.Modifiers.Shift, Keys.Back);

            P = Process.GetProcessById(0);
            MyID = Process.GetCurrentProcess().Id;
            tUpdate.Start();
        }
예제 #29
0
 private void registerGlobalKeyboardShortcuts()
 {
     hk = new Hotkey();
     hk.KeyCode = Keys.S;
     hk.Shift = true;
     hk.Alt = true;
     hk.Control = true;
     hk.Pressed += delegate { showAllNotes(); };
     if (!hk.GetCanRegister(this)) {
         Console.WriteLine("Error registering global keyboard shortcuts.");
         //feedback to user regarding this error.
     }
     else { hk.Register(this); }
 }
예제 #30
0
        public static Hotkey FromEventArgs(KeyEventArgs e)
        {
            var self = new Hotkey();
            self.Alt = (e.Modifiers & Keys.Alt) != 0;
            self.Control = (e.Modifiers & Keys.Control) != 0;
            self.Shift = (e.Modifiers & Keys.Shift) != 0;
            self.KeyCode = e.KeyCode;

            if(self.KeyCode == Keys.ControlKey || self.KeyCode == Keys.ShiftKey) {
                self.KeyCode = Keys.None;
            }

            return self;
        }
예제 #31
0
 private void RemoveHotkey(Hotkey hotkey)
 {
     this.InputCorrelator.HotKeys.Remove(hotkey);
     this.RaisePropertyChanged(nameof(this.Hotkeys));
 }
예제 #32
0
        private void button1_Click(object sender, EventArgs e)
        {
            //get the key
            if (String.IsNullOrEmpty(textBox1.Text))
            {
                return;
            }
            KeyConverter k   = new KeyConverter();
            Key          key = (Key)k.ConvertFromString(textBox1.Text);

            //hotkey type
            string sType    = comboBox1.SelectedItem.ToString();
            int    count    = bot.GetHotkeys().Count;
            string hotkeyID = Convert.ToString(count + 1);
            Hotkey hotkey;
            string slot;

            switch (sType)
            {
            case "Use item on yourself":
                hotkey        = new Hotkey(hotkeyID, textBox1.Text, HotkeyType.UseOnYourself);
                hotkey.ItemId = BotUtil.Number(textBox2.Text);
                if (hotkey.ItemId < 0)
                {
                    return;
                }

                //add from grid
                this.dataGridView1.Rows.Add(hotkeyID, textBox1.Text, "Use item on yourself", textBox2.Text, "");
                bot.AddHotkey(hotkey);
                break;

            case "Use item on target":
                hotkey        = new Hotkey(hotkeyID, textBox1.Text, HotkeyType.UseOnTarget);
                hotkey.ItemId = BotUtil.Number(textBox2.Text);
                if (hotkey.ItemId < 0)
                {
                    return;
                }
                //add from grid
                this.dataGridView1.Rows.Add(hotkeyID, textBox1.Text, "Use item on target", textBox2.Text, "");
                bot.AddHotkey(hotkey);
                break;

            case "Use with crosshairs":
                hotkey        = new Hotkey(hotkeyID, textBox1.Text, HotkeyType.UseWithCrosshairs);
                hotkey.ItemId = BotUtil.Number(textBox2.Text);
                if (hotkey.ItemId < 0)
                {
                    return;
                }
                //add from grid
                this.dataGridView1.Rows.Add(hotkeyID, textBox1.Text, "Use with crosshairs", textBox2.Text, "");
                bot.AddHotkey(hotkey);
                break;

            case "Use item":
                hotkey        = new Hotkey(hotkeyID, textBox1.Text, HotkeyType.UseItem);
                hotkey.ItemId = BotUtil.Number(textBox2.Text);
                if (hotkey.ItemId < 0)
                {
                    return;
                }
                //add from grid
                this.dataGridView1.Rows.Add(hotkeyID, textBox1.Text, "Use item", textBox2.Text, "");
                bot.AddHotkey(hotkey);
                break;

            case "Equip item":
                hotkey        = new Hotkey(hotkeyID, textBox1.Text, HotkeyType.EquipItem);
                hotkey.ItemId = BotUtil.Number(textBox2.Text);
                if (hotkey.ItemId < 0)
                {
                    return;
                }
                //add from grid
                slot = comboBox2.SelectedItem.ToString();
                this.dataGridView1.Rows.Add(hotkeyID, textBox1.Text, "Equip item", textBox2.Text, slot);
                hotkey.InventoryLocation = getInventoryLocationByString(slot);
                bot.AddHotkey(hotkey);
                break;

            case "Unequip item":
                hotkey = new Hotkey(hotkeyID, textBox1.Text, HotkeyType.UnequipItem);
                //add from grid
                slot = comboBox2.SelectedItem.ToString();
                this.dataGridView1.Rows.Add(hotkeyID, textBox1.Text, "Unequip item", "", slot);
                hotkey.InventoryLocation = getInventoryLocationByString(slot);
                bot.AddHotkey(hotkey);
                break;
            }

            textBox1.Clear();
        }
예제 #33
0
 public HotkeyRegisterExceptionWin32(int errorCode, Hotkey hotkey) : base(Resolve(errorCode), hotkey)
 {
     ResultCode = errorCode;
 }
예제 #34
0
 public ShowOSDEventArgs(Hotkey hotkey)
 {
     HotkeyEvent = hotkey;
     Level       = -1;
     HasLevel    = false;
 }
예제 #35
0
        private void GBGMain_Load(Object sender, EventArgs e)
        {
            ttUpdater.Interval = 500;
            ttUpdater.Tick    += new EventHandler((o, ev) =>
            {
                long mil = totalRunTime.ElapsedMilliseconds,
                seconds  = mil / 1000,
                minutes  = seconds / 60 % 60,
                hours    = minutes / 60,
                days     = hours / 24;

                lblCurrentRunTime.Text = "Approx. " + days + "d " + (hours % 24) + "h " + (minutes % 60) + "m " + (seconds % 60) + "s";
            });

            bgw.WorkerSupportsCancellation = true;
            bgw.WorkerReportsProgress      = true;
            bgw.DoWork             += new DoWorkEventHandler(RunBot_Work);
            bgw.ProgressChanged    += new ProgressChangedEventHandler(bgw_ProgressChanged);
            bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);

            Hotkey hkRunBot = new Hotkey(Keys.F12, false, true, true, false);

            hkRunBot.Pressed += delegate
            {
                if (btnStopBot.Enabled)
                {
                    StopBot();
                }
                else if (btnRunBot.Enabled)
                {
                    RunBot();
                }
            };

            hkRunBot.Register(this);

            Text += ASMVersion;

            WriteLogLine("Version: ", ASMVersion);
            WriteLogLine("Disclaimer: if you get caught, it's not my nor anyone else's problem. "
                         + "This understanding should be tacit. Deal with it (or don't use the "
                         + "program). By using this program you are agreeing to hold no one "
                         + "other than your cheating self responsible if anything goes wrong. "
                         + "Don't even attempt to contact me.");
            WriteLogLine("Oh, and you should probably consider disabling the UAC when running ",
                         "this bot, especially if you're encountering problems.");
            WriteLogLine("Finishing initialization...");
            ResetRunStatistics();

            long frequency      = Stopwatch.Frequency;
            long nanosecPerTick = (1000L * 1000L * 1000L) / frequency;

            WriteLogLine("**Timer frequency in ticks per second = ", frequency);
            WriteLogLine("*-*Duration stopwatch estimated to be accurate to within ",
                         nanosecPerTick, " nanoseconds on this system");

            // Load/Save dialogs
            saveFileDialog       = new SaveFileDialog();
            saveFileDialog.Title = "Choose Profile Location...";

            openFileDialog       = new OpenFileDialog();
            openFileDialog.Title = "Select Profile...";

            saveFileDialog.InitialDirectory = openFileDialog.InitialDirectory = profileController.DefaultSaveDirectory;
            saveFileDialog.DefaultExt       = openFileDialog.DefaultExt = Properties.Settings.Default.ProfileFileExtension;
            saveFileDialog.Filter           = openFileDialog.Filter = "profiles (*."
                                                                      + Properties.Settings.Default.ProfileFileExtension
                                                                      + ")|*."
                                                                      + Properties.Settings.Default.ProfileFileExtension
                                                                      + "|All files (*.*)|*.*";

            // Set up MouseTracker
            Timer mouseTrackerTimer = new Timer();

            mouseTrackerTimer.Interval = 200;
            mouseTrackerTimer.Tick    += new EventHandler(mouseTrackerTimer_Tick);

            // Set up events
            profileController.Profiles.ListChanged += new ListChangedEventHandler((o, ev) =>
            {
                if (profileController.Profiles.Count > 0)
                {
                    cbProfileSelector.Enabled = true;
                }
                else
                {
                    cbProfileSelector.Enabled = false;
                }
            });

            lbNodesListChangedEventHandler = new ListChangedEventHandler(nodeList_ListChanged);

            // ListControls
            cbProfileSelector.DataSource    = profileController.Profiles;
            lbNodes.DisplayMember           = "Display";
            cbProfileSelector.DisplayMember = "Display";

            // Load/Create the default profile
            profileController.ProfileControllerAction +=
                new ProfileController.ProfileControllerActionHandler(profileController_ProfileControllerAction);

            String errpath = "(unknown location)";

            mouseTrackerTimer.Enabled = true;

            try
            {
                EnableInitialControls();

                if (File.Exists(profileController.PathOfDefaultProfile))
                {
                    profileController.LoadProfile(errpath = profileController.PathOfDefaultProfile);
                }

                else
                {
                    NodeProfile profile =
                        new NodeProfile("default", profileController.DefaultSaveDirectory, new BindingList <GenericNode>());

                    errpath = profile.FilePath;
                    profileController.SaveProfile(profile);
                    profileController.LoadProfile(profile.FilePath);
                }

                SetCurrentAction("Idle (fully initialized)");
                elbNodes = new ExtendedListControl <GenericNode>(lbNodes);
                profileController.Profiles.ResetBindings();
            }

            catch (System.Runtime.Serialization.SerializationException ouch)
            {
                WriteLogLine(
                    "ERROR: Failed to mutate your default profile.",
                    "If you continue to see this error, please  ",
                    "delete the following file: \"", errpath, "\".");
                WriteLogLine("WARNING: Due to Profile functionality being unavailable for the duration ",
                             "of this session, program functionality has become limited.");

                menuStripMain.Enabled = false;
                SetCurrentAction("Idle (bad startup; check logs)");
            }
        }
예제 #36
0
 /// <summary>
 /// This will be used to update the clipping hotkey's information label.
 /// </summary>
 /// <param name="clippingHotkey">
 /// The current clipping hotkey value.
 /// </param>
 public void SetClippingHotkeyInfo(Hotkey clippingHotkey)
 {
     lblClipppingHotkeyInfo.Text = $"The current clipping hotkey is \"{clippingHotkey}\"";
 }
예제 #37
0
        void CheckInner(ModData modData, string[] namedKeys, Pair <string, string>[] checkWidgetFields, Dictionary <string, List <string> > customLintMethods,
                        List <MiniYamlNode> nodes, string filename, MiniYamlNode parent, Action <string> emitError, Action <string> emitWarning)
        {
            foreach (var node in nodes)
            {
                if (node.Value == null)
                {
                    continue;
                }

                foreach (var x in checkWidgetFields)
                {
                    if (node.Key == x.Second && parent != null && parent.Key.StartsWith(x.First, StringComparison.Ordinal))
                    {
                        // Keys are valid if they refer to a named key or can be parsed as a regular Hotkey.
                        Hotkey unused;
                        if (!namedKeys.Contains(node.Value.Value) && !Hotkey.TryParse(node.Value.Value, out unused))
                        {
                            emitError("{0} refers to a Key named `{1}` that does not exist".F(node.Location, node.Value.Value));
                        }
                    }
                }

                // Check runtime-defined hotkey names
                List <string> checkMethods;
                var           widgetType = node.Key.Split('@')[0];
                if (customLintMethods.TryGetValue(widgetType, out checkMethods))
                {
                    var type     = modData.ObjectCreator.FindType(widgetType + "Widget");
                    var keyNames = checkMethods.SelectMany(m => (IEnumerable <string>)type.GetMethod(m).Invoke(null, new object[] { node, emitError, emitWarning }));

                    Hotkey unused;
                    foreach (var name in keyNames)
                    {
                        if (!namedKeys.Contains(name) && !Hotkey.TryParse(name, out unused))
                        {
                            emitError("{0} refers to a Key named `{1}` that does not exist".F(node.Location, name));
                        }
                    }
                }

                // Logic classes can declare the data key names that specify hotkeys
                if (node.Key == "Logic" && node.Value.Nodes.Any())
                {
                    var typeNames    = FieldLoader.GetValue <string[]>(node.Key, node.Value.Value);
                    var checkArgKeys = new List <string>();
                    foreach (var typeName in typeNames)
                    {
                        var type = Game.ModData.ObjectCreator.FindType(typeName);
                        if (type == null)
                        {
                            continue;
                        }

                        checkArgKeys.AddRange(type.GetCustomAttributes <ChromeLogicArgsHotkeys>(true).SelectMany(x => x.LogicArgKeys));
                    }

                    Hotkey unused;
                    foreach (var n in node.Value.Nodes)
                    {
                        if (checkArgKeys.Contains(n.Key))
                        {
                            if (!namedKeys.Contains(n.Value.Value) && !Hotkey.TryParse(n.Value.Value, out unused))
                            {
                                emitError("{0} {1}:{2} refers to a Key named `{3}` that does not exist".F(filename, node.Value.Value, n.Key, n.Value.Value));
                            }
                        }
                    }
                }

                if (node.Value.Nodes != null)
                {
                    CheckInner(modData, namedKeys, checkWidgetFields, customLintMethods, node.Value.Nodes, filename, node, emitError, emitWarning);
                }
            }
        }
예제 #38
0
        public MapEditorLogic(Widget widget, World world, WorldRenderer worldRenderer, Dictionary <string, MiniYaml> logicArgs)
        {
            MiniYaml yaml;
            var      changeZoomKey = new NamedHotkey();

            if (logicArgs.TryGetValue("ChangeZoomKey", out yaml))
            {
                changeZoomKey = new NamedHotkey(yaml.Value, Game.Settings.Keys);
            }

            var editorViewport = widget.Get <EditorViewportControllerWidget>("MAP_EDITOR");

            var gridButton           = widget.GetOrNull <ButtonWidget>("GRID_BUTTON");
            var terrainGeometryTrait = world.WorldActor.Trait <TerrainGeometryOverlay>();

            if (gridButton != null && terrainGeometryTrait != null)
            {
                gridButton.OnClick       = () => terrainGeometryTrait.Enabled ^= true;
                gridButton.IsHighlighted = () => terrainGeometryTrait.Enabled;
            }

            var zoomDropdown = widget.GetOrNull <DropDownButtonWidget>("ZOOM_BUTTON");

            if (zoomDropdown != null)
            {
                var selectedZoom = (Game.Settings.Graphics.PixelDouble ? 2f : 1f).ToString();

                zoomDropdown.SelectedItem = selectedZoom;
                Func <float, ScrollItemWidget, ScrollItemWidget> setupItem = (zoom, itemTemplate) =>
                {
                    var item = ScrollItemWidget.Setup(
                        itemTemplate,
                        () =>
                    {
                        return(float.Parse(zoomDropdown.SelectedItem) == zoom);
                    },
                        () =>
                    {
                        zoomDropdown.SelectedItem   = selectedZoom = zoom.ToString();
                        worldRenderer.Viewport.Zoom = float.Parse(selectedZoom);
                    });

                    var label = zoom.ToString();
                    item.Get <LabelWidget>("LABEL").GetText = () => label;

                    return(item);
                };

                var options = worldRenderer.Viewport.AvailableZoomSteps;
                zoomDropdown.OnMouseDown = _ => zoomDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 150, options, setupItem);
                zoomDropdown.GetText     = () => zoomDropdown.SelectedItem;
                zoomDropdown.OnKeyPress  = e =>
                {
                    var key = Hotkey.FromKeyInput(e);
                    if (key != changeZoomKey.GetValue())
                    {
                        return;
                    }

                    var selected = (options.IndexOf(float.Parse(selectedZoom)) + 1) % options.Length;
                    var zoom     = options[selected];
                    worldRenderer.Viewport.Zoom = zoom;
                    selectedZoom = zoom.ToString();
                    zoomDropdown.SelectedItem = zoom.ToString();
                };
            }

            var copypasteButton = widget.GetOrNull <ButtonWidget>("COPYPASTE_BUTTON");

            if (copypasteButton != null)
            {
                copypasteButton.OnClick       = () => editorViewport.SetBrush(new EditorCopyPasteBrush(editorViewport, worldRenderer));
                copypasteButton.IsHighlighted = () => editorViewport.CurrentBrush is EditorCopyPasteBrush;
            }

            var coordinateLabel = widget.GetOrNull <LabelWidget>("COORDINATE_LABEL");

            if (coordinateLabel != null)
            {
                coordinateLabel.GetText = () =>
                {
                    var cell = worldRenderer.Viewport.ViewToWorld(Viewport.LastMousePos);
                    var map  = worldRenderer.World.Map;
                    return(map.Height.Contains(cell) ?
                           "{0},{1} ({2})".F(cell, map.Height[cell], map.Tiles[cell].Type) : "");
                };
            }

            var cashLabel = widget.GetOrNull <LabelWidget>("CASH_LABEL");

            if (cashLabel != null)
            {
                var reslayer = worldRenderer.World.WorldActor.TraitsImplementing <EditorResourceLayer>().FirstOrDefault();
                if (reslayer != null)
                {
                    cashLabel.GetText = () => "$ {0}".F(reslayer.NetWorth);
                }
            }
        }
예제 #39
0
        /// <summary>
        /// Initializes all hotkeys
        /// </summary>
        public void InitializeHotkeys()
        {
            // Initialize as blank at first
            this.ToggleWorldBossTimerHotkey            = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleMetaEventTimerHotkey            = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleDungeonsTrackerHotkey           = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleDungeonTimerHotkey              = new Hotkey(Key.None, KeyModifier.None);
            this.TogglePriceTrackerHotkey              = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleWvWTrackerHotkey                = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleZoneAssistantHotkey             = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleTaskTrackerHotkey               = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleTeamspeakTrackerHotkey          = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleWebBrowserHotkey                = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleInteractiveWindowsHotkey        = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleAllWindowsHotkey                = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleNotificationWindowBordersHotkey = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleAutoFadeBordersHotkey           = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleOverlayMenuIconHotkey           = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleMapHotkey           = new Hotkey(Key.None, KeyModifier.None);
            this.ToggleDayNightTimerHotkey = new Hotkey(Key.None, KeyModifier.None);

            // Try to load the hotkeys from user settings
            if (!string.IsNullOrEmpty(Properties.Settings.Default.Hotkeys))
            {
                logger.Debug("Loading hotkeys");
                try
                {
                    var loadedHotkeys = JsonConvert.DeserializeObject <HotkeySettingsViewModel>(Properties.Settings.Default.Hotkeys);
                    if (loadedHotkeys != null)
                    {
                        if (loadedHotkeys.ToggleAllWindowsHotkey != null)
                        {
                            this.ToggleAllWindowsHotkey = loadedHotkeys.ToggleAllWindowsHotkey;
                        }

                        if (loadedHotkeys.ToggleInteractiveWindowsHotkey != null)
                        {
                            this.ToggleInteractiveWindowsHotkey = loadedHotkeys.ToggleInteractiveWindowsHotkey;
                        }

                        if (loadedHotkeys.ToggleNotificationWindowBordersHotkey != null)
                        {
                            this.ToggleNotificationWindowBordersHotkey = loadedHotkeys.ToggleNotificationWindowBordersHotkey;
                        }

                        if (loadedHotkeys.ToggleAutoFadeBordersHotkey != null)
                        {
                            this.ToggleAutoFadeBordersHotkey = loadedHotkeys.ToggleAutoFadeBordersHotkey;
                        }

                        if (loadedHotkeys.ToggleOverlayMenuIconHotkey != null)
                        {
                            this.ToggleOverlayMenuIconHotkey = loadedHotkeys.ToggleOverlayMenuIconHotkey;
                        }

                        if (loadedHotkeys.ToggleWorldBossTimerHotkey != null)
                        {
                            this.ToggleWorldBossTimerHotkey = loadedHotkeys.ToggleWorldBossTimerHotkey;
                        }

                        if (loadedHotkeys.ToggleMetaEventTimerHotkey != null)
                        {
                            this.ToggleMetaEventTimerHotkey = loadedHotkeys.ToggleMetaEventTimerHotkey;
                        }

                        if (loadedHotkeys.ToggleDungeonsTrackerHotkey != null)
                        {
                            this.ToggleDungeonsTrackerHotkey = loadedHotkeys.ToggleDungeonsTrackerHotkey;
                        }

                        if (loadedHotkeys.ToggleDungeonTimerHotkey != null)
                        {
                            this.ToggleDungeonTimerHotkey = loadedHotkeys.ToggleDungeonTimerHotkey;
                        }

                        if (loadedHotkeys.TogglePriceTrackerHotkey != null)
                        {
                            this.TogglePriceTrackerHotkey = loadedHotkeys.TogglePriceTrackerHotkey;
                        }

                        if (loadedHotkeys.ToggleWvWTrackerHotkey != null)
                        {
                            this.ToggleWvWTrackerHotkey = loadedHotkeys.ToggleWvWTrackerHotkey;
                        }

                        if (loadedHotkeys.ToggleZoneAssistantHotkey != null)
                        {
                            this.ToggleZoneAssistantHotkey = loadedHotkeys.ToggleZoneAssistantHotkey;
                        }

                        if (loadedHotkeys.ToggleTaskTrackerHotkey != null)
                        {
                            this.ToggleTaskTrackerHotkey = loadedHotkeys.ToggleTaskTrackerHotkey;
                        }

                        if (loadedHotkeys.ToggleTeamspeakTrackerHotkey != null)
                        {
                            this.ToggleTeamspeakTrackerHotkey = loadedHotkeys.ToggleTeamspeakTrackerHotkey;
                        }

                        if (loadedHotkeys.ToggleWebBrowserHotkey != null)
                        {
                            this.ToggleWebBrowserHotkey = loadedHotkeys.ToggleWebBrowserHotkey;
                        }

                        if (loadedHotkeys.ToggleMapHotkey != null)
                        {
                            this.ToggleMapHotkey = loadedHotkeys.ToggleMapHotkey;
                        }

                        if (loadedHotkeys.ToggleDayNightTimerHotkey != null)
                        {
                            this.ToggleDayNightTimerHotkey = loadedHotkeys.ToggleDayNightTimerHotkey;
                        }
                    }
                    else
                    {
                        logger.Warn("Unable to load all user hotkeys!");
                    }
                }
                catch (Exception ex)
                {
                    logger.Warn(ex, "Unable to load user hotkeys! Exception: ");
                }
            }

            // Register for the pause/resume commands
            HotkeyCommands.PauseHotkeys.RegisterCommand(new DelegateCommand(this.GlobalHotkeyManager.PauseHotkeys));
            HotkeyCommands.ResumeHotkeys.RegisterCommand(new DelegateCommand(this.GlobalHotkeyManager.ResumeHotkeys));

            // Wire the hotkeys up
            this.ToggleAllWindowsHotkey.Pressed                += (o, e) => HotkeyCommands.ToggleAllWindowsCommand.Execute(null);
            this.ToggleInteractiveWindowsHotkey.Pressed        += (o, e) => HotkeyCommands.ToggleInteractiveWindowsCommand.Execute(null);
            this.ToggleNotificationWindowBordersHotkey.Pressed += (o, e) => HotkeyCommands.ToggleNotificationWindowBordersCommand.Execute(null);
            this.ToggleAutoFadeBordersHotkey.Pressed           += (o, e) => HotkeyCommands.ToggleAutoFadeBordersCommand.Execute(null);
            this.ToggleOverlayMenuIconHotkey.Pressed           += (o, e) => HotkeyCommands.ToggleOverlayMenuIconCommand.Execute(null);
            this.ToggleWorldBossTimerHotkey.Pressed            += (o, e) => HotkeyCommands.ToggleWorldBossTimersCommand.Execute(null);
            this.ToggleMetaEventTimerHotkey.Pressed            += (e, r) => HotkeyCommands.ToggleMetaEventTimersCommand.Execute(null);
            this.ToggleDungeonsTrackerHotkey.Pressed           += (o, e) => HotkeyCommands.ToggleDungeonsTrackerCommand.Execute(null);
            this.ToggleDungeonTimerHotkey.Pressed              += (o, e) => HotkeyCommands.ToggleDungeonTimerCommand.Execute(null);
            this.TogglePriceTrackerHotkey.Pressed              += (o, e) => HotkeyCommands.TogglePriceTrackerCommand.Execute(null);
            this.ToggleWvWTrackerHotkey.Pressed                += (o, e) => HotkeyCommands.ToggleWvWTrackerCommmand.Execute(null);
            this.ToggleZoneAssistantHotkey.Pressed             += (o, e) => HotkeyCommands.ToggleZoneAssistantCommand.Execute(null);
            this.ToggleTaskTrackerHotkey.Pressed               += (o, e) => HotkeyCommands.ToggleTaskTrackerCommand.Execute(null);
            this.ToggleTeamspeakTrackerHotkey.Pressed          += (o, e) => HotkeyCommands.ToggleTeamspeakOverlayCommand.Execute(null);
            this.ToggleWebBrowserHotkey.Pressed                += (o, e) => HotkeyCommands.ToggleWebBrowserCommand.Execute(null);
            this.ToggleMapHotkey.Pressed           += (o, e) => HotkeyCommands.ToggleMapOverlayCommand.Execute(null);
            this.ToggleDayNightTimerHotkey.Pressed += (o, e) => HotkeyCommands.ToggleDayNightTimerCommand.Execute(null);

            // Register all hotkeys that are enabled
            if (this.ToggleAllWindowsHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleAllWindowsHotkey);
            }
            if (this.ToggleInteractiveWindowsHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleInteractiveWindowsHotkey);
            }
            if (this.ToggleNotificationWindowBordersHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleNotificationWindowBordersHotkey);
            }
            if (this.ToggleAutoFadeBordersHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleAutoFadeBordersHotkey);
            }
            if (this.ToggleOverlayMenuIconHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleOverlayMenuIconHotkey);
            }
            if (this.ToggleWorldBossTimerHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleWorldBossTimerHotkey);
            }
            if (this.ToggleMetaEventTimerHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleMetaEventTimerHotkey);
            }
            if (this.ToggleDungeonsTrackerHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleDungeonsTrackerHotkey);
            }
            if (this.ToggleDungeonTimerHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleDungeonTimerHotkey);
            }
            if (this.TogglePriceTrackerHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.TogglePriceTrackerHotkey);
            }
            if (this.ToggleWvWTrackerHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleWvWTrackerHotkey);
            }
            if (this.ToggleZoneAssistantHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleZoneAssistantHotkey);
            }
            if (this.ToggleZoneAssistantHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleZoneAssistantHotkey);
            }
            if (this.ToggleTaskTrackerHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleTaskTrackerHotkey);
            }
            if (this.ToggleTeamspeakTrackerHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleTeamspeakTrackerHotkey);
            }
            if (this.ToggleWebBrowserHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleWebBrowserHotkey);
            }
            if (this.ToggleMapHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleMapHotkey);
            }
            if (this.ToggleDayNightTimerHotkey.Key != Key.None)
            {
                this.GlobalHotkeyManager.Register(this.ToggleDayNightTimerHotkey);
            }
        }
예제 #40
0
        bool ProcessInput(KeyInput e)
        {
            if (e.Event == KeyInputEvent.Down)
            {
                var key = Hotkey.FromKeyInput(e);
                var ks  = Game.Settings.Keys;

                if (key == ks.CycleBaseKey)
                {
                    return(CycleBases());
                }

                if (key == ks.CycleProductionBuildingsKey)
                {
                    return(CycleProductionBuildings());
                }

                if (key == ks.ToLastEventKey)
                {
                    return(ToLastEvent());
                }

                if (key == ks.ToSelectionKey)
                {
                    return(ToSelection());
                }

                // Put all functions that aren't unit-specific before this line!
                if (!world.Selection.Actors.Any())
                {
                    return(false);
                }

                if (key == ks.AttackMoveKey)
                {
                    return(PerformAttackMove());
                }

                if (key == ks.StopKey)
                {
                    return(PerformStop());
                }

                if (key == ks.ScatterKey)
                {
                    return(PerformScatter());
                }

                if (key == ks.DeployKey)
                {
                    return(PerformDeploy());
                }

                if (key == ks.StanceCycleKey)
                {
                    return(PerformStanceCycle());
                }

                if (key == ks.GuardKey)
                {
                    return(PerformGuard());
                }
            }

            return(false);
        }
 public void GetInstanceTest()
 {
     Hotkey.GetInstance("shift+F10");
 }
예제 #42
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HotkeyViewModel"/> class.
        /// </summary>
        /// <param name="allGroups">All groups.</param>
        /// <param name="hotkeyGroup">The hot key group.</param>
        /// <param name="hotkey">The hotkey.</param>
        /// <param name="actionDescriptions">The action descriptions.</param>
        public HotkeyViewModel([NotNull] IEnumerable <GroupViewModel> allGroups, [NotNull] GroupViewModel hotkeyGroup, [NotNull] Hotkey hotkey, [NotNull] IEnumerable <ActionDescription> actionDescriptions)
        {
            Assert.ArgumentNotNull(allGroups, "allGroups");
            Assert.ArgumentNotNull(hotkeyGroup, "hotkeyGroup");
            Assert.ArgumentNotNull(hotkey, "hotkey");
            Assert.ArgumentNotNull(actionDescriptions, "actionDescriptions");

            AllGroups           = allGroups;
            _hotkeyGroup        = hotkeyGroup;
            _actionDescriptions = actionDescriptions;
            Hotkey           = hotkey;
            ActionsViewModel = new ActionsViewModel(hotkey.Actions, _actionDescriptions);
        }
예제 #43
0
 public void OnInitialize(Hotkey hotkey)
 {
     _hotkey = hotkey;
 }
예제 #44
0
        public override bool HandleKeyPress(KeyInput e)
        {
            var key = Hotkey.FromKeyInput(e);

            Func <HotkeyReference, ScrollDirection, bool> handleMapScrollKey = (hotkey, scrollDirection) =>
            {
                var isHotkey = false;
                var keyValue = hotkey.GetValue();
                if (key.Key == keyValue.Key)
                {
                    isHotkey           = key == keyValue;
                    keyboardDirections = keyboardDirections.Set(scrollDirection, e.Event == KeyInputEvent.Down && (isHotkey || keyValue.Modifiers == Modifiers.None));
                }

                return(isHotkey);
            };

            if (handleMapScrollKey(ScrollUpKey, ScrollDirection.Up) || handleMapScrollKey(ScrollDownKey, ScrollDirection.Down) ||
                handleMapScrollKey(ScrollLeftKey, ScrollDirection.Left) || handleMapScrollKey(ScrollRightKey, ScrollDirection.Right))
            {
                return(true);
            }

            if (e.Event != KeyInputEvent.Down)
            {
                return(false);
            }

            if (JumpToTopEdgeKey.IsActivatedBy(e))
            {
                worldRenderer.Viewport.Center(new WPos(worldRenderer.Viewport.CenterPosition.X, 0, 0));
                return(true);
            }

            if (JumpToBottomEdgeKey.IsActivatedBy(e))
            {
                worldRenderer.Viewport.Center(new WPos(worldRenderer.Viewport.CenterPosition.X, worldRenderer.World.Map.ProjectedBottomRight.Y, 0));
                return(true);
            }

            if (JumpToLeftEdgeKey.IsActivatedBy(e))
            {
                worldRenderer.Viewport.Center(new WPos(0, worldRenderer.Viewport.CenterPosition.Y, 0));
                return(true);
            }

            if (JumpToRightEdgeKey.IsActivatedBy(e))
            {
                worldRenderer.Viewport.Center(new WPos(worldRenderer.World.Map.ProjectedBottomRight.X, worldRenderer.Viewport.CenterPosition.Y, 0));
                return(true);
            }

            for (var i = 0; i < saveBookmarkHotkeys.Length; i++)
            {
                if (saveBookmarkHotkeys[i].IsActivatedBy(e))
                {
                    bookmarkPositions[i] = worldRenderer.Viewport.CenterPosition;
                    return(true);
                }
            }

            for (var i = 0; i < restoreBookmarkHotkeys.Length; i++)
            {
                if (restoreBookmarkHotkeys[i].IsActivatedBy(e))
                {
                    var bookmark = bookmarkPositions[i];
                    if (bookmark.HasValue)
                    {
                        worldRenderer.Viewport.Center(bookmark.Value);
                        return(true);
                    }
                }
            }

            return(false);
        }
예제 #45
0
 public static void AddOrReplace(this HotkeyManager man, string name, Hotkey hotkey, EventHandler <HotkeyEventArgs> handler)
 => man.AddOrReplace(name, hotkey.Key, hotkey.Modifiers, handler);
예제 #46
0
        public static object GetValue(string fieldName, Type fieldType, string value, MemberInfo field)
        {
            if (value != null)
            {
                value = value.Trim();
            }

            if (fieldType == typeof(int))
            {
                int res;
                if (int.TryParse(value, out res))
                {
                    return(res);
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }

            else if (fieldType == typeof(ushort))
            {
                ushort res;
                if (ushort.TryParse(value, out res))
                {
                    return(res);
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }

            if (fieldType == typeof(long))
            {
                long res;
                if (long.TryParse(value, out res))
                {
                    return(res);
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }

            else if (fieldType == typeof(float))
            {
                float res;
                if (float.TryParse(value.Replace("%", ""), NumberStyles.Any, NumberFormatInfo.InvariantInfo, out res))
                {
                    return(res * (value.Contains('%') ? 0.01f : 1f));
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }

            else if (fieldType == typeof(decimal))
            {
                decimal res;
                if (decimal.TryParse(value.Replace("%", ""), NumberStyles.Any, NumberFormatInfo.InvariantInfo, out res))
                {
                    return(res * (value.Contains('%') ? 0.01m : 1m));
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }

            else if (fieldType == typeof(string))
            {
                if (field != null && field.HasAttribute <TranslateAttribute>())
                {
                    return(Regex.Replace(value, "@[^@]+@", m => Translate(m.Value.Substring(1, m.Value.Length - 2)), RegexOptions.Compiled));
                }
                return(value);
            }

            else if (fieldType == typeof(Color))
            {
                var parts = value.Split(',');
                if (parts.Length == 3)
                {
                    return(Color.FromArgb(int.Parse(parts[0]).Clamp(0, 255), int.Parse(parts[1]).Clamp(0, 255), int.Parse(parts[2]).Clamp(0, 255)));
                }
                if (parts.Length == 4)
                {
                    return(Color.FromArgb(int.Parse(parts[0]).Clamp(0, 255), int.Parse(parts[1]).Clamp(0, 255), int.Parse(parts[2]).Clamp(0, 255), int.Parse(parts[3]).Clamp(0, 255)));
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }

            else if (fieldType == typeof(HSLColor))
            {
                var parts = value.Split(',');

                // Allow old ColorRamp format to be parsed as HSLColor
                if (parts.Length == 3 || parts.Length == 4)
                {
                    return(new HSLColor(
                               (byte)int.Parse(parts[0]).Clamp(0, 255),
                               (byte)int.Parse(parts[1]).Clamp(0, 255),
                               (byte)int.Parse(parts[2]).Clamp(0, 255)));
                }

                return(InvalidValueAction(value, fieldType, fieldName));
            }

            else if (fieldType == typeof(Hotkey))
            {
                Hotkey res;
                if (Hotkey.TryParse(value, out res))
                {
                    return(res);
                }

                return(InvalidValueAction(value, fieldType, fieldName));
            }

            else if (fieldType == typeof(WRange))
            {
                WRange res;
                if (WRange.TryParse(value, out res))
                {
                    return(res);
                }

                return(InvalidValueAction(value, fieldType, fieldName));
            }

            else if (fieldType == typeof(WVec))
            {
                var parts = value.Split(',');
                if (parts.Length == 3)
                {
                    WRange rx, ry, rz;
                    if (WRange.TryParse(parts[0], out rx) && WRange.TryParse(parts[1], out ry) && WRange.TryParse(parts[2], out rz))
                    {
                        return(new WVec(rx, ry, rz));
                    }
                }

                return(InvalidValueAction(value, fieldType, fieldName));
            }

            else if (fieldType == typeof(WPos))
            {
                var parts = value.Split(',');
                if (parts.Length == 3)
                {
                    WRange rx, ry, rz;
                    if (WRange.TryParse(parts[0], out rx) && WRange.TryParse(parts[1], out ry) && WRange.TryParse(parts[2], out rz))
                    {
                        return(new WPos(rx, ry, rz));
                    }
                }

                return(InvalidValueAction(value, fieldType, fieldName));
            }

            else if (fieldType == typeof(WAngle))
            {
                int res;
                if (int.TryParse(value, out res))
                {
                    return(new WAngle(res));
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }

            else if (fieldType == typeof(WRot))
            {
                var parts = value.Split(',');
                if (parts.Length == 3)
                {
                    int rr, rp, ry;
                    if (int.TryParse(value, out rr) && int.TryParse(value, out rp) && int.TryParse(value, out ry))
                    {
                        return(new WRot(new WAngle(rr), new WAngle(rp), new WAngle(ry)));
                    }
                }

                return(InvalidValueAction(value, fieldType, fieldName));
            }

            else if (fieldType.IsEnum)
            {
                if (!Enum.GetNames(fieldType).Select(a => a.ToLower()).Contains(value.ToLower()))
                {
                    return(InvalidValueAction(value, fieldType, fieldName));
                }
                return(Enum.Parse(fieldType, value, true));
            }

            else if (fieldType == typeof(bool))
            {
                return(ParseYesNo(value, fieldType, fieldName));
            }

            else if (fieldType.IsArray)
            {
                if (value == null)
                {
                    return(Array.CreateInstance(fieldType.GetElementType(), 0));
                }

                var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                var ret = Array.CreateInstance(fieldType.GetElementType(), parts.Length);
                for (int i = 0; i < parts.Length; i++)
                {
                    ret.SetValue(GetValue(fieldName, fieldType.GetElementType(), parts[i].Trim(), field), i);
                }
                return(ret);
            }

            else if (fieldType == typeof(int2))
            {
                var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                return(new int2(int.Parse(parts[0]), int.Parse(parts[1])));
            }

            else if (fieldType == typeof(float2))
            {
                var   parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                float xx    = 0;
                float yy    = 0;
                float res;
                if (float.TryParse(parts[0].Replace("%", ""), out res))
                {
                    xx = res * (parts[0].Contains('%') ? 0.01f : 1f);
                }
                if (float.TryParse(parts[1].Replace("%", ""), out res))
                {
                    yy = res * (parts[1].Contains('%') ? 0.01f : 1f);
                }
                return(new float2(xx, yy));
            }

            else if (fieldType == typeof(Rectangle))
            {
                var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                return(new Rectangle(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), int.Parse(parts[3])));
            }

            else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Bits <>))
            {
                var parts     = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var argTypes  = new Type[] { typeof(string[]) };
                var argValues = new object[] { parts };
                return(fieldType.GetConstructor(argTypes).Invoke(argValues));
            }

            else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                var innerType  = fieldType.GetGenericArguments().First();
                var innerValue = GetValue("Nullable<T>", innerType, value, field);
                return(fieldType.GetConstructor(new[] { innerType }).Invoke(new[] { innerValue }));
            }

            UnknownFieldAction("[Type] {0}".F(value), fieldType);
            return(null);
        }
 public HotkeyActionCallbackFailedEventArgs(Hotkey hotkey, Exception exception)
 {
     this.Hotkey    = hotkey;
     this.Exception = exception;
 }
예제 #48
0
        public SupportPowerTooltipLogic(Widget widget, TooltipContainerWidget tooltipContainer, Player player, SupportPowersWidget palette, World world,
                                        PlayerResources playerResources)
        {
            widget.IsVisible = () => palette.TooltipIcon != null && palette.TooltipIcon.Power.Info != null;
            var nameLabel   = widget.Get <LabelWidget>("NAME");
            var hotkeyLabel = widget.Get <LabelWidget>("HOTKEY");
            var timeLabel   = widget.Get <LabelWidget>("TIME");
            var descLabel   = widget.Get <LabelWidget>("DESC");
            var costLabel   = widget.Get <LabelWidget>("COST");
            var nameFont    = Game.Renderer.Fonts[nameLabel.Font];
            var hotkeyFont  = Game.Renderer.Fonts[hotkeyLabel.Font];
            var timeFont    = Game.Renderer.Fonts[timeLabel.Font];
            var descFont    = Game.Renderer.Fonts[descLabel.Font];
            var costFont    = Game.Renderer.Fonts[costLabel.Font];
            var baseHeight  = widget.Bounds.Height;
            var timeOffset  = timeLabel.Bounds.X;
            var costOffset  = costLabel.Bounds.X;

            SupportPowerInstance lastPower = null;
            Hotkey lastHotkey           = Hotkey.Invalid;
            var    lastRemainingSeconds = 0;

            tooltipContainer.BeforeRender = () =>
            {
                var icon = palette.TooltipIcon;
                if (icon == null)
                {
                    return;
                }

                var sp = icon.Power;

                // HACK: This abuses knowledge of the internals of WidgetUtils.FormatTime
                // to efficiently work when the label is going to change, requiring a panel relayout
                var remainingSeconds = (int)Math.Ceiling(sp.RemainingTime * world.Timestep / 1000f);

                var hotkey = icon.Hotkey != null?icon.Hotkey.GetValue() : Hotkey.Invalid;

                if (sp == lastPower && hotkey == lastHotkey && lastRemainingSeconds == remainingSeconds)
                {
                    return;
                }

                var cost       = sp.Info.Cost;
                var costString = costLabel.Text + cost.ToString();
                costLabel.GetText  = () => costString;
                costLabel.GetColor = () => playerResources.Cash + playerResources.Resources >= cost
                                        ? Color.White : Color.Red;
                costLabel.IsVisible = () => cost != 0;

                nameLabel.Text = sp.Info.Description;
                var nameSize = nameFont.Measure(nameLabel.Text);

                descLabel.Text = sp.Info.LongDesc.Replace("\\n", "\n");
                var descSize = descFont.Measure(descLabel.Text);

                var remaining = WidgetUtils.FormatTime(sp.RemainingTime, world.Timestep);
                var total     = WidgetUtils.FormatTime(sp.Info.ChargeTime * 25, world.Timestep);
                timeLabel.Text = "{0} / {1}".F(remaining, total);
                var timeSize = timeFont.Measure(timeLabel.Text);

                var hotkeyWidth = 0;
                hotkeyLabel.Visible = hotkey.IsValid();
                if (hotkeyLabel.Visible)
                {
                    var hotkeyText = "({0})".F(hotkey.DisplayString());

                    hotkeyWidth          = hotkeyFont.Measure(hotkeyText).X + 2 * nameLabel.Bounds.X;
                    hotkeyLabel.Text     = hotkeyText;
                    hotkeyLabel.Bounds.X = nameSize.X + 2 * nameLabel.Bounds.X;
                }

                var timeWidth = timeSize.X;
                var costWidth = costFont.Measure(costString).X;
                var topWidth  = nameSize.X + hotkeyWidth + timeWidth + timeOffset;

                if (cost != 0)
                {
                    topWidth += costWidth + costOffset;
                }

                widget.Bounds.Width  = 2 * nameLabel.Bounds.X + Math.Max(topWidth, descSize.X);
                widget.Bounds.Height = baseHeight + descSize.Y;
                timeLabel.Bounds.X   = widget.Bounds.Width - nameLabel.Bounds.X - timeWidth;

                if (cost != 0)
                {
                    timeLabel.Bounds.X -= costWidth + costOffset;
                    costLabel.Bounds.X  = widget.Bounds.Width - nameLabel.Bounds.X - costWidth;
                }

                lastPower            = sp;
                lastHotkey           = hotkey;
                lastRemainingSeconds = remainingSeconds;
            };

            timeLabel.GetColor = () => palette.TooltipIcon != null && !palette.TooltipIcon.Power.Active
                                ? Color.Red : Color.White;
        }
예제 #49
0
        public ProductionTooltipLogic(Widget widget, TooltipContainerWidget tooltipContainer, Player player, Func <ProductionIcon> getTooltipIcon)
        {
            var world    = player.World;
            var mapRules = world.Map.Rules;
            var pm       = player.PlayerActor.TraitOrDefault <PowerManager>();
            var pr       = player.PlayerActor.Trait <PlayerResources>();

            widget.IsVisible = () => getTooltipIcon() != null && getTooltipIcon().Actor != null;
            var nameLabel     = widget.Get <LabelWidget>("NAME");
            var hotkeyLabel   = widget.Get <LabelWidget>("HOTKEY");
            var requiresLabel = widget.Get <LabelWidget>("REQUIRES");
            var powerLabel    = widget.Get <LabelWidget>("POWER");
            var powerIcon     = widget.Get <ImageWidget>("POWER_ICON");
            var timeLabel     = widget.Get <LabelWidget>("TIME");
            var timeIcon      = widget.Get <ImageWidget>("TIME_ICON");
            var costLabel     = widget.Get <LabelWidget>("COST");
            var costIcon      = widget.Get <ImageWidget>("COST_ICON");
            var descLabel     = widget.Get <LabelWidget>("DESC");

            var iconMargin = timeIcon.Bounds.X;

            var font            = Game.Renderer.Fonts[nameLabel.Font];
            var descFont        = Game.Renderer.Fonts[descLabel.Font];
            var requiresFont    = Game.Renderer.Fonts[requiresLabel.Font];
            var formatBuildTime = new CachedTransform <int, string>(time => WidgetUtils.FormatTime(time, world.Timestep));
            var requiresFormat  = requiresLabel.Text;

            ActorInfo lastActor      = null;
            Hotkey    lastHotkey     = Hotkey.Invalid;
            var       lastPowerState = pm == null ? PowerState.Normal : pm.PowerState;

            tooltipContainer.BeforeRender = () =>
            {
                var tooltipIcon = getTooltipIcon();
                if (tooltipIcon == null)
                {
                    return;
                }

                var actor = tooltipIcon.Actor;
                if (actor == null)
                {
                    return;
                }

                var hotkey = tooltipIcon.Hotkey != null?tooltipIcon.Hotkey.GetValue() : Hotkey.Invalid;

                if (actor == lastActor && hotkey == lastHotkey && (pm == null || pm.PowerState == lastPowerState))
                {
                    return;
                }

                var tooltip   = actor.TraitInfos <TooltipInfo>().FirstOrDefault(info => info.EnabledByDefault);
                var name      = tooltip != null ? tooltip.Name : actor.Name;
                var buildable = actor.TraitInfo <BuildableInfo>();
                var cost      = actor.TraitInfo <ValuedInfo>().Cost;

                nameLabel.Text = name;

                var nameSize    = font.Measure(name);
                var hotkeyWidth = 0;
                hotkeyLabel.Visible = hotkey.IsValid();

                if (hotkeyLabel.Visible)
                {
                    var hotkeyText = "({0})".F(hotkey.DisplayString());

                    hotkeyWidth          = font.Measure(hotkeyText).X + 2 * nameLabel.Bounds.X;
                    hotkeyLabel.Text     = hotkeyText;
                    hotkeyLabel.Bounds.X = nameSize.X + 2 * nameLabel.Bounds.X;
                }

                var prereqs = buildable.Prerequisites.Select(a => ActorName(mapRules, a))
                              .Where(s => !s.StartsWith("~", StringComparison.Ordinal) && !s.StartsWith("!", StringComparison.Ordinal));
                requiresLabel.Text = prereqs.Any() ? requiresFormat.F(prereqs.JoinWith(", ")) : "";
                var requiresSize = requiresFont.Measure(requiresLabel.Text);

                var powerSize = new int2(0, 0);
                if (pm != null)
                {
                    var power = actor.TraitInfos <PowerInfo>().Where(i => i.EnabledByDefault).Sum(i => i.Amount);
                    powerLabel.Text     = power.ToString();
                    powerLabel.GetColor = () => ((pm.PowerProvided - pm.PowerDrained) >= -power || power > 0)
                                                ? Color.White : Color.Red;
                    powerLabel.Visible = power != 0;
                    powerIcon.Visible  = power != 0;
                    powerSize          = font.Measure(powerLabel.Text);
                }

                var buildTime      = tooltipIcon.ProductionQueue == null ? 0 : tooltipIcon.ProductionQueue.GetBuildTime(actor, buildable);
                var timeMultiplier = pm != null && pm.PowerState != PowerState.Normal ? tooltipIcon.ProductionQueue.Info.LowPowerSlowdown : 1;

                timeLabel.Text      = formatBuildTime.Update(buildTime * timeMultiplier);
                timeLabel.TextColor = (pm != null && pm.PowerState != PowerState.Normal && tooltipIcon.ProductionQueue.Info.LowPowerSlowdown > 1) ? Color.Red : Color.White;
                var timeSize = font.Measure(timeLabel.Text);

                costLabel.Text     = cost.ToString();
                costLabel.GetColor = () => pr.Cash + pr.Resources >= cost ? Color.White : Color.Red;
                var costSize = font.Measure(costLabel.Text);

                descLabel.Text = buildable.Description.Replace("\\n", "\n");
                var descSize = descFont.Measure(descLabel.Text);

                var leftWidth = new[] { nameSize.X + hotkeyWidth, requiresSize.X, descSize.X }.Aggregate(Math.Max);
                var rightWidth = new[] { powerSize.X, timeSize.X, costSize.X }.Aggregate(Math.Max);

                timeIcon.Bounds.X   = powerIcon.Bounds.X = costIcon.Bounds.X = leftWidth + 2 * nameLabel.Bounds.X;
                timeLabel.Bounds.X  = powerLabel.Bounds.X = costLabel.Bounds.X = timeIcon.Bounds.Right + iconMargin;
                widget.Bounds.Width = leftWidth + rightWidth + 3 * nameLabel.Bounds.X + timeIcon.Bounds.Width + iconMargin;

                var leftHeight  = nameSize.Y + requiresSize.Y + descSize.Y;
                var rightHeight = powerSize.Y + timeSize.Y + costSize.Y;
                widget.Bounds.Height = Math.Max(leftHeight, rightHeight) * 3 / 2 + 3 * nameLabel.Bounds.Y;

                lastActor  = actor;
                lastHotkey = hotkey;
                if (pm != null)
                {
                    lastPowerState = pm.PowerState;
                }
            };
        }
예제 #50
0
 public NetworkConnectionsHandler()
 {
     Hotkey = new Hotkey(ModifierKeys.Windows, Key.F5);
 }
예제 #51
0
 public void UpdateHotkeyData(Hotkey _hotkey, InventoryGearData _gearData)
 {
     _hotkey.UpdateData(_gearData);
 }
예제 #52
0
 public void Handle(Hotkey hotkey)
 {
     Process.Start(@"C:\Windows\explorer.exe", "::{7007ACC7-3202-11D1-AAD2-00805FC1270E}");
 }
예제 #53
0
        public MapEditorLogic(Widget widget, ModData modData, World world, WorldRenderer worldRenderer, Dictionary <string, MiniYaml> logicArgs)
        {
            MiniYaml yaml;
            var      changeZoomKey = new HotkeyReference();

            if (logicArgs.TryGetValue("ChangeZoomKey", out yaml))
            {
                changeZoomKey = modData.Hotkeys[yaml.Value];
            }

            var editorViewport = widget.Get <EditorViewportControllerWidget>("MAP_EDITOR");

            var gridButton           = widget.GetOrNull <ButtonWidget>("GRID_BUTTON");
            var terrainGeometryTrait = world.WorldActor.Trait <TerrainGeometryOverlay>();

            if (gridButton != null && terrainGeometryTrait != null)
            {
                gridButton.OnClick       = () => terrainGeometryTrait.Enabled ^= true;
                gridButton.IsHighlighted = () => terrainGeometryTrait.Enabled;
            }

            var zoomDropdown = widget.GetOrNull <DropDownButtonWidget>("ZOOM_BUTTON");

            if (zoomDropdown != null)
            {
                var selectedZoom = (Game.Settings.Graphics.PixelDouble ? 2f : 1f).ToString();

                zoomDropdown.SelectedItem = selectedZoom;
                Func <float, ScrollItemWidget, ScrollItemWidget> setupItem = (zoom, itemTemplate) =>
                {
                    var item = ScrollItemWidget.Setup(
                        itemTemplate,
                        () =>
                    {
                        return(float.Parse(zoomDropdown.SelectedItem) == zoom);
                    },
                        () =>
                    {
                        zoomDropdown.SelectedItem   = selectedZoom = zoom.ToString();
                        worldRenderer.Viewport.Zoom = float.Parse(selectedZoom);
                    });

                    var label = zoom.ToString();
                    item.Get <LabelWidget>("LABEL").GetText = () => label;

                    return(item);
                };

                var options = worldRenderer.Viewport.AvailableZoomSteps;
                zoomDropdown.OnMouseDown = _ => zoomDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 150, options, setupItem);
                zoomDropdown.GetText     = () => zoomDropdown.SelectedItem;
                zoomDropdown.OnKeyPress  = e =>
                {
                    if (!changeZoomKey.IsActivatedBy(e))
                    {
                        return;
                    }

                    var selected = (options.IndexOf(float.Parse(selectedZoom)) + 1) % options.Length;
                    var zoom     = options[selected];
                    worldRenderer.Viewport.Zoom = zoom;
                    selectedZoom = zoom.ToString();
                    zoomDropdown.SelectedItem = zoom.ToString();
                };
            }

            var copypasteButton = widget.GetOrNull <ButtonWidget>("COPYPASTE_BUTTON");

            if (copypasteButton != null)
            {
                // HACK: Replace Ctrl with Cmd on macOS
                // TODO: Add platform-specific override support to HotkeyManager
                // and then port the editor hotkeys to this system.
                var copyPasteKey = copypasteButton.Key.GetValue();
                if (Platform.CurrentPlatform == PlatformType.OSX && copyPasteKey.Modifiers.HasModifier(Modifiers.Ctrl))
                {
                    var modified = new Hotkey(copyPasteKey.Key, copyPasteKey.Modifiers & ~Modifiers.Ctrl | Modifiers.Meta);
                    copypasteButton.Key = FieldLoader.GetValue <HotkeyReference>("Key", modified.ToString());
                }

                copypasteButton.OnClick       = () => editorViewport.SetBrush(new EditorCopyPasteBrush(editorViewport, worldRenderer, () => copyFilters));
                copypasteButton.IsHighlighted = () => editorViewport.CurrentBrush is EditorCopyPasteBrush;
            }

            var copyFilterDropdown = widget.Get <DropDownButtonWidget>("COPYFILTER_BUTTON");

            copyFilterDropdown.OnMouseDown = _ =>
            {
                copyFilterDropdown.RemovePanel();
                copyFilterDropdown.AttachPanel(CreateCategoriesPanel());
            };

            var coordinateLabel = widget.GetOrNull <LabelWidget>("COORDINATE_LABEL");

            if (coordinateLabel != null)
            {
                coordinateLabel.GetText = () =>
                {
                    var cell = worldRenderer.Viewport.ViewToWorld(Viewport.LastMousePos);
                    var map  = worldRenderer.World.Map;
                    return(map.Height.Contains(cell) ?
                           "{0},{1} ({2})".F(cell, map.Height[cell], map.Tiles[cell].Type) : "");
                };
            }

            var cashLabel = widget.GetOrNull <LabelWidget>("CASH_LABEL");

            if (cashLabel != null)
            {
                var reslayer = worldRenderer.World.WorldActor.TraitsImplementing <EditorResourceLayer>().FirstOrDefault();
                if (reslayer != null)
                {
                    cashLabel.GetText = () => "$ {0}".F(reslayer.NetWorth);
                }
            }
        }
예제 #54
0
        /// <summary>
        /// Updates the hotkey, bypassing setters to avoid triggering view updates.
        /// </summary>
        /// <param name="hotkey">The hotkey for this project item.</param>
        public void LoadHotkey(Hotkey hotkey)
        {
            this.hotkey = hotkey;

            this.HotKey?.SetCallBackFunction(() => this.IsActivated = !this.IsActivated);
        }
예제 #55
0
 private void UpdateHotkeyText()
 {
     buttonHotkey.Text = Hotkey.ToString();
 }
예제 #56
0
        private void applyShortcutButton_Click(object sender, EventArgs e)
        {
            try
            {
                int notMetaCount = shortcutKeys.Count(k => !IsMetaKey(k));
                if (notMetaCount == 0)
                {
                    ShowErrorMessage("You should also choose one character that is not CTRL, SHIFT, ALT or WIN");
                    return;
                }

                bool ctrl  = false;
                bool shift = false;
                bool alt   = false;
                bool win   = false;
                Keys key   = Keys.F19;

                foreach (Keys item in shortcutKeys)
                {
                    if (item == Keys.ControlKey)
                    {
                        ctrl = true;
                    }
                    else if (item == Keys.ShiftKey)
                    {
                        shift = true;
                    }
                    else if (item == Keys.LWin || item == Keys.RWin)
                    {
                        win = true;
                    }
                    else if (item == Keys.Alt || item == Keys.Menu)
                    {
                        alt = true;
                    }
                    else
                    {
                        key = item;
                    }
                }

                if (hotKey != null && hotKey.Registered)
                {
                    hotKey.Unregister();
                }

                hotKey          = new Hotkey(key, shift, ctrl, alt, win);
                hotKey.Pressed += (hkSender, hkArgs) => ShowScreenShotForm();

                if (hotKey.GetCanRegister(shortcut))
                {
                    hotKey.Register(shortcut);
                    new UserSettings().Shortcut = shortcutKeys;
                }
                else
                {
                    MessageBox.Show(this, "There is another application using this combination already. Please choose another one",
                                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex.Message);
            }
        }
예제 #57
0
        public override bool HandleKeyPress(KeyInput e)
        {
            var key = Hotkey.FromKeyInput(e);
            var ks  = Game.Settings.Keys;

            if (key == ks.MapScrollUp)
            {
                keyboardDirections = keyboardDirections.Set(ScrollDirection.Up, e.Event == KeyInputEvent.Down);
                return(true);
            }

            if (key == ks.MapScrollDown)
            {
                keyboardDirections = keyboardDirections.Set(ScrollDirection.Down, e.Event == KeyInputEvent.Down);
                return(true);
            }

            if (key == ks.MapScrollLeft)
            {
                keyboardDirections = keyboardDirections.Set(ScrollDirection.Left, e.Event == KeyInputEvent.Down);
                return(true);
            }

            if (key == ks.MapScrollRight)
            {
                keyboardDirections = keyboardDirections.Set(ScrollDirection.Right, e.Event == KeyInputEvent.Down);
                return(true);
            }

            if (key == ks.MapPushTop)
            {
                worldRenderer.Viewport.Center(new WPos(worldRenderer.Viewport.CenterPosition.X, 0, 0));
                return(false);
            }

            if (key == ks.MapPushBottom)
            {
                worldRenderer.Viewport.Center(new WPos(worldRenderer.Viewport.CenterPosition.X, worldRenderer.World.Map.ProjectedBottomRight.Y, 0));
                return(false);
            }

            if (key == ks.MapPushLeftEdge)
            {
                worldRenderer.Viewport.Center(new WPos(0, worldRenderer.Viewport.CenterPosition.Y, 0));
                return(false);
            }

            if (key == ks.MapPushRightEdge)
            {
                worldRenderer.Viewport.Center(new WPos(worldRenderer.World.Map.ProjectedBottomRight.X, worldRenderer.Viewport.CenterPosition.Y, 0));
            }

            if (key == ks.ViewPortBookmarkSaveSlot1)
            {
                SaveCurrentPositionToBookmark(0);
                return(false);
            }

            if (key == ks.ViewPortBookmarkSaveSlot2)
            {
                SaveCurrentPositionToBookmark(1);
                return(false);
            }

            if (key == ks.ViewPortBookmarkSaveSlot3)
            {
                SaveCurrentPositionToBookmark(2);
                return(false);
            }

            if (key == ks.ViewPortBookmarkSaveSlot4)
            {
                SaveCurrentPositionToBookmark(3);
                return(false);
            }

            if (key == ks.ViewPortBookmarkUseSlot1)
            {
                JumpToSavedBookmark(0);
                return(false);
            }

            if (key == ks.ViewPortBookmarkUseSlot2)
            {
                JumpToSavedBookmark(1);
                return(false);
            }

            if (key == ks.ViewPortBookmarkUseSlot3)
            {
                JumpToSavedBookmark(2);
                return(false);
            }

            if (key == ks.ViewPortBookmarkUseSlot4)
            {
                JumpToSavedBookmark(3);
                return(false);
            }

            return(false);
        }
예제 #58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HotkeyEditor" /> class.
 /// </summary>
 /// <param name="hotkey">The initial hotkeys to edit.</param>
 public HotkeyEditor(Hotkey hotkey = null)
 {
     this.InitializeComponent();
     this.HotkeyEditorViewModel.SetActiveHotkey(hotkey);
 }
    PlayerInventory inventory;      //The inventory of the player

    private void Awake()
    {
        key       = GetComponentInChildren <Hotkey>();
        inventory = GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerInventory>();
    }
예제 #60
0
 /// <summary>
 /// Unregister the main hotkey which starts/stgops the thread
 /// </summary>
 public void UnregisterMainKey()
 {
     Hotkey.UnregisterHotKey(this.Handle, HOTKEY_ID_PAUSE);
 }