Exemple #1
0
        private void ExecuteSearchCommand()
        {
            if (IgnoreSearch)
            {
                return;
            }

            IgnoreSearch = true;

            var delayer = new Delayer <object>(TimeSpan.FromMilliseconds(250));

            delayer.Action += (sender, args) =>
            {
                IgnoreSearch = false;
            };
            delayer.ResetAndTick();

            var delayer2 = new Delayer <object>(TimeSpan.FromMilliseconds(10));

            delayer2.Action += (sender, args) =>
            {
                Logger.Instance.Information("Search in the paste bar started.");
                Search();
                RaisePropertyChanged(nameof(NoSearchResult));
            };
            delayer2.ResetAndTick();

            if (CoreHelper.IsUnitTesting())
            {
                Task.Delay(50).Wait();
                DispatcherHelper.DoEvents();
            }
        }
Exemple #2
0
        public void Delayer()
        {
            var actionCalled = false;

            DispatcherUtil.ExecuteOnDispatcherThread(() =>
            {
                var delayer     = new Delayer <string>(TimeSpan.FromMilliseconds(100));
                delayer.Action += (sender, args) =>
                {
                    if (args.Data == "hello")
                    {
                        actionCalled = true;
                    }
                };

                Assert.IsFalse(actionCalled);
                delayer.ResetAndTick("hello");

                Task.Delay(100).Wait();
                DispatcherUtil.DoEvents();
                Assert.IsFalse(actionCalled);
            }, 1);

            Task.Delay(100).Wait();
            DispatcherUtil.DoEvents();
            Assert.IsTrue(actionCalled);
        }
Exemple #3
0
        private void ExecuteHideBarButtonCommand()
        {
            if (_mouseAndKeyboardHookService != null)
            {
                if (Settings.Default.ClosePasteBarWhenMouseIsAway)
                {
                    _mouseAndKeyboardHookService.MouseAction -= MouseAndKeyboardHookService_MouseAction;
                }

                if (Settings.Default.ClosePasteBarWithHotKey)
                {
                    _mouseAndKeyboardHookService.UnregisterHotKey(Consts.PasteShortcutName);
                    _mouseAndKeyboardHookService.HotKeyDetected -= MouseAndKeyboardHookService_HotKeyDetected;
                }
                _mouseAndKeyboardHookService.Pause();
            }

            Logger.Instance.Information($"The paste bar window has been hidden.");

            MessengerInstance.Send(new ComponentModel.Messages.Message(), MessageIdentifiers.HidePasteBarWindow);
            var delayer = new Delayer <object>(TimeSpan.FromMilliseconds(200));

            delayer.Action += (sender, args) =>
            {
                _mouseAndKeyboardHookService = null;
                _canCloseIfMouseMovesAway    = false;
                if (!string.IsNullOrEmpty(SearchQueryString) || SearchType != SearchType.All)
                {
                    SearchQueryString = string.Empty;
                    SearchType        = SearchType.All;
                    Search();
                }
            };
            delayer.ResetAndTick();
        }
        /// <summary>
        /// Paste the data to the current foreground window.
        /// </summary>
        /// <param name="message">The message to show.</param>
        private void PasteData(Message message)
        {
            Requires.NotNull(message.Values, nameof(message.Values));

            var delayer = new Delayer <object>(TimeSpan.FromMilliseconds(200));

            delayer.Action += (sender, args) =>
            {
                var clipboardService            = ServiceLocator.GetService <ClipboardService>();
                var mouseAndKeyboardHookService = ServiceLocator.GetService <MouseAndKeyboardHookService>();
                mouseAndKeyboardHookService.Pause();
                clipboardService.Pause();

                ServiceLocator.GetService <DataService>().CopyData((DataEntry)message.Values.First());
                clipboardService.Paste();

                delayer         = new Delayer <object>(TimeSpan.FromMilliseconds(300));
                delayer.Action += (sender2, args2) =>
                {
                    mouseAndKeyboardHookService.Resume();
                    clipboardService.Resume();
                };
                delayer.ResetAndTick();
            };
            delayer.ResetAndTick();
        }
        private void ExecuteExitCommand()
        {
            Logger.Instance.Information("Exit menu from icon in the task bar clicked.");
            HideNotifyIcon();

            var delayer = new Delayer <object>(TimeSpan.FromMilliseconds(300));

            delayer.Action += (o, args) =>
            {
                if (MessageBox.Show(Language.MainWindow.Message_Quit, Language.MainWindow.ApplicationTitle, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    if (CoreHelper.IsUnitTesting())
                    {
                        throw new OperationCanceledException("Unable to quit a unit test");
                    }

                    _pasteBarMustBeRecreatedAutomatically = false;
                    _pasteBarWindow.Close();
                    Application.Current.Shutdown(0);
                }
                else
                {
                    Logger.Instance.Information("Exit has been canceled.");
                    ShowNotifyIcon();
                }
            };
            delayer.ResetAndTick();
        }
        /// <summary>
        /// Resume the hooking with the specified delay.
        /// </summary>
        /// <param name="delay">The delay before resuming.</param>
        internal void DelayedResume(TimeSpan delay)
        {
            var delayedHooking = new Delayer <object>(delay);

            delayedHooking.Action += (sender, args) => Resume();
            delayedHooking.ResetAndTick();
        }
Exemple #7
0
        /// <summary>
        /// Display on the screen the paste bare with an animation.
        /// </summary>
        internal void DisplayBar()
        {
            var delayer = new Delayer <object>(TimeSpan.FromMilliseconds(250));

            delayer.Action += (sender, args) =>
            {
                if (Settings.Default.ClosePasteBarWhenMouseIsAway && !CoreHelper.IsUnitTesting())
                {
                    _mouseAndKeyboardHookService              = ServiceLocator.GetService <MouseAndKeyboardHookService>();
                    _mouseAndKeyboardHookService.MouseAction += MouseAndKeyboardHookService_MouseAction;
                    _mouseAndKeyboardHookService.Resume();
                }

                if (Settings.Default.ClosePasteBarWithHotKey && !CoreHelper.IsUnitTesting())
                {
                    if (_mouseAndKeyboardHookService == null)
                    {
                        _mouseAndKeyboardHookService = ServiceLocator.GetService <MouseAndKeyboardHookService>();
                    }
                    _mouseAndKeyboardHookService.HotKeyDetected += MouseAndKeyboardHookService_HotKeyDetected;
                    _mouseAndKeyboardHookService.RegisterHotKey(Consts.PasteShortcutName, Settings.Default.KeyboardShortcut.Cast <Key>().ToArray());
                    _mouseAndKeyboardHookService.Resume();
                    Logger.Instance.Information($"The keyboard is listened. The expecting shortcut is {JsonConvert.SerializeObject(Settings.Default.KeyboardShortcut.Cast<Key>().ToArray())}.");
                }
            };
            delayer.ResetAndTick();
        }
Exemple #8
0
        private void MouseAndKeyboardHookService_MouseAction(object sender, MouseHookEventArgs e)
        {
            var mustClose    = false;
            var activeScreen = Screen.FromPoint(new System.Drawing.Point(Cursor.Position.X, Cursor.Position.Y));
            var screen       = SystemInfoHelper.GetAllScreenInfos().Single(s => s.DeviceName == activeScreen.DeviceName);

            switch (Settings.Default.PasteBarPosition)
            {
            case PasteBarPosition.Top:
                if (e.Coords.Y - screen.Bounds.Top >= screen.Bounds.Bottom / 2)
                {
                    if (_canCloseIfMouseMovesAway)
                    {
                        mustClose = true;
                    }
                }
                else
                {
                    _canCloseIfMouseMovesAway = true;
                }
                break;

            case PasteBarPosition.Bottom:
                if (e.Coords.Y - screen.Bounds.Top <= screen.Bounds.Bottom / 2)
                {
                    if (_canCloseIfMouseMovesAway)
                    {
                        mustClose = true;
                    }
                }
                else
                {
                    _canCloseIfMouseMovesAway = true;
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            if (mustClose)
            {
                if (_mouseAndKeyboardHookService != null)
                {
                    _mouseAndKeyboardHookService.MouseAction -= MouseAndKeyboardHookService_MouseAction;
                }
                Logger.Instance.Information($"Mouse moves away from the paste bar.");

                var delayer = new Delayer <object>(TimeSpan.FromMilliseconds(10));
                delayer.Action += (o, args) => HideBarButtonCommand?.Execute(null);
                delayer.ResetAndTick();
            }
        }
        /// <summary>
        /// Initialize the <see cref="_delayedTextChangedTimer"/> each time that the text change
        /// </summary>
        private void InitializeDelayedTextChangedTimer()
        {
            _delayedTextChangedTimer?.Stop();

            if (_delayedTextChangedTimer == null)
            {
                _delayedTextChangedTimer         = new Delayer <object>(TimeSpan.FromMilliseconds(DelayedTextChangedTimeout));
                _delayedTextChangedTimer.Action += DelayedTextChangedTimer_Tick;
            }

            _delayedTextChangedTimer.ResetAndTick();
        }
        public HomeViewModel(IDataService dataService)
        {
            _dataService = dataService;

            StopResults = new ObservableCollection <StopResult>();
            TramResults = new ObservableCollection <JourneyResult>();
            BusResults  = new ObservableCollection <JourneyResult>();

            searchStopsWithDelay.Action += async(sender, e) =>
            {
                await GetStopsCodeByName(StopSearch);
            };

            GetStopResultsCommand = new RelayCommand <AutoSuggestBoxTextChangedEventArgs>(args =>
            {
                if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput && StopSearch.Length > 2)
                {
                    searchStopsWithDelay.ResetAndTick();
                }
            });

            GetJourneyResultsCommand = new RelayCommand <AutoSuggestBoxSuggestionChosenEventArgs>(async stop =>
            {
                var current  = (StopResult)stop.SelectedItem;
                current.Name = current.Name.ToUpper();

                this.CurrentStop = current;

                await GetJourneyResults(CurrentStop.Code);
            });

            PinStopCommand = new RelayCommand(() =>
            {
                if (CurrentStop == null)
                {
                    return;
                }

                ApplicationDataContainer settingsRoaming = ApplicationData.Current.RoamingSettings;
                ApplicationDataCompositeValue composite  = new ApplicationDataCompositeValue();

                var key = $"{this.CurrentStop.Code}/{this.CurrentStop.Name}";

                composite["Code"] = this.CurrentStop.Code;
                composite["Name"] = this.CurrentStop.Name;

                if (!settingsRoaming.Values.Keys.Contains(key))
                {
                    settingsRoaming.Values[key] = composite;
                }
            });
        }
Exemple #11
0
        private void ExecutePasteCommand(DataEntry dataEntry)
        {
            var delayer = new Delayer <DataEntry>(TimeSpan.FromMilliseconds(200));

            delayer.Action += (sender, args) =>
            {
                Logger.Instance.Information("Paste command activated.");
                Requires.NotNull(args.Data, nameof(args.Data));
                HideBarButtonCommand.Execute(null);
                MessengerInstance.Send(new ComponentModel.Messages.Message(args.Data), MessageIdentifiers.PasteData);
            };
            delayer.ResetAndTick(dataEntry);
        }
        private void MouseAndKeyboardHookService_MouseAction(object sender, MouseHookEventArgs e)
        {
            switch (Settings.Default.PasteBarPosition)
            {
            case PasteBarPosition.Top:
                if (e.WheelAction == MouseWheelAction.WheelDown)
                {
                    var activeScreen = Screen.FromPoint(new System.Drawing.Point(System.Windows.Forms.Cursor.Position.X, System.Windows.Forms.Cursor.Position.Y));
                    var screen       = SystemInfoHelper.GetAllScreenInfos().Single(s => s.DeviceName == activeScreen.DeviceName);

                    if (e.Coords.Y <= screen.Bounds.Top + 5 && PasteCommand.CanExecute(null))
                    {
                        e.Handled = true;
                        Logger.Instance.Information($"Mouse gesture detected at the top of the screen.");
                        _delayedPasteCommand.ResetAndTick();
                    }
                }
                break;

            case PasteBarPosition.Bottom:
                if (e.WheelAction == MouseWheelAction.WheelUp)
                {
                    var activeScreen = Screen.FromPoint(new System.Drawing.Point(System.Windows.Forms.Cursor.Position.X, System.Windows.Forms.Cursor.Position.Y));
                    var screen       = SystemInfoHelper.GetAllScreenInfos().Single(s => s.DeviceName == activeScreen.DeviceName);

                    if (e.Coords.Y >= screen.Bounds.Bottom + screen.Bounds.Top - 5 && PasteCommand.CanExecute(null))
                    {
                        e.Handled = true;
                        Logger.Instance.Information($"Mouse gesture detected at the bottom of the screen.");
                        _delayedPasteCommand.ResetAndTick();
                    }
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemple #13
0
        private void MouseAndKeyboardHookService_HotKeyDetected(object sender, HotKeyEventArgs e)
        {
            if (_mouseAndKeyboardHookService != null)
            {
                _mouseAndKeyboardHookService.HotKeyDetected -= MouseAndKeyboardHookService_HotKeyDetected;
            }
            Logger.Instance.Information($"The keyboard shortcut has hit.");
            e.Handled = true;

            var delayer = new Delayer <object>(TimeSpan.FromMilliseconds(10));

            delayer.Action += (o, args) => HideBarButtonCommand?.Execute(null);
            delayer.ResetAndTick();
        }
Exemple #14
0
        private void ExecuteCopyCommand(DataEntry dataEntry)
        {
            var delayer = new Delayer <DataEntry>(TimeSpan.FromMilliseconds(200));

            delayer.Action += (sender, args) =>
            {
                Logger.Instance.Information("Copy command activated.");
                Requires.NotNull(args.Data, nameof(args.Data));

                _mouseAndKeyboardHookService?.Pause();
                _dataService.CopyData(args.Data);
                _mouseAndKeyboardHookService?.Resume();
            };
            delayer.ResetAndTick(dataEntry);
        }
Exemple #15
0
        /// <summary>
        /// Perform a Ctrl + V to paste the current data in the clipboard.
        /// </summary>
        internal void Paste(int delay = 100)
        {
            Pause();
            var delayer = new Delayer <object>(TimeSpan.FromMilliseconds(delay));

            delayer.Action += async(sender, args) =>
            {
                // SendKeys.SendWait("^v"); // Ctrl + V
                Metatool.Input.Keyboard.Hit(Keys.V, new List <Keys> {
                    Keys.RControlKey
                });

                delayer         = new Delayer <object>(TimeSpan.FromMilliseconds(delay));
                delayer.Action += (sender2, args2) => { Resume(); };
                delayer.ResetAndTick();
            };
            delayer.ResetAndTick();
        }
        /// <summary>
        /// Perform a Ctrl + V to paste the current data in the clipboard.
        /// </summary>
        internal void Paste()
        {
            Pause();

            var delayer = new Delayer <object>(TimeSpan.FromMilliseconds(100));

            delayer.Action += (sender, args) =>
            {
                SendKeys.SendWait("^v"); // Ctrl + V

                delayer         = new Delayer <object>(TimeSpan.FromMilliseconds(100));
                delayer.Action += (sender2, args2) =>
                {
                    Resume();
                };
                delayer.ResetAndTick();
            };
            delayer.ResetAndTick();
        }
        /// <summary>
        /// Display on the screen the paste bare with an animation.
        /// </summary>
        /// <param name="actionOnHidding">Action to perform when the paste bar is hidden.</param>
        internal void DisplayBar(Action actionOnHidding)
        {
            if (_isDisplayed)
            {
                throw new Exception("Paste bar already displayed.");
            }

            var dataContext = (PasteBarWindowViewModel)DataContext;

            _isDisplayed     = true;
            _actionOnHidding = actionOnHidding;

            var activeScreen = Screen.FromPoint(new System.Drawing.Point(System.Windows.Forms.Cursor.Position.X,
                                                                         System.Windows.Forms.Cursor.Position.Y));
            var screen = SystemInfoHelper.GetAllScreenInfos().Single(s => s.DeviceName == activeScreen.DeviceName);

            InitializePosition(screen);
            InitializeStoryboards(screen);

            Messenger.Default.Register <ComponentModel.Messages.Message>(this, MessageIdentifiers.HidePasteBarWindow,
                                                                         HidePasteBarWindow);

            Show();
            Activate();
            Focus();
            var firstFocus = VisualHelper.FindVisualChildren <System.Windows.Controls.ListBox>(this).FirstOrDefault();

            firstFocus?.Focus();
            Keyboard.Focus(firstFocus);

            Logger.Instance.Information("Paste bar displayed.");
            var delayer = new Delayer <object>(TimeSpan.FromMilliseconds(50));

            delayer.Action += (o, args) => _openingStoryboard.Begin();
            delayer.ResetAndTick();

            dataContext.DisplayBar();
        }
        /// <summary>
        /// Called when the clipboard content has changed.
        /// </summary>
        /// <param name="sender">The <see cref="ClipboardHook"/>.</param>
        /// <param name="e">The information about the changes.</param>
        internal void ClipboardHook_ClipboardChanged(object sender, Events.ClipboardHookEventArgs e)
        {
            if (_ignoreClipboardChange)
            {
                return;
            }

            _ignoreClipboardChange = true;

            var mouseAndKeyboardHookService = ServiceLocator.GetService <MouseAndKeyboardHookService>();

            mouseAndKeyboardHookService.Pause();
            Pause();

            var delayer = new Delayer <object>(TimeSpan.FromMilliseconds(10));

            delayer.Action += (o, args) =>
            {
                try
                {
                    Logger.Instance.Information($"A data has been copied. The {nameof(ClipboardService)} tries to retrieve the data.");

                    Requires.NotNull(e, nameof(e));
                    DispatcherHelper.ThrowIfNotStaThread();

                    var dataIgnored  = false;
                    var isCreditCard = false;
                    var isPassword   = false;

                    var dataService      = ServiceLocator.GetService <DataService>();
                    var foregroundWindow = ServiceLocator.GetService <WindowsService>().GetForegroundWindow();

                    if (_ignoredApplications.Any(app => app.ApplicationIdentifier == foregroundWindow.ApplicationIdentifier))
                    {
                        dataIgnored = true;
                        Logger.Instance.Information($"The {nameof(ClipboardService)} ignored the data because it comes from an ignored application.");
                    }
                    else
                    {
                        if (e.DataObject.ContainsText())
                        {
                            var text = e.DataObject.GetText();

                            isCreditCard = dataService.IsCreditCard(text);
                            if (isCreditCard && dataService.KeepOrIgnoreCreditCard(text))
                            {
                                dataIgnored = true;
                                Logger.Instance.Information($"The {nameof(ClipboardService)} ignored the data because it is a credit card number.");
                            }

                            isPassword = dataService.IsPassword(text, foregroundWindow);
                            if (isPassword && dataService.KeepOrIgnorePassword(text))
                            {
                                dataIgnored = true;
                                Logger.Instance.Information($"The {nameof(ClipboardService)} ignored the data because it is a password.");
                            }
                        }
                    }

                    if (!dataIgnored)
                    {
                        dataService.Reset();

                        var identifiers = dataService.GetDataIdentifiers(e.DataObject.GetFormats());

                        if (identifiers.Count == 0)
                        {
                            Logger.Instance.Information($"The {nameof(ClipboardService)} ignored the data because it does not detected any compatible data format in the clipboard.");
                        }
                        else
                        {
                            using (Logger.Instance.Stopwatch("Persisting clipboard data to the hard drive."))
                            {
                                dataService.EnsureDataFolderExists();
                                using (var clipboardReader = new ClipboardReader(e.DataObject))
                                {
                                    for (var i = 0; i < identifiers.Count; i++)
                                    {
                                        try
                                        {
                                            WriteClipboardDataToFile(clipboardReader, identifiers[i], dataService.ClipboardDataPath);
                                        }
                                        catch
                                        {
                                            identifiers.RemoveAt(i);
                                            i--;
                                        }
                                    }
                                }
                            }

                            using (Logger.Instance.Stopwatch("Adding a new data entry to the data service."))
                            {
                                dataService.AddDataEntry(e, identifiers, foregroundWindow, isCreditCard, isPassword);
                            }

                            Logger.Instance.Information($"The {nameof(ClipboardService)} successfully retrieved the data from the clipboard.");
                        }
                    }
                }
                catch (Exception exception)
                {
                    Logger.Instance.Error(exception);
                }
                finally
                {
                    delayer         = new Delayer <object>(TimeSpan.FromMilliseconds(10));
                    delayer.Action += (sender1, eventArgs) =>
                    {
                        _ignoreClipboardChange = false;
                        Resume();
                        mouseAndKeyboardHookService.Resume();
                        CoreHelper.MinimizeFootprint();
                    };
                    delayer.ResetAndTick();

                    if (CoreHelper.IsUnitTesting())
                    {
                        Task.Delay(10).Wait();
                        DispatcherHelper.DoEvents();
                    }
                }
            };
            delayer.ResetAndTick();
        }
        /// <summary>
        /// Initialize a new instance of the <see cref="MainWindowViewModel"/> class.
        /// </summary>
        internal MainWindowViewModel()
        {
            InitializeCommands();

            if (IsInDesignMode)
            {
                return;
            }

            var firstStart = Settings.Default.FirstStart;

            if (firstStart)
            {
                var dataMigrationRequired = Settings.Default.DataMigrationRequired;
                var previousVersion       = Settings.Default.CurrentVersion;
                Settings.Default.Upgrade();
                Settings.Default.DataMigrationRequired = dataMigrationRequired;
                if (!string.IsNullOrWhiteSpace(previousVersion))
                {
                    Settings.Default.CurrentVersion = previousVersion;
                }

                ServiceLocator.SettingProvider = new ServiceSettingProvider();
                ServiceLocator.GetService <WindowsService>();

                var firstStartWindow = new FirstStartWindow();
                firstStartWindow.ShowDialog();

                Settings.Default.FirstStart = false;
                Settings.Default.Save();
                Settings.Default.Reload();
            }

            // First call and initialization of services.
            var dataService                 = ServiceLocator.GetService <DataService>();
            var cloudStorageService         = ServiceLocator.GetService <CloudStorageService>();
            var mouseAndKeyboardHookService = ServiceLocator.GetService <MouseAndKeyboardHookService>();

            ServiceLocator.GetService <WindowsService>();
            ServiceLocator.GetService <ClipboardService>();

            dataService.CreditCardNumberDetected       += DataService_CreditCardNumberDetected;
            dataService.CreditCardNumberSaved          += DataService_CreditCardNumberSaved;
            dataService.PasswordDetected               += DataService_PasswordDetected;
            dataService.PasswordSaved                  += DataService_PasswordSaved;
            cloudStorageService.SynchronizationStarted += CloudStorageService_SynchronizationStarted;
            cloudStorageService.SynchronizationFailed  += CloudStorageService_SynchronizationFailed;
            cloudStorageService.SynchronizationEnded   += CloudStorageService_SynchronizationEnded;

            _timer          = new DispatcherTimer();
            _timer.Tick    += TimerOnTick;
            _timer.Interval = TimeSpan.FromMilliseconds(5000);
            _timer.Start();

            _delayedPasteCommand         = new Delayer <object>(TimeSpan.FromMilliseconds(10));
            _delayedPasteCommand.Action += DelayedPasteCommand;

            mouseAndKeyboardHookService.Pause();
            CreateNewPasteBar();
            mouseAndKeyboardHookService.DelayedResume(TimeSpan.FromSeconds(1));

            Messenger.Default.Register <Message>(this, MessageIdentifiers.PasteData, PasteData);

            SetNormalNotifyIcon();
            ShowNotifyIcon();

            if (firstStart)
            {
                var delayedNotification = new Delayer <object>(TimeSpan.FromSeconds(2));
                delayedNotification.Action += (sender, args) => MessengerInstance.Send(new Message(Language.FirstStartWindow.Welcome_Title, Language.FirstStartWindow.Welcome_Text), MessageIdentifiers.ShowNotifyIconBalloon);
                delayedNotification.ResetAndTick();
            }
        }