PageRenderTime 225ms CodeModel.GetById 19ms app.highlight 168ms RepoModel.GetById 1ms app.codeStats 2ms

/verve patch/base/Applications/BetterExplorer/BExplorer/BetterExplorer/MainWindow.xaml.cs

https://bitbucket.org/jdm7dvmoore/msft-research-verve
C# | 4158 lines | 3239 code | 628 blank | 291 comment | 747 complexity | 4806bfa8d44f4dae5cca83557fa289ee MD5 | raw file
   1// --------------------------------------------------------------------------------------------------------------------
   2// <copyright file="MainWindow.xaml.cs" company="Gainedge ORG">
   3//   Better Explorer (c)2016
   4// </copyright>
   5// <summary>
   6//   Interaction logic for MainWindow.xaml
   7// </summary>
   8// --------------------------------------------------------------------------------------------------------------------
   9
  10using System;
  11using System.Collections.Generic;
  12using System.Collections.Specialized;
  13using System.ComponentModel;
  14using System.Diagnostics;
  15using System.Drawing;
  16using System.Drawing.Imaging;
  17using System.IO;
  18using System.Linq;
  19using System.Net;
  20using System.Reflection;
  21using System.Runtime.InteropServices;
  22using System.ServiceModel;
  23using System.Text;
  24using System.Threading;
  25using System.Threading.Tasks;
  26using System.Windows;
  27using System.Windows.Controls;
  28using System.Windows.Controls.Primitives;
  29using System.Windows.Input;
  30using System.Windows.Interop;
  31using System.Windows.Media;
  32using System.Windows.Media.Imaging;
  33using System.Windows.Shell;
  34using System.Windows.Threading;
  35using System.Xml;
  36using System.Xml.Linq;
  37using BEHelper;
  38using BetterExplorer.UsbEject;
  39using BetterExplorerControls;
  40using BExplorer.Shell;
  41using BExplorer.Shell._Plugin_Interfaces;
  42using BExplorer.Shell.CommonFileDialogs;
  43using BExplorer.Shell.DropTargetHelper;
  44using BExplorer.Shell.Interop;
  45using Fluent;
  46using LTR.IO.ImDisk;
  47using Microsoft.Win32;
  48using Settings;
  49using SevenZip;
  50using Shell32;
  51using TaskDialogInterop;
  52using wyDay.Controls;
  53
  54using Clipboards = System.Windows.Forms.Clipboard;
  55using ContextMenu = Fluent.ContextMenu;
  56using Image = System.Windows.Controls.Image;
  57using MenuItem = Fluent.MenuItem;
  58using WIN = System.Windows;
  59
  60namespace BetterExplorer {
  61
  62  /// <summary>
  63  /// Interaction logic for MainWindow.xaml
  64  /// </summary>
  65  public partial class MainWindow : Fluent.RibbonWindow {
  66
  67    #region DLLImports
  68
  69    [DllImport("user32.dll")]
  70    [return: MarshalAs(UnmanagedType.Bool)]
  71    internal static extern bool GetCursorPos(ref BExplorer.Shell.DataObject.Win32Point pt);
  72
  73    //[DllImport("user32.dll", SetLastError = true)]
  74    //private static extern int RegisterHotKey(IntPtr hwnd, int id, int fsModifiers, int vk);
  75
  76    //[DllImport("user32.dll", SetLastError = true)]
  77    //private static extern int UnregisterHotKey(IntPtr hwnd, int id);
  78
  79    [DllImport("winmm.dll")]
  80    static extern Int32 mciSendString(String command, StringBuilder buffer, Int32 bufferSize, IntPtr hwndCallback);
  81
  82    #endregion
  83
  84    #region Private Members
  85    private bool _IsCalledFromLoading, isOnLoad;
  86    private MenuItem misa, misd, misag, misdg;
  87    private ShellTreeViewEx ShellTree = new ShellTreeViewEx();
  88    private ShellView _ShellListView = new ShellView();
  89    private bool IsNeedEnsureVisible;
  90    private ClipboardMonitor cbm = new ClipboardMonitor();
  91    private ContextMenu _CMHistory = new ContextMenu();
  92    private WIN.Shell.JumpList AppJL = new WIN.Shell.JumpList();
  93    //private List<string> Archives = new List<string>(new[] { ".rar", ".zip", ".7z", ".tar", ".gz", ".xz", ".bz2" });
  94    private List<string> Images = new List<string>(new[] { ".jpg", ".jpeg", ".png", ".bmp", ".gif", ".wmf" });
  95    private string SelectedArchive = "";
  96    private bool KeepBackstageOpen = false;
  97    string sessionid = DateTime.UtcNow.ToFileTimeUtc().ToString();
  98    string logdir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\BExplorer\\ActionLog\\";
  99    WIN.Forms.Timer updateCheckTimer = new WIN.Forms.Timer();
 100    Double CommandPromptWinHeight;
 101
 102    //List<LVItemColor> LVItemsColor { get; set; }
 103    ContextMenu chcm;
 104
 105    WIN.Forms.Timer focusTimer = new WIN.Forms.Timer() { Interval = 500 };
 106    private WIN.Forms.Timer _ProgressTimer = new WIN.Forms.Timer() { Interval = 1000, Enabled = false };
 107    private string _DBPath = Path.Combine(KnownFolders.RoamingAppData.ParsingName, @"BExplorer\Settings.sqlite");
 108
 109    private IntPtr Handle;
 110    private ObservableCollectionEx<LVItemColor> LVItemsColorCol { get; set; }
 111    public Dictionary<String, Dictionary<IListItemEx, List<string>>> Badges { get; set; }
 112    #endregion
 113
 114    public bool IsMultipleWindowsOpened { get; set; }
 115
 116    #region Events
 117
 118    private void btnAbout_Click(object sender, RoutedEventArgs e) => new fmAbout(this).ShowDialog();
 119    private void btnBugtracker_Click(object sender, RoutedEventArgs e) => Process.Start("http://bugs.gainedge.org/public/betterexplorer");
 120    private void TheRibbon_CustomizeQuickAccessToolbar(object sender, EventArgs e) => CustomizeQAT.Open(this, TheRibbon);
 121
 122    private void btnConsolePane_Click(object sender, RoutedEventArgs e) {
 123      Settings.BESettings.IsConsoleShown = btnConsolePane.IsChecked.Value;
 124      Settings.BESettings.SaveSettings();
 125      if (btnConsolePane.IsChecked.Value) {
 126        rCommandPrompt.Height = new GridLength(this.CommandPromptWinHeight);
 127        rCommandPrompt.MinHeight = 100;
 128        spCommandPrompt.Height = GridLength.Auto;
 129        if (!ctrlConsole.IsProcessRunning)
 130          ctrlConsole.ChangeFolder(_ShellListView.CurrentFolder.ParsingName, _ShellListView.CurrentFolder.IsFileSystem);
 131      } else {
 132        rCommandPrompt.MinHeight = 0;
 133        rCommandPrompt.Height = new GridLength(0);
 134        spCommandPrompt.Height = new GridLength(0);
 135        ctrlConsole.StopProcess();
 136      }
 137    }
 138    private void backstage_IsOpenChanged(object sender, DependencyPropertyChangedEventArgs e) {
 139      if ((Boolean)e.NewValue) {
 140        this._ShellListView.IsFocusAllowed = false;
 141        this.backstage.Focus();
 142      } else {
 143        this._ShellListView.IsFocusAllowed = true;
 144      }
 145      this.autoUpdater.Visibility = Visibility.Visible;
 146      this.autoUpdater.UpdateLayout();
 147
 148      if (this.KeepBackstageOpen) {
 149        this.backstage.IsOpen = true;
 150        this.KeepBackstageOpen = false;
 151      }
 152    }
 153
 154    /// <summary>
 155    /// Loads initial position of the main window
 156    /// </summary>
 157    private void LoadInitialWindowPositionAndState() {
 158      this.Width = BESettings.LastWindowWidth;
 159      this.Height = BESettings.LastWindowHeight;
 160
 161      var location = new System.Drawing.Point();
 162      try {
 163        location = new System.Drawing.Point((int)BESettings.LastWindowPosLeft, (int)BESettings.LastWindowPosTop);
 164      } catch { }
 165
 166      this.Left = location.X;
 167      this.Top = location.Y;
 168
 169      switch (BESettings.LastWindowState) {
 170        case 2:
 171          this.WindowState = WindowState.Maximized;
 172          break;
 173        case 1:
 174          this.WindowState = WindowState.Minimized;
 175          break;
 176        case 0:
 177          this.WindowState = WindowState.Normal;
 178          break;
 179        default:
 180          this.WindowState = WindowState.Maximized;
 181          break;
 182      }
 183
 184      this.chkRibbonMinimizedGlass.IsChecked = BESettings.IsGlassOnRibonMinimized;
 185      this.TheRibbon.IsMinimized = BESettings.IsRibonMinimized;
 186
 187      //CommandPrompt window size
 188      this.CommandPromptWinHeight = BESettings.CmdWinHeight;
 189      this.rCommandPrompt.Height = new GridLength(this.CommandPromptWinHeight);
 190
 191      if (BESettings.IsConsoleShown) {
 192        this.rCommandPrompt.MinHeight = 100;
 193        this.rCommandPrompt.Height = new GridLength(this.CommandPromptWinHeight);
 194        this.spCommandPrompt.Height = GridLength.Auto;
 195      } else {
 196        this.rCommandPrompt.MinHeight = 0;
 197        this.rCommandPrompt.Height = new GridLength(0);
 198        this.spCommandPrompt.Height = new GridLength(0);
 199      }
 200    }
 201
 202    private void LoadColorCodesFromFile() {
 203      Task.Run(() => {
 204        var itemColorSettingsLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"BExplorer\itemcolors.cfg");
 205
 206        if (File.Exists(itemColorSettingsLocation)) {
 207          var docs = XDocument.Load(itemColorSettingsLocation);
 208
 209          docs.Root.Elements("ItemColorRow")
 210            .Select(
 211              element =>
 212                new LVItemColor(
 213                  element.Elements().ToArray()[0].Value,
 214                  WIN.Media.Color.FromArgb(
 215                    BitConverter.GetBytes(Convert.ToInt32(element.Elements().ToArray()[1].Value))[0],
 216                    BitConverter.GetBytes(Convert.ToInt32(element.Elements().ToArray()[1].Value))[1],
 217                    BitConverter.GetBytes(Convert.ToInt32(element.Elements().ToArray()[1].Value))[2],
 218                    BitConverter.GetBytes(Convert.ToInt32(element.Elements().ToArray()[1].Value))[3])))
 219            .ToList().ForEach(e => this.LVItemsColorCol.Add(e));
 220
 221        }
 222      });
 223    }
 224
 225    private void RibbonWindow_Initialized(object sender, EventArgs e) {
 226      this.LoadInitialWindowPositionAndState();
 227      this.LoadColorCodesFromFile();
 228
 229      AppCommands.RoutedNewTab.InputGestures.Add(new KeyGesture(Key.T, ModifierKeys.Control));
 230      AppCommands.RoutedEnterInBreadCrumbCombo.InputGestures.Add(new KeyGesture(Key.E, ModifierKeys.Alt));
 231      AppCommands.RoutedChangeTab.InputGestures.Add(new KeyGesture(Key.Tab, ModifierKeys.Control));
 232      AppCommands.RoutedCloseTab.InputGestures.Add(new KeyGesture(Key.W, ModifierKeys.Control));
 233      AppCommands.RoutedNavigateBack.InputGestures.Add(new KeyGesture(Key.Left, ModifierKeys.Alt));
 234      AppCommands.RoutedNavigateFF.InputGestures.Add(new KeyGesture(Key.Right, ModifierKeys.Alt));
 235      AppCommands.RoutedNavigateUp.InputGestures.Add(new KeyGesture(Key.Up, ModifierKeys.Alt));
 236      AppCommands.RoutedGotoSearch.InputGestures.Add(new KeyGesture(Key.F, ModifierKeys.Control));
 237    }
 238
 239    #region ViewEnumerationComplete
 240
 241    /// <summary>
 242    /// Sets up btnSort and btnGroup so they have the correct items after navigating 
 243    /// </summary>
 244    private void SetSortingAndGroupingButtons() {
 245      btnSort.Items.Clear();
 246      btnGroup.Items.Clear();
 247
 248      try {
 249        foreach (Collumns item in _ShellListView.Collumns.Where(x => x != null)) {
 250          var lastSortedColumn = _ShellListView.Collumns.FirstOrDefault(w => w.ID == this._ShellListView.LastSortedColumnId);
 251          if (lastSortedColumn != null) {
 252            var IsChecked1 = (item.pkey.fmtid == lastSortedColumn.pkey.fmtid) && (item.pkey.pid == lastSortedColumn.pkey.pid);
 253            btnSort.Items.Add(Utilities.Build_MenuItem(item.Name, item, checkable: true, isChecked: IsChecked1, GroupName: "GR2", onClick: mi_Click));
 254          }
 255          var IsCheckable2 = _ShellListView.LastGroupCollumn != null && (item.pkey.fmtid == _ShellListView.LastGroupCollumn.pkey.fmtid) && (item.pkey.pid == _ShellListView.LastGroupCollumn.pkey.pid);
 256          btnGroup.Items.Add(Utilities.Build_MenuItem(item.Name, item, checkable: true, isChecked: IsCheckable2, GroupName: "GR3", onClick: mig_Click));
 257        }
 258      } catch (Exception ex) {
 259        //FIXME: I disable this message because of strange null after filter
 260        MessageBox.Show("BetterExplorer had an issue loading the visible columns for the current view. You might not be able to sort or group items.", ex.ToString(), MessageBoxButton.OK, MessageBoxImage.Error);
 261      }
 262
 263      btnSort.Items.Add(new Separator() { Focusable = false });
 264      misa = Utilities.Build_MenuItem(FindResource("miAscending"), checkable: true, GroupName: "GR1", onClick: misa_Click);
 265      misd = Utilities.Build_MenuItem(FindResource("miDescending"), checkable: true, GroupName: "GR1", onClick: misd_Click);
 266
 267      if (this._ShellListView.LastSortOrder == WIN.Forms.SortOrder.Ascending)
 268        misa.IsChecked = true;
 269      else
 270        misd.IsChecked = true;
 271
 272      btnSort.Items.Add(misa);
 273      btnSort.Items.Add(misd);
 274
 275      btnGroup.Items.Add(Utilities.Build_MenuItem("(none)", GroupName: "GR3", checkable: true, isChecked: _ShellListView.LastGroupCollumn == null, onClick: misng_Click));
 276      btnGroup.Items.Add(new Separator());
 277
 278      misag = Utilities.Build_MenuItem(FindResource("miAscending"), checkable: true, GroupName: "GR4", onClick: misag_Click);
 279      misdg = Utilities.Build_MenuItem(FindResource("miDescending"), checkable: true, GroupName: "GR4", onClick: misag_Click);
 280
 281      if (this._ShellListView.LastGroupOrder == WIN.Forms.SortOrder.Ascending)
 282        misag.IsChecked = true;
 283      else
 284        misdg.IsChecked = true;
 285
 286      btnGroup.Items.Add(misag);
 287      btnGroup.Items.Add(misdg);
 288    }
 289
 290    void misag_Click(object sender, RoutedEventArgs e) {
 291      this._ShellListView.SetGroupOrder();
 292    }
 293
 294    private void SetupColumnsButton() {
 295      var allAvailColls = this._ShellListView.AllAvailableColumns.Values.ToList();
 296      btnMoreColls.Items.Clear();
 297      chcm.Items.Clear();
 298
 299      for (int j = 1; j < 10; j++) {
 300        //TODO: Try to remove this Try Catch!!
 301        try {
 302          var IsChecked = _ShellListView.Collumns.Any(col => col.pkey.fmtid == allAvailColls[j].pkey.fmtid && col.pkey.pid == allAvailColls[j].pkey.pid);
 303          btnMoreColls.Items.Add(Utilities.Build_MenuItem(allAvailColls[j].Name, allAvailColls[j], checkable: true, onClick: mic_Click, isChecked: IsChecked));
 304          chcm.Items.Add(Utilities.Build_MenuItem(allAvailColls[j].Name, allAvailColls[j], checkable: true, onClick: mic_Click, isChecked: IsChecked));
 305        } catch (Exception) {
 306        }
 307      }
 308
 309      int ItemsCount = _ShellListView.Items.Count;
 310      sbiItemsCount.Visibility = ItemsCount == 0 ? Visibility.Collapsed : Visibility.Visible;
 311      sbiItemsCount.Content = ItemsCount == 1 ? "1 item" : ItemsCount + " items";
 312      sbiSelItemsCount.Visibility = _ShellListView.GetSelectedCount() == 0 ? Visibility.Collapsed : Visibility.Visible;
 313      spSelItems.Visibility = sbiSelItemsCount.Visibility;
 314
 315      btnMoreColls.Items.Add(new Separator());
 316      btnMoreColls.Items.Add(Utilities.Build_MenuItem(FindResource("btnMoreColCP"), allAvailColls, onClick: micm_Click));
 317      btnMoreColls.Tag = allAvailColls;
 318
 319      chcm.Items.Add(new Separator());
 320      chcm.Items.Add(Utilities.Build_MenuItem(FindResource("btnMoreColCP"), allAvailColls, onClick: micm_Click));
 321    }
 322
 323    #endregion
 324
 325    void misd_Click(object sender, RoutedEventArgs e) {
 326      foreach (var item in btnSort.Items.OfType<MenuItem>().Where(item => item.IsChecked && item != (sender as MenuItem))) {
 327        _ShellListView.SetSortCollumn(true, (Collumns)item.Tag, WIN.Forms.SortOrder.Descending);
 328      }
 329    }
 330
 331    void misa_Click(object sender, RoutedEventArgs e) {
 332      foreach (var item in btnSort.Items.OfType<MenuItem>().Where(item => item.IsChecked && item != (sender as MenuItem))) {
 333        _ShellListView.SetSortCollumn(true, (Collumns)item.Tag, WIN.Forms.SortOrder.Ascending);
 334      }
 335    }
 336
 337    void micm_Click(object sender, RoutedEventArgs e) {
 338      var fMoreCollumns = new MoreColumns();
 339      fMoreCollumns.PopulateAvailableColumns((List<Collumns>)(sender as FrameworkElement).Tag, this._ShellListView, this.PointToScreen(Mouse.GetPosition(this)));
 340    }
 341
 342    void mic_Click(object sender, RoutedEventArgs e) {
 343      var mi = (sender as MenuItem);
 344      Collumns col = (Collumns)mi.Tag;
 345      _ShellListView.SetColInView(col, !mi.IsChecked);
 346    }
 347
 348    void miItem_Click(object sender, RoutedEventArgs e) {
 349      MenuItem mi = sender as MenuItem;
 350      ShellItem SaveLoc = mi.Tag as ShellItem;
 351
 352      if (_ShellListView.CurrentFolder.ParsingName.Contains(KnownFolders.Libraries.ParsingName) && _ShellListView.CurrentFolder.ParsingName.EndsWith("library-ms")) {
 353        var lib = ShellLibrary.Load(Path.GetFileNameWithoutExtension(_ShellListView.CurrentFolder.ParsingName), false);
 354        lib.DefaultSaveFolder = SaveLoc.ParsingName;
 355        lib.Close();
 356      } else if (_ShellListView.GetFirstSelectedItem().ParsingName.Contains(KnownFolders.Libraries.ParsingName)) {
 357        var lib = ShellLibrary.Load(Path.GetFileNameWithoutExtension(_ShellListView.GetFirstSelectedItem().ParsingName), false);
 358        lib.DefaultSaveFolder = SaveLoc.ParsingName;
 359        lib.Close();
 360      }
 361    }
 362
 363    void LinksFolderWarcher_Renamed(object sender, RenamedEventArgs e) {
 364      Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(
 365          () => btnFavorites.Items.OfType<MenuItem>().First(x => (x.Tag as ShellItem).ParsingName == e.OldFullPath).Header = Path.GetFileNameWithoutExtension(e.Name)));
 366    }
 367
 368    void LinksFolderWarcher_Deleted(object sender, FileSystemEventArgs e) {
 369      Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(
 370          () => btnFavorites.Items.Remove(btnFavorites.Items.OfType<MenuItem>().First(item => item.Header.ToString() == Path.GetFileNameWithoutExtension(e.Name)))));
 371    }
 372
 373    void LinksFolderWarcher_Created(object sender, FileSystemEventArgs e) {
 374      Dispatcher.BeginInvoke(DispatcherPriority.Normal,
 375                      (Action)(() => {
 376                        if (Path.GetExtension(e.FullPath).ToLowerInvariant() == ".lnk") {
 377                          var so = new ShellItem(e.FullPath);
 378                          so.Thumbnail.FormatOption = ShellThumbnailFormatOption.IconOnly;
 379                          so.Thumbnail.CurrentSize = new WIN.Size(16, 16);
 380                          ImageSource icon = so.Thumbnail.BitmapSource;
 381
 382                          btnFavorites.Items.Add(Utilities.Build_MenuItem(so.DisplayName, so, icon, onClick: mif_Click));
 383                        }
 384                      }));
 385    }
 386
 387    /// <summary>
 388    /// Sets up each ribbon tab after select or navigate in ShellListView
 389    /// </summary>
 390    /// <param name="selectedItemsCount">The number of items selected</param>
 391    /// <param name="selectedItem">The last selected item</param>
 392    /// <remarks>
 393    /// Only used in SetupUIOnSelectOrNavigate
 394    /// </remarks>
 395    private void SetUpRibbonTabsVisibilityOnSelectOrNavigate(int selectedItemsCount, IListItemEx selectedItem) {
 396      #region Search Contextual Tab
 397      ctgSearch.Visibility = BooleanToVisibiliy(_ShellListView.CurrentFolder.IsSearchFolder);
 398      if (ctgSearch.Visibility == Visibility.Visible && !_ShellListView.CurrentFolder.IsSearchFolder) {
 399        ctgSearch.Visibility = Visibility.Collapsed;
 400        TheRibbon.SelectedTabItem = HomeTab;
 401      }
 402      #endregion
 403
 404      #region Folder Tools Context Tab
 405      ctgFolderTools.Visibility = BooleanToVisibiliy((selectedItemsCount == 1 && selectedItem.IsFolder && selectedItem.IsFileSystem && !selectedItem.IsDrive && !selectedItem.IsNetworkPath));
 406
 407      if (BESettings.AutoSwitchFolderTools && ctgFolderTools.Visibility == Visibility.Visible) {
 408        TheRibbon.SelectedTabItem = ctgFolderTools.Items[0];
 409      }
 410      #endregion
 411
 412      #region Drive Contextual Tab
 413      ctgDrive.Visibility = BooleanToVisibiliy(_ShellListView.CurrentFolder.IsDrive || (selectedItemsCount == 1 && (selectedItem.IsDrive || (selectedItem.Parent != null && selectedItem.Parent.IsDrive))));
 414      if (BESettings.AutoSwitchDriveTools && ctgDrive.Visibility == Visibility.Visible && selectedItemsCount == 1 && selectedItem.IsDrive) {
 415        TheRibbon.SelectedTabItem = ctgDrive.Items[0];
 416      }
 417      #endregion
 418
 419      #region Library Context Tab
 420      ctgLibraries.Visibility = BooleanToVisibiliy((selectedItemsCount == 1 && _ShellListView.CurrentFolder.ParsingName.Equals(KnownFolders.Libraries.ParsingName)) || (selectedItemsCount == 1 && selectedItem.Parent != null && selectedItem.Parent.ParsingName.Equals(KnownFolders.Libraries.ParsingName)));
 421
 422      if (ctgLibraries.Visibility == Visibility.Visible && BESettings.AutoSwitchLibraryTools) {
 423        TheRibbon.SelectedTabItem = ctgLibraries.Items[0];
 424      }
 425
 426      /*
 427        if (ctgLibraries.Visibility == Visibility.Visible && _ShellListView.CurrentFolder.ParsingName.Equals(KnownFolders.Libraries.ParsingName)) {
 428          if (selectedItem != null && selectedItemsCount == 1)
 429            SetupLibrariesTab(ShellLibrary.Load(Path.GetFileNameWithoutExtension(selectedItem.ParsingName), false));
 430        } else if (ctgLibraries.Visibility == Visibility.Visible && _ShellListView.CurrentFolder.Parent.ParsingName.Equals(KnownFolders.Libraries.ParsingName)) {
 431          if (selectedItemsCount == 1)
 432            SetupLibrariesTab(ShellLibrary.Load(Path.GetFileNameWithoutExtension(_ShellListView.CurrentFolder.ParsingName), false));
 433        }
 434        if (selectedItemsCount == 0) {
 435          ctgLibraries.Visibility = Visibility.Collapsed;
 436        }
 437      */
 438      if (selectedItemsCount == 0)
 439        ctgLibraries.Visibility = Visibility.Collapsed;
 440      else if (selectedItemsCount > 1) { } else if (ctgLibraries.Visibility == Visibility.Visible && _ShellListView.CurrentFolder.ParsingName.Equals(KnownFolders.Libraries.ParsingName))
 441        SetupLibrariesTab(ShellLibrary.Load(Path.GetFileNameWithoutExtension(selectedItem.ParsingName), false));
 442      else if (ctgLibraries.Visibility == Visibility.Visible && _ShellListView.CurrentFolder.Parent.ParsingName.Equals(KnownFolders.Libraries.ParsingName))
 443        SetupLibrariesTab(ShellLibrary.Load(Path.GetFileNameWithoutExtension(_ShellListView.CurrentFolder.ParsingName), false));
 444
 445      #endregion
 446
 447      #region Archive Contextual Tab
 448      ctgArchive.Visibility = WIN.Visibility.Collapsed; //TODO: Restore this: BooleanToVisibiliy(selectedItemsCount == 1 && Archives.Contains(Path.GetExtension(selectedItem.ParsingName).ToLowerInvariant()));
 449      if (BESettings.AutoSwitchArchiveTools && ctgArchive.Visibility == Visibility.Visible)
 450        TheRibbon.SelectedTabItem = ctgArchive.Items[0];
 451
 452      #endregion
 453
 454      #region Application Context Tab
 455      ctgExe.Visibility = BooleanToVisibiliy(selectedItemsCount == 1 && !selectedItem.IsFolder && (Path.GetExtension(selectedItem.ParsingName).ToLowerInvariant() == ".exe" || Path.GetExtension(selectedItem.ParsingName).ToLowerInvariant() == ".msi"));
 456      if (BESettings.AutoSwitchApplicationTools && ctgExe.Visibility == Visibility.Visible) {
 457        TheRibbon.SelectedTabItem = ctgExe.Items[0];
 458      }
 459      #endregion
 460
 461      #region Image Context Tab
 462      ctgImage.Visibility = BooleanToVisibiliy(selectedItemsCount == 1 && !selectedItem.IsFolder && Images.Contains(Path.GetExtension(selectedItem.ParsingName).ToLowerInvariant()));
 463      if (ctgImage.Visibility == Visibility.Visible) {
 464        try {
 465          if (new FileInfo(selectedItem.ParsingName).Length != 0) {
 466            using (var cvt = new Bitmap(selectedItem.ParsingName)) {
 467              imgSizeDisplay.WidthData = cvt.Width.ToString();
 468              imgSizeDisplay.HeightData = cvt.Height.ToString();
 469
 470              if (BESettings.AutoSwitchImageTools) TheRibbon.SelectedTabItem = ctgImage.Items[0];
 471            }
 472          }
 473        } catch (Exception) {
 474          MessageBox.Show("Image was invalid");
 475        }
 476      }
 477      #endregion
 478
 479      #region Virtual Disk Context Tab
 480      ctgVirtualDisk.Visibility = BooleanToVisibiliy(selectedItemsCount == 1 && !selectedItem.IsFolder && Path.GetExtension(selectedItem.ParsingName).ToLowerInvariant() == ".iso");
 481      if (BESettings.AutoSwitchVirtualDriveTools && ctgVirtualDisk.Visibility == Visibility.Visible) {
 482        TheRibbon.SelectedTabItem = ctgVirtualDisk.Items[0];
 483      }
 484      #endregion
 485
 486    }
 487
 488    /// <summary>
 489    /// Sets up the status bar
 490    /// </summary>
 491    /// <param name="selectedItemsCount">The number of items currently selected</param>
 492    private void SetUpStatusBarOnSelectOrNavigate(int selectedItemsCount) {
 493      spSelItems.Visibility = BooleanToVisibiliy(selectedItemsCount > 0);
 494      sbiSelItemsCount.Visibility = BooleanToVisibiliy(selectedItemsCount > 0);
 495      if (selectedItemsCount == 1)
 496        sbiSelItemsCount.Content = "1 item selected";
 497      else if (selectedItemsCount > 1)
 498        sbiSelItemsCount.Content = selectedItemsCount.ToString() + " items selected";
 499    }
 500
 501    private void SetUpButtonsStateOnSelectOrNavigate(int selectedItemsCount, IListItemEx selectedItem) {
 502      btnBadges.IsEnabled = selectedItemsCount > 0;
 503      btnCopy.IsEnabled = selectedItemsCount > 0;
 504      btnCopyto.IsEnabled = selectedItemsCount > 0;
 505      btnMoveto.IsEnabled = selectedItemsCount > 0;
 506      btnCut.IsEnabled = selectedItemsCount > 0;
 507      btnDelete.IsEnabled = selectedItem != null && selectedItem.IsFileSystem;
 508      btnRename.IsEnabled = selectedItem != null && (selectedItem.IsFileSystem || (selectedItem.Parent != null && selectedItem.Parent.Equals(KnownFolders.Libraries)));
 509      btnProperties3.IsEnabled = selectedItemsCount > 0;
 510      if (selectedItem != null) {
 511        var rg = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\" + Path.GetExtension(selectedItem.ParsingName) + @"\OpenWithProgids");
 512        if (rg == null)
 513          btnEdit.IsEnabled = false;
 514        else {
 515          string filetype = rg.GetValueNames()[0];
 516          rg.Close();
 517
 518          using (var rgtype = Registry.ClassesRoot.OpenSubKey(filetype + @"\shell\edit\command")) {
 519            btnEdit.IsEnabled = !(rgtype == null);
 520          }
 521        }
 522      }
 523
 524      btnSelAll.IsEnabled = selectedItemsCount != _ShellListView.Items.Count;
 525      btnSelNone.IsEnabled = selectedItemsCount > 0;
 526      btnShare.IsEnabled = selectedItemsCount == 1 && selectedItem.IsFolder;
 527      btnAdvancedSecurity.IsEnabled = selectedItemsCount == 1;
 528      btnHideSelItems.IsEnabled = _ShellListView.CurrentFolder.IsFileSystem;
 529    }
 530
 531    private void SetupLibrariesTab(ShellLibrary lib) {
 532      IsFromSelectionOrNavigation = true;
 533      chkPinNav.IsChecked = lib.IsPinnedToNavigationPane;
 534      IsFromSelectionOrNavigation = false;
 535
 536      foreach (ShellItem item in lib) {
 537        item.Thumbnail.FormatOption = ShellThumbnailFormatOption.IconOnly;
 538        item.Thumbnail.CurrentSize = new WIN.Size(16, 16);
 539
 540        btnDefSave.Items.Add(Utilities.Build_MenuItem(item.GetDisplayName(SIGDN.NORMALDISPLAY), item, item.Thumbnail.BitmapSource, GroupName: "GRDS1", checkable: true,
 541                                                      isChecked: item.ParsingName == lib.DefaultSaveFolder, onClick: miItem_Click));
 542      }
 543
 544      btnDefSave.IsEnabled = lib.Count != 0;
 545      lib.Close();
 546    }
 547
 548    /// <summary>
 549    /// Does setup required for the UI when navigation occurs to a new folder
 550    /// </summary>
 551    private void SetupUIOnSelectOrNavigate() {
 552      Dispatcher.BeginInvoke(DispatcherPriority.Background, (ThreadStart)(() => {
 553        btnDefSave.Items.Clear();
 554        var selItemsCount = _ShellListView.GetSelectedCount();
 555        var selectedItem = this._ShellListView.GetFirstSelectedItem();
 556
 557        if (selectedItem == null) {
 558          btnOpenWith.IsEnabled = false;
 559        } else {
 560          var mnu = new ShellContextMenu(this._ShellListView, false);
 561
 562          try {
 563            var tempPoint = btnOpenWith.PointToScreen(new WIN.Point(0, 0));
 564            var itemMenuCount = mnu.ShowContextMenu(new System.Drawing.Point((int)tempPoint.X, (int)tempPoint.Y + (int)btnOpenWith.ActualHeight), 1, false);
 565            btnOpenWith.IsEnabled = itemMenuCount > 0 && selItemsCount == 1;
 566          } catch {
 567            btnOpenWith.IsEnabled = false;
 568          }
 569        }
 570
 571        btnNewItem.IsEnabled = this._ShellListView.CurrentFolder.IsFileSystem || this._ShellListView.CurrentFolder.ParsingName == KnownFolders.Libraries.ParsingName;
 572        if (selectedItem != null && selectedItem.IsFileSystem && BESettings.IsPreviewPaneEnabled && !selectedItem.IsFolder && selItemsCount == 1)
 573          this.Previewer.FileName = selectedItem.ParsingName;
 574        else if (!String.IsNullOrEmpty(this.Previewer.FileName))
 575          this.Previewer.FileName = null;
 576
 577        //Set up ribbon contextual tabs on selection changed
 578        SetUpRibbonTabsVisibilityOnSelectOrNavigate(selItemsCount, selectedItem);
 579        SetUpButtonsStateOnSelectOrNavigate(selItemsCount, selectedItem);
 580      }));
 581    }
 582
 583    bool IsFromSelectionOrNavigation = false;
 584
 585    void cbm_ClipboardChanged(object sender, Tuple<WIN.Forms.IDataObject> e) {
 586      btnPaste.IsEnabled = e.Item1.GetDataPresent(DataFormats.FileDrop) || e.Item1.GetDataPresent("Shell IDList Array");
 587      btnPasetShC.IsEnabled = e.Item1.GetDataPresent(DataFormats.FileDrop) || e.Item1.GetDataPresent("Shell IDList Array");
 588    }
 589
 590    #endregion
 591
 592    #region Conditional Select
 593
 594    private void miSelAllByType_Click(object sender, RoutedEventArgs e) {
 595      if (_ShellListView.GetSelectedCount() > 0) {
 596        var typePK = new PROPERTYKEY() { fmtid = Guid.Parse("B725F130-47EF-101A-A5F1-02608C9EEBAC"), pid = 4 };
 597        var flt = _ShellListView.SelectedItems.Select(item => item.GetPropertyValue(typePK, typeof(String)).Value.ToString().ToLowerInvariant());
 598        var items = _ShellListView.Items.Where(w => flt.Contains(w.GetPropertyValue(typePK, typeof(String)).Value.ToString().ToLowerInvariant())).ToArray();
 599        _ShellListView.SelectItems(items);
 600        btnCondSel.IsDropDownOpen = false;
 601      }
 602    }
 603
 604    private void miSelAllByDate_Click(object sender, RoutedEventArgs e) {
 605      if (_ShellListView.GetSelectedCount() > 0) {
 606        var typePK = new PROPERTYKEY() { fmtid = Guid.Parse("b725f130-47ef-101a-a5f1-02608c9eebac"), pid = 15 };
 607        var flt = _ShellListView.SelectedItems.Select(item => DateTime.Parse(item.GetPropertyValue(typePK, typeof(String)).Value.ToString().ToLowerInvariant()).Date);
 608        var items = _ShellListView.Items.Where(w => flt.Contains(DateTime.Parse(w.GetPropertyValue(typePK, typeof(String)).Value.ToString().ToLowerInvariant()).Date)).ToArray();
 609        _ShellListView.SelectItems(items);
 610        btnCondSel.IsDropDownOpen = false;
 611      }
 612    }
 613
 614    private void btnCondSel_Click(object sender, RoutedEventArgs e) {
 615      btnCondSel.IsDropDownOpen = false;
 616      ConditionalSelectForm.Open(_ShellListView);
 617    }
 618
 619    #endregion
 620
 621    #region Size Chart
 622
 623    private void btnFSizeChart_Click(object sender, RoutedEventArgs e) {
 624      if (_ShellListView.GetSelectedCount() > 0) {
 625        if ((_ShellListView.GetFirstSelectedItem().IsFolder || _ShellListView.GetFirstSelectedItem().IsDrive) && _ShellListView.GetFirstSelectedItem().IsFileSystem) {
 626          FolderSizeWindow.Open(_ShellListView.GetFirstSelectedItem().ParsingName, this);
 627          return;
 628        }
 629      } else if ((_ShellListView.CurrentFolder.IsFolder || _ShellListView.CurrentFolder.IsDrive) && _ShellListView.CurrentFolder.IsFileSystem) {
 630        FolderSizeWindow.Open(_ShellListView.CurrentFolder.ParsingName, this);
 631      }
 632    }
 633
 634    private void btnSizeChart_Click(object sender, RoutedEventArgs e) {
 635      FolderSizeWindow.Open(_ShellListView.CurrentFolder.ParsingName, this);
 636    }
 637
 638    #endregion
 639
 640    #region Home Tab
 641
 642    private void btnctDocuments_Click(object sender, RoutedEventArgs e) => SetFOperation(KnownFolders.Documents.ParsingName, OperationType.Copy);
 643    private void btnctDesktop_Click(object sender, RoutedEventArgs e) => SetFOperation(KnownFolders.Desktop.ParsingName, OperationType.Copy);
 644    private void btnctDounloads_Click(object sender, RoutedEventArgs e) => SetFOperation(KnownFolders.Downloads.ParsingName, OperationType.Copy);
 645    private void btnmtDocuments_Click(object sender, RoutedEventArgs e) => SetFOperation(KnownFolders.Documents.ParsingName, OperationType.Move);
 646    private void btnmtDesktop_Click(object sender, RoutedEventArgs e) => SetFOperation(KnownFolders.Desktop.ParsingName, OperationType.Move);
 647    private void btnmtDounloads_Click(object sender, RoutedEventArgs e) => SetFOperation(KnownFolders.Downloads.ParsingName, OperationType.Move);
 648    private void btnCopyto_Click(object sender, RoutedEventArgs e) => btnctOther_Click(sender, e);
 649    private void btnMoveto_Click(object sender, RoutedEventArgs e) => btnmtOther_Click(sender, e);
 650    private void btnCut_Click(object sender, RoutedEventArgs e) => _ShellListView.CutSelectedFiles();
 651    private void btnOpenWith_Click(object sender, RoutedEventArgs e) => Process.Start($"\"{_ShellListView.GetFirstSelectedItem().ParsingName}\"");
 652    private void btnPaste_Click(object sender, RoutedEventArgs e) => _ShellListView.PasteAvailableFiles();
 653    private void btnDelete_Click(object sender, RoutedEventArgs e) => MenuItem_Click(sender, e);
 654    private void btnRename_Click(object sender, RoutedEventArgs e) => _ShellListView.RenameSelectedItem();
 655    private void btnSelAll_Click(object sender, RoutedEventArgs e) => _ShellListView.SelectAll();
 656    private void btnSelNone_Click(object sender, RoutedEventArgs e) => _ShellListView.DeSelectAllItems();
 657    private void MenuItem_Click(object sender, RoutedEventArgs e) => _ShellListView.DeleteSelectedFiles(true);
 658    private void MenuItem_Click_1(object sender, RoutedEventArgs e) => _ShellListView.DeleteSelectedFiles(false);
 659    private void btnProperties_Click(object sender, RoutedEventArgs e) => _ShellListView.ShowPropPage(this.Handle, _ShellListView.GetFirstSelectedItem().ParsingName, "");
 660    private void btnInvSel_Click(object sender, RoutedEventArgs e) => _ShellListView.InvertSelection();
 661    private void btnNewWindow_Click(object sender, RoutedEventArgs e) => Process.Start(Assembly.GetExecutingAssembly().Location, "/nw");
 662    void miow_Click(object sender, RoutedEventArgs e) => ((AssociationItem)(sender as MenuItem).Tag).Invoke();
 663
 664
 665
 666    private void miJunctionpoint_Click(object sender, RoutedEventArgs e) {
 667      string pathForDrop = _ShellListView.CurrentFolder.ParsingName.Replace(@"\\", @"\");
 668      var files = new string[0];
 669      if (Clipboards.ContainsData("Shell IDList Array"))
 670        files = Clipboards.GetDataObject().ToShellItemArray().ToArray().Select(s => new ShellItem(s).ParsingName).ToArray();
 671      else
 672        files = Clipboards.GetFileDropList().OfType<string>().ToArray();
 673
 674      foreach (string item in files) {
 675        var o = new ShellItem(item);
 676        JunctionPointUtils.JunctionPoint.Create($@"{pathForDrop}\{o.GetDisplayName(SIGDN.NORMALDISPLAY)}", o.ParsingName, true);
 677        AddToLog($@"Created Junction Point at {pathForDrop}\{o.GetDisplayName(SIGDN.NORMALDISPLAY)} linked to {o.ParsingName}");
 678      }
 679    }
 680
 681    private void miCreateSymlink_Click(object sender, RoutedEventArgs e) {
 682      var items = new IListItemEx[0];
 683      items = Clipboards.ContainsData("Shell IDList Array") ? Clipboards.GetDataObject().ToShellItemArray().ToArray().Select(s => FileSystemListItem.InitializeWithIShellItem(this._ShellListView.LVHandle, s)).ToArray() : Clipboards.GetFileDropList().OfType<string>().ToArray().Select(s => FileSystemListItem.ToFileSystemItem(this._ShellListView.LVHandle, s)).ToArray();
 684      var pathForDrop = _ShellListView.CurrentFolder.ParsingName.Replace(@"\\", @"\");
 685      var exePath = Utilities.AppDirectoryItem("BetterExplorerOperations.exe");
 686      var linkItems = items.Select(s => new LinkItem() {
 687        IsDirectory = s.IsFolder,
 688        DestinationData = pathForDrop + @"\" + s.DisplayName,
 689        SourceData = s.ParsingName
 690      }).ToArray();
 691
 692      Task.Run(() => {
 693        using (var proc = new Process()) {
 694          proc.StartInfo = new ProcessStartInfo {
 695            FileName = exePath,
 696            Verb = "runas",
 697            UseShellExecute = true,
 698            Arguments = $"/env /user:Administrator \"{exePath}\""
 699          };
 700
 701          proc.Start();
 702          ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
 703          var address = new EndpointAddress(new Uri("net.tcp://localhost:60000/BEComChannel"));
 704          var binding = new NetTcpBinding() { MaxReceivedMessageSize = 4000000, MaxBufferPoolSize = 4000000, MaxBufferSize = 4000000 };
 705          binding.Security = new NetTcpSecurity() { Mode = SecurityMode.Message };
 706          var factory = new ChannelFactory<IBetterExplorerCommunication>(binding, address);
 707          var beSvc = factory.CreateChannel();
 708          try {
 709            beSvc.CreateLink(new LinkData() { Items = linkItems });
 710          } finally {
 711            Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => this._ShellListView.UnvalidateDirectory()));
 712          }
 713
 714          proc.WaitForExit();
 715          if (proc.ExitCode == 1)
 716            MessageBox.Show("Error in creating symlink", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
 717          else {
 718            Thread.Sleep(1000);
 719            Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => this._ShellListView.UnvalidateDirectory()));
 720          }
 721        }
 722      });
 723
 724    }
 725
 726    private void btnHistory_Click(object sender, RoutedEventArgs e) {
 727      _ShellListView.ShowPropPage(this.Handle, _ShellListView.GetFirstSelectedItem().ParsingName,
 728                                      User32.LoadResourceString(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "twext.dll"), 1024, "Previous Versions"));
 729    }
 730
 731    private void btnBackstageExit_Click(object sender, RoutedEventArgs e) {
 732      //! We call Shutdown() so to explicit shutdown the app regardless of windows closing cancel flag.
 733      if (this.IsMultipleWindowsOpened)
 734        this.Close();
 735      else
 736        Application.Current.Shutdown();
 737    }
 738
 739    void mif_Click(object sender, RoutedEventArgs e) {
 740      using (var obj = (sender as MenuItem).Tag as ShellItem)
 741      using (var lnk = new ShellLink(obj.ParsingName)) {
 742        NavigationController(FileSystemListItem.ToFileSystemItem(this._ShellListView.LVHandle, lnk.TargetPIDL));
 743      }
 744    }
 745
 746    private void btnCopy_Click(object sender, RoutedEventArgs e) {
 747      var sc = new StringCollection();
 748      sc.AddRange(_ShellListView.SelectedItems.Select(x => x.ParsingName).ToArray());
 749      Clipboards.SetFileDropList(sc);
 750    }
 751
 752
 753    private void btnPathCopy_Click(object sender, RoutedEventArgs e) {
 754      if (_ShellListView.SelectedItems.Count > 1)
 755        Clipboards.SetText(_ShellListView.SelectedItems.Select(item => "\r\n" + item.ParsingName).Aggregate((x, y) => x + y).Trim());
 756      else if (_ShellListView.SelectedItems.Count == 1)
 757        Clipboards.SetText(_ShellListView.GetFirstSelectedItem().ParsingName);
 758      else
 759        Clipboards.SetText(_ShellListView.CurrentFolder.ParsingName);
 760    }
 761
 762
 763    // New Folder/Library
 764    private void btnNewFolder_Library(object sender, RoutedEventArgs e) {
 765      //We should focus the ListView or on some circumstances new folder does not start renaming after folder is created
 766      this._ShellListView.Focus();
 767      _ShellListView.IsRenameNeeded = true;
 768
 769      if (_ShellListView.CurrentFolder.ParsingName == KnownFolders.Libraries.ParsingName)
 770        _ShellListView.CreateNewLibrary(FindResource("btnNewLibraryCP").ToString());
 771      else
 772        _ShellListView.CreateNewFolder(null);
 773    }
 774
 775    private void btnPasetShC_Click(object sender, RoutedEventArgs e) {
 776      string PathForDrop = _ShellListView.CurrentFolder.ParsingName;
 777      foreach (string item in Clipboards.GetFileDropList()) {
 778        using (var shortcut = new ShellLink()) {
 779          var o = new ShellItem(item);
 780          shortcut.Target = item;
 781          shortcut.WorkingDirectory = Path.GetDirectoryName(item);
 782          shortcut.Description = o.GetDisplayName(SIGDN.NORMALDISPLAY);
 783          shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
 784          shortcut.Save($"{PathForDrop}\\{o.GetDisplayName(SIGDN.NORMALDISPLAY)}.lnk");
 785          AddToLog($"Shortcut created at {PathForDrop}\\{o.GetDisplayName(SIGDN.NORMALDISPLAY)} from source {item}");
 786        }
 787      }
 788    }
 789
 790    private void btnmtOther_Click(object sender, RoutedEventArgs e) {
 791      var dlg = new FolderSelectDialog();
 792      if (dlg.ShowDialog())
 793        SetFOperation(dlg.FileName, OperationType.Move);
 794    }
 795
 796    private void SetFOperation(String fileName, OperationType opType) {
 797      var obj = FileSystemListItem.ToFileSystemItem(this._ShellListView.LVHandle, fileName.ToShellParsingName());
 798      if (opType == OperationType.Copy)
 799        _ShellListView.DoCopy(obj);
 800      else if (opType == OperationType.Move)
 801        _ShellListView.DoMove(obj);
 802    }
 803
 804    private void SetFOperation(IListItemEx obj, OperationType opType) {
 805      if (opType == OperationType.Copy)
 806        _ShellListView.DoCopy(obj);
 807      else if (opType == OperationType.Move)
 808        _ShellListView.DoMove(obj);
 809    }
 810
 811    private void btnctOther_Click(object sender, RoutedEventArgs e) {
 812      var dlg = new FolderSelectDialog();
 813      if (dlg.ShowDialog())
 814        SetFOperation(dlg.FileName, OperationType.Copy);
 815
 816      _ShellListView.Focus();
 817    }
 818
 819    private void btnNewItem_Click(object sender, RoutedEventArgs e) {
 820      var state = new BExplorer.Shell.Interop.Shell32.SHELLSTATE() { fShowAllObjects = 0 };
 821      BExplorer.Shell.Interop.Shell32.SHGetSetSettings(ref state, BExplorer.Shell.Interop.Shell32.SSF.SSF_SHOWALLOBJECTS, true);
 822    }
 823
 824    private void btnEdit_Click(object sender, RoutedEventArgs e) {
 825      new Process() {
 826        StartInfo = new ProcessStartInfo {
 827          FileName = _ShellListView.GetFirstSelectedItem().ParsingName,
 828          Verb = "edit",
 829          UseShellExecute = true,
 830        }
 831      }.Start();
 832    }
 833
 834    private void btnFavorites_Click(object sender, RoutedEventArgs e) {
 835      var selectedItems = _ShellListView.SelectedItems;
 836      if (selectedItems.Count == 1) {
 837        var link = new ShellLink();
 838        link.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
 839        link.Target = _ShellListView.GetFirstSelectedItem().ParsingName;
 840        link.Save($@"{KnownFolders.Links.ParsingName}\{_ShellListView.GetFirstSelectedItem().DisplayName}.lnk");
 841        link.Dispose();
 842      }
 843
 844      if (selectedItems.Count == 0) {
 845        var link = new ShellLink();
 846        link.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
 847        link.Target = _ShellListView.CurrentFolder.ParsingName;
 848        link.Save($@"{KnownFolders.Links.ParsingName}\{_ShellListView.CurrentFolder.DisplayName}.lnk");
 849        link.Dispose();
 850      }
 851    }
 852
 853    #endregion
 854
 855    #region Drive Tools / Virtual Disk Tools
 856
 857    private void btnDefragDrive_Click(object sender, RoutedEventArgs e) {
 858      string DriveLetter = "";
 859
 860      if (!_ShellListView.SelectedItems.Any())
 861        DriveLetter = _ShellListView.CurrentFolder.ParsingName;
 862      else if (Directory.GetLogicalDrives().Contains(_ShellListView.SelectedItems[0].ParsingName))
 863        DriveLetter = _ShellListView.SelectedItems[0].ParsingName;
 864      else
 865        DriveLetter = _ShellListView.CurrentFolder.ParsingName;
 866
 867      Process.Start(Path.Combine(Environment.SystemDirectory, "dfrgui.exe"), $"/u /v {DriveLetter.Replace("\\", "")}");
 868    }
 869
 870    private char GetDriveLetterFromDrivePath(string path) => path.Substring(0, 1).ToCharArray()[0];
 871
 872    private void btnFormatDrive_Click(object sender, RoutedEventArgs e) {
 873      if (MessageBox.Show("Are you sure you want to do this?", FindResource("btnFormatDriveCP").ToString(), MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) {
 874        var formatDriveThread = new Thread(() => {
 875          string DriveLetter =
 876          _ShellListView.SelectedItems.Any() ?
 877          DriveLetter = Directory.GetLogicalDrives().Contains(_ShellListView.SelectedItems[0].ParsingName) ? _ShellListView.SelectedItems[0].ParsingName : _ShellListView.CurrentFolder.ParsingName
 878          :
 879          DriveLetter = _ShellListView.CurrentFolder.ParsingName;
 880
 881          BExplorer.Shell.Interop.Shell32.FormatDrive(IntPtr.Zero, DriveLetter);
 882        });
 883
 884        formatDriveThread.Start();
 885      }
 886    }
 887
 888    private void btnCleanDrive_Click(object sender, RoutedEventArgs e) {
 889      string DriveLetter = "";
 890      if (_ShellListView.SelectedItems.Any())
 891        DriveLetter = Directory.GetLogicalDrives().Contains(_ShellListView.SelectedItems[0].ParsingName) ? _ShellListView.SelectedItems[0].ParsingName : _ShellListView.CurrentFolder.ParsingName;
 892      else
 893        DriveLetter = _ShellListView.CurrentFolder.ParsingName;
 894
 895      Process.Start("Cleanmgr.exe", "/d" + DriveLetter.Replace(":\\", ""));
 896    }
 897
 898    private void OpenCDTray(char DriveLetter) {
 899      mciSendString($"open {DriveLetter}: type CDAudio alias drive{DriveLetter}", null, 0, IntPtr.Zero);
 900      mciSendString($"set drive{DriveLetter} door open", null, 0, IntPtr.Zero);
 901    }
 902
 903    private void CloseCDTray(char DriveLetter) {
 904      mciSendString($"open {DriveLetter}: type CDAudio alias drive{DriveLetter}", null, 0, IntPtr.Zero);
 905      mciSendString($"set drive{DriveLetter} door closed", null, 0, IntPtr.Zero);
 906    }
 907
 908    private void btnOpenTray_Click(object sender, RoutedEventArgs e) {
 909      if (_ShellListView.GetFirstSelectedItem()?.GetDriveInfo().DriveType == DriveType.CDRom)
 910        OpenCDTray(GetDriveLetterFromDrivePath(_ShellListView.GetFirstSelectedItem().ParsingName));
 911    }
 912
 913    private void btnCloseTray_Click(object sender, RoutedEventArgs e) {
 914      if (_ShellListView.GetFirstSelectedItem()?.GetDriveInfo().DriveType == DriveType.CDRom)
 915        CloseCDTray(GetDriveLetterFromDrivePath(_ShellListView.GetFirstSelectedItem().ParsingName));
 916    }
 917
 918    private void EjectDisk(char DriveLetter) {
 919      Thread t = new Thread(() => {
 920        Thread.Sleep(10);
 921        var vdc = new VolumeDeviceClass();
 922        foreach (Volume item in vdc.Devices) {
 923          if (GetDriveLetterFromDrivePath(item.LogicalDrive) == DriveLetter) {
 924            var veto = item.Eject(false);
 925            if (veto != Native.PNP_VETO_TYPE.TypeUnknown) {
 926              if (veto == Native.PNP_VETO_TYPE.Ok) {
 927                Dispatcher.BeginInvoke(DispatcherPriority.Normal,
 928                                (Action)(() => {
 929                                  this.beNotifyIcon.ShowBalloonTip("Information", $"It is safe to remove {item.LogicalDrive}", Hardcodet.Wpf.TaskbarNotification.BalloonIcon.Info);
 930                                  var tabsForRemove = tcMain.Items.OfType<Wpf.Controls.TabItem>().Where(w => {
 931                                    var root = String.Empty;
 932                                    try {
 933                                      root = Path.GetPathRoot(w.ShellObject.ParsingName.ToShellParsingName());
 934                                    } catch { }
 935                                    return !String.IsNullOrEmpty(root) && (w.ShellObject.IsFileSystem &&
 936                                                    root.ToLowerInvariant() == $"{DriveLetter}:\\".ToLowerInvariant());
 937                                  }).ToArray();
 938
 939                                  foreach (Wpf.Controls.TabItem tab in tabsForRemove) {
 940                                    tcMain.RemoveTabItem(tab);
 941                                  }
 942                                }));
 943              } else {
 944                var message = String.Empty;
 945                var obj = new ShellItem(item.LogicalDrive);
 946                switch (veto) {
 947                  case Native.PNP_VETO_TYPE.Ok:
 948                    break;
 949                  case Native.PNP_VETO_TYPE.TypeUnknown:
 950                    break;
 951                  case Native.PNP_VETO_TYPE.LegacyDevice:
 952                    break;
 953                  case Native.PNP_VETO_TYPE.PendingClose:
 954                    break;
 955                  case Native.PNP_VETO_TYPE.WindowsApp:
 956                    break;
 957                  case Native.PNP_VETO_TYPE.WindowsService:
 958                    break;
 959                  case Native.PNP_VETO_TYPE.OutstandingOpen:
 960                    message = $"The device {obj.GetDisplayName(SIGDN.NORMALDISPLAY)} can not be disconnected because is in use!";
 961                    break;
 962                  case Native.PNP_VETO_TYPE.Device:
 963                    break;
 964                  case Native.PNP_VETO_TYPE.Driver:
 965                    break;
 966                  case Native.PNP_VETO_TYPE.IllegalDeviceRequest:
 967                    break;
 968                  case Native.PNP_VETO_TYPE.InsufficientPower:
 969                    break;
 970                  case Native.PNP_VETO_TYPE.NonDisableable:
 971                    message = $"The device {obj.GetDisplayName(SIGDN.NORMALDISPLAY)} does not support disconnecting!";
 972                    break;
 973                  case Native.PNP_VETO_TYPE.LegacyDriver:
 974                    break;
 975                  default:
 976                    break;
 977                }
 978
 979                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => this.beNotifyIcon.ShowBalloonTip("Error", message, Hardcodet.Wpf.TaskbarNotification.BalloonIcon.Error)));
 980              }
 981            }
 982            break;
 983          }
 984        }
 985      });
 986      t.SetApartmentState(ApartmentState.STA);
 987      t.Start();
 988    }
 989
 990    private void btnEjectDevice_Click(object sender, RoutedEventArgs e) {
 991      var firstSelectedItem = _ShellListView.GetFirstSelectedItem();
 992      if (firstSelectedItem?.GetDriveInfo().DriveType == DriveType.Removable || firstSelectedItem.GetDriveInfo().DriveType == DriveType.Fixed) {
 993        EjectDisk(GetDriveLetterFromDrivePath(firstSelectedItem.ParsingName));
 994        //USBEject.EjectDrive(GetDriveLetterFromDrivePath(firstSelectedItem.ParsingName));
 995      }
 996    }
 997
 998    // Virtual Disk Tools
 999    private bool CheckImDiskInstalled() {
1000      try {
1001        ImDiskAPI.GetDeviceList();
1002        return true;
1003      } catch (DllNotFoundException) {
1004        return false;
1005      }
1006    }
1007
1008    public void ShowInstallImDiskMessage() {
1009      if (MessageBox.Show("It appears you do not have the ImDisk Virtual Disk Driver installed. This driver is used to power Better Explorer's ISO-mounting features. \n\nWould you like to visit ImDisk's website to install the product? (http://www.ltr-data.se/opencode.html/)", "ImDisk Not Found", MessageBoxButton.YesNo, MessageBoxImage.Error) == MessageBoxResult.Yes) {
1010        Process.Start("http://www.ltr-data.se/opencode.html/#ImDisk");
1011      }
1012    }
1013
1014    private void btnAdvMountIso_Click(object sender, RoutedEventArgs e) {
1015      if (!CheckImDiskInstalled()) {
1016        ShowInstallImDiskMessage();
1017        return;
1018      }
1019
1020      var mi = new MountIso() { Owner = this };
1021      mi.ShowDialog();
1022      if (mi.yep) {
1023        string DriveLetter = String.Format("{0}:", mi.chkPreselect.IsChecked == true ? ImDiskAPI.FindFreeDriveLetter() : (char)mi.cbbLetter.SelectedItem);
1024        long size = mi.chkPresized.IsChecked == true ? 0 : Convert.ToInt64(mi.txtSize.Text);
1025
1026        ImDiskFlags imflags;
1027        switch (mi.cbbType.SelectedIndex) {
1028          case 0:
1029            //Hard Drive
1030            imflags = ImDiskFlags.DeviceTypeHD;
1031            break;
1032          case 1:
1033            // CD/DVD
1034            imflags = ImDiskFlags.DeviceTypeCD;
1035            break;
1036          case 2:
1037            // Floppy Disk
1038            imflags = ImDiskFlags.DeviceTypeFD;
1039            break;
1040          case 3:
1041            // Raw Data
1042            imflags = ImDiskFlags.DeviceTypeRAW;
1043            break;
1044          default:
1045            imflags = ImDiskFlags.DeviceTypeCD;
1046            break;
1047        }
1048
1049        switch (mi.cbbAccess.SelectedIndex) {
1050          case 0:
1051            // Access directly
1052            imflags |= ImDiskFlags.FileTypeDirect;
1053            break;
1054          case 1:
1055            // Copy to memory
1056            imflags |= ImDiskFlags.FileTypeAwe;
1057            break;
1058          default:
1059            imflags |= ImDiskFlags.FileTypeDirect;
1060            break;
1061        }
1062
1063        if (mi.chkRemovable.IsChecked == true)
1064          imflags |= ImDiskFlags.Removable;
1065        if (mi.chkReadOnly.IsChecked == true)
1066          imflags |= ImDiskFlags.ReadOnly;
1067
1068        ImDiskAPI.CreateDevice(size, 0, 0, 0, 0, imflags, _ShellListView.GetFirstSelectedItem().ParsingName, false, DriveLetter, IntPtr.Zero);
1069      }
1070    }
1071
1072    private void btnMountIso_Click(object sender, RoutedEventArgs e) {
1073      try {
1074        var freeDriveLetter = $"{ImDiskAPI.FindFreeDriveLetter()}:";
1075        ImDiskAPI.CreateDevice(0, 0, 0, 0, 0, ImDiskFlags.Auto, _ShellListView.GetFirstSelectedItem().ParsingName, false, freeDriveLetter, IntPtr.Zero);
1076      } catch (DllNotFoundException) {
1077        ShowInstallImDiskMessage();
1078      } catch (Exception ex) {
1079        MessageBox.Show("An error occurred while trying to mount this file. \n\n" + ex.Message, ex.ToString(), MessageBoxButton.OK, MessageBoxImage.Error);
1080      }
1081    }
1082
1083    private void btnWriteIso_Click(object sender, RoutedEventArgs e) {
1084      Process.Start(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "isoburn.exe"), $"\"{_ShellListView.GetFirstSelectedItem().ParsingName}\"");
1085    }
1086
1087    private void btnUnmountDrive_Click(object sender, RoutedEventArgs e) {
1088      //SelectedDriveID was NEVER anything but 0
1089      uint SelectedDriveID = 0;
1090
1091      try {
1092        if (!CheckImDiskInstalled())
1093          ShowInstallImDiskMessage();
1094        else if ((ImDiskAPI.QueryDevice(SelectedDriveID).Flags & ImDiskFlags.DeviceTypeCD) != 0)
1095          ImDiskAPI.ForceRemoveDevice(SelectedDriveID);
1096        else
1097          ImDiskAPI.RemoveDevice(SelectedDriveID);
1098      } catch {
1099        if (MessageBox.Show("The drive could not be removed. Would you like to try to force a removal?", "Remove Drive Failed", MessageBoxButton.YesNo, MessageBoxImage.Error) == MessageBoxResult.Yes) {
1100          ImDiskAPI.ForceRemoveDevice(SelectedDriveID);
1101        }
1102      }
1103      _ShellListView.RefreshContents();
1104      ctgDrive.Visibility = Visibility.Collapsed;
1105    }
1106
1107    #endregion
1108
1109    #region Application Tools
1110
1111    private void btnPin_Click(object sender, RoutedEventArgs e) => User32.PinUnpinToTaskbar(_ShellListView.GetFirstSelectedItem().ParsingName);
1112    private void btnPinToStart_Click(object sender, RoutedEventArgs e) => User32.PinUnpinToStartMenu(_ShellListView.GetFirstSelectedItem().ParsingName);
1113    private void btnRunAs_Click(object sender, RoutedEventArgs e) => CredUI.RunProcesssAsUser(_ShellListView.GetFirstSelectedItem().ParsingName);
1114
1115    private void btnRunAsAdmin_Click(object sender, RoutedEventArgs e) {
1116      var FileName = _ShellListView.GetFirstSelectedItem().ParsingName;
1117      Process.Start(new ProcessStartInfo {
1118        FileName = FileName,
1119        Verb = "runas",
1120        UseShellExecute = true,
1121        Arguments = $"/env /user:Administrator \"{FileName}\""
1122      });
1123    }
1124
1125    #endregion
1126
1127    #region Backstage - Information Tab
1128
1129    private void Button_Click_6(object sender, RoutedEventArgs e) {
1130      backstage.IsOpen = true;
1131      autoUpdater.Visibility = WIN.Visibility.Visible;
1132      autoUpdater.UpdateLayout();
1133
1134      switch (autoUpdater.UpdateStepOn) {
1135        case UpdateStepOn.Checking:
1136        case UpdateStepOn.DownloadingUpdate:
1137        case UpdateStepOn.ExtractingUpdate:
1138          autoUpdater.Cancel();
1139          break;
1140        case UpdateStepOn.UpdateReadyToInstall:
1141        case UpdateStepOn.UpdateAvailable:
1142          break;
1143        case UpdateStepOn.UpdateDownloaded:
1144          autoUpdater.InstallNow();
1145          break;
1146        default:
1147          autoUpdater.ForceCheckForUpdate(true);
1148          break;
1149      }
1150    }
1151
1152    private void Button_Click_7(object sender, RoutedEventArgs e) => Process.Start("http://gainedge.org/better-explorer/");
1153
1154    #endregion
1155
1156    #region Path to String HelperFunctions / Other HelperFunctions
1157
1158    private Visibility BooleanToVisibiliy(bool value) => value ? Visibility.Visible : Visibility.Collapsed;
1159
1160    private void AddToLog(string value) {
1161      try {
1162        if (BESettings.EnableActionLog) {
1163          if (!Directory.Exists(logdir)) Directory.CreateDirectory(logdir);
1164
1165          using (var sw = new StreamWriter($"{logdir}{sessionid}.txt", true)) {
1166            sw.WriteLine(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + " : " + value);
1167          }
1168        }
1169      } catch (Exception exe) {
1170        MessageBox.Show("An error occurred while writing to the log file. This error can be avoided if you disable the action logging feature. Please report this issue at http://bugs.gainedge.org/public/betterexplorer. \r\n\r\n Here is some information about the error: \r\n\r\n" + exe.Message + "\r\n\r\n" + exe.ToString(), "Error While Writing to Log", MessageBoxButton.OK, MessageBoxImage.Error);
1171      }
1172    }
1173
1174    #endregion
1175
1176    #region Updater
1177
1178    private void CheckBox_Checked(object sender, RoutedEventArgs e) {
1179      if (isOnLoad) return;
1180
1181      Settings.BESettings.IsUpdateCheck = true;
1182      Settings.BESettings.SaveSettings();
1183      updateCheckTimer.Start();
1184    }
1185
1186    private void CheckBox_Unchecked(object sender, RoutedEventArgs e) {
1187      if (isOnLoad) return;
1188
1189      Settings.BESettings.IsUpdateCheck = false;
1190      Settings.BESettings.SaveSettings();
1191    }
1192
1193    private void rbCheckInterval_Click(object sender, RoutedEventArgs e) {
1194      if (rbDaily.IsChecked.Value)
1195        Settings.BESettings.UpdateCheckInterval = 1;
1196      else if (rbMonthly.IsChecked.Value)
1197        Settings.BESettings.UpdateCheckInterval = 30;
1198      else
1199        Settings.BESettings.UpdateCheckInterval = 7;
1200
1201      Settings.BESettings.SaveSettings();
1202    }
1203
1204    private void chkUpdateStartupCheck_Click(object sender, RoutedEventArgs e) {
1205      Settings.BESettings.IsUpdateCheckStartup = chkUpdateStartupCheck.IsChecked.Value;
1206      Settings.BESettings.SaveSettings();
1207    }
1208
1209    private void UpdateTypeCheck_Click(object sender, RoutedEventArgs e) {
1210      Settings.BESettings.UpdateCheckType = rbReleases.IsChecked.Value ? 0 : 1;
1211      Settings.BESettings.SaveSettings();
1212    }
1213
1214    #endregion
1215
1216    #region On Startup
1217
1218    /// <summary>
1219    /// Gets the badges from the folder Badges located in the .EXE's directory and the badges from SQLite database
1220    /// </summary>
1221    /// <returns></returns>
1222    private Dictionary<String, Dictionary<IListItemEx, List<string>>> LoadBadgesData() {
1223      var result = new Dictionary<String, Dictionary<IListItemEx, List<string>>>();
1224      var badgesDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Badges");
1225      var badgesIshellItem = FileSystemListItem.ToFileSystemItem(this._ShellListView.LVHandle, badgesDirectory);
1226      foreach (var item in badgesIshellItem.Where(w => w.IsFolder)) {
1227        var innerDict = new Dictionary<IListItemEx, List<string>>();
1228        foreach (var badgeItem in item.Where(w => w.Extension.ToLowerInvariant() == ".ico")) {
1229          innerDict.Add(badgeItem, new List<String>());
1230        }
1231
1232        result.Add(item.DisplayName, innerDict);
1233      }
1234
1235      try {
1236        var m_dbConnection = new System.Data.SQLite.SQLiteConnection($"Data Source={this._DBPath};Version=3;");
1237        m_dbConnection.Open();
1238
1239        var command1 = new System.Data.SQLite.SQLiteCommand("SELECT * FROM badges", m_dbConnection);
1240
1241        var Reader = command1.ExecuteReader();
1242        while (Reader.Read()) {
1243          var values = Reader.GetValues();
1244          var path = values.GetValues("Path").Single();
1245          var collectionName = values.GetValues("Collection").Single();
1246          var badgeName = values.GetValues("Badge").Single();
1247          var badgeDBItem = FileSystemListItem.ToFileSystemItem(this._ShellListView.LVHandle, Path.Combine(badgesDirectory, collectionName, badgeName));
1248          var collectionDict = result[collectionName];
1249          var collectionItemKey = collectionDict.Keys.SingleOrDefault(w => w.ParsingName.Equals(badgeDBItem.ParsingName));
1250
1251          if (collectionItemKey != null) {
1252            result[collectionName][collectionItemKey].Add(path);
1253          }
1254        }
1255        Reader.Close();
1256      } catch (Exception) {
1257      }
1258
1259      return result;
1260    }
1261
1262    /// <summary>
1263    /// Adds all default items to <see cref="btnFavorites"/>
1264    /// </summary>
1265    /// <remarks>
1266    /// 1. Sets OpenFavorites's OnClick event to open <see cref="KnownFolders.Links"/>
1267    /// 2. Adds all links from <see cref="KnownFolders.Links"/> that are not hidden 
1268    /// </remarks>
1269    private void SetUpFavoritesMenu() {
1270      Dispatcher.BeginInvoke(DispatcherPriority.Render, (ThreadStart)(() => {
1271        btnFavorites.Visibility = Visibility.Visible;
1272
1273        var OpenFavorites = new MenuItem() { Header = "Open Favorites" };
1274        var Path = ((ShellItem)KnownFolders.Links).FileSystemPath;
1275        OpenFavorites.Click += (x, y) => Process.Start(Path);
1276
1277        btnFavorites.Items.Add(OpenFavorites);
1278        btnFavorites.Items.Add(new Separator());
1279
1280        foreach (ShellItem item in KnownFolders.Links.Where(w => !w.IsHidden)) {
1281          item.Thumbnail.FormatOption = ShellThumbnailFormatOption.IconOnly;
1282          item.Thumbnail.CurrentSize = new WIN.Size(16, 16);
1283          btnFavorites.Items.Add(Utilities.Build_MenuItem(item.GetDisplayName(SIGDN.NORMALDISPLAY), item, item.Thumbnail.BitmapSource, onClick: mif_Click));
1284        }
1285      }));
1286    }
1287
1288    private void InitializeExplorerControl() {
1289      this.ShellTree.NodeClick += ShellTree_NodeClick;
1290      this._ShellListView.Navigated += ShellListView_Navigated;
1291      this._ShellListView.ViewStyleChanged += ShellListView_ViewStyleChanged;
1292      this._ShellListView.SelectionChanged += ShellListView_SelectionChanged;
1293      this._ShellListView.LVItemsColorCodes = this.LVItemsColorCol;
1294      this._ShellListView.ItemUpdated += ShellListView_ItemUpdated;
1295      this._ShellListView.ColumnHeaderRightClick += ShellListView_ColumnHeaderRightClick;
1296      this._ShellListView.KeyJumpKeyDown += ShellListView_KeyJumpKeyDown;
1297      this._ShellListView.KeyJumpTimerDone += ShellListView_KeyJumpTimerDone;
1298      //this.ShellListView.ItemDisplayed += ShellListView_ItemDisplayed;
1299      this._ShellListView.OnListViewColumnDropDownClicked += ShellListView_OnListViewColumnDropDownClicked;
1300      this._ShellListView.Navigating += ShellListView_Navigating;
1301      this._ShellListView.ItemMiddleClick += (sender, e) => tcMain.NewTab(e.Folder, false);
1302      this._ShellListView.BeginItemLabelEdit += ShellListView_BeginItemLabelEdit;
1303      this._ShellListView.EndItemLabelEdit += ShellListView_EndItemLabelEdit;
1304      this._ShellListView.OnListViewCollumnsChanged += _ShellListView_OnListViewCollumnsChanged;
1305      this._ShellListView.BadgesData = this.Badges;
1306    }
1307
1308    private void _ShellListView_OnListViewCollumnsChanged(object sender, CollumnsChangedArgs e) => this.SetSortingAndGroupingButtons();
1309
1310    void ShellListView_OnListViewColumnDropDownClicked(object sender, ListViewColumnDropDownArgs e) {
1311      //TODO: Add Events for when an item's check has been changed
1312      var packUri = "pack://application:,,,/BetterExplorer;component/Images/stack16.png";
1313      var menu = new ListviewColumnDropDown() {
1314        Placement = PlacementMode.AbsolutePoint,
1315        HorizontalOffset = e.ActionPoint.X,
1316        VerticalOffset = e.ActionPoint.Y,
1317        IsOpen = true,
1318        StaysOpen = true,
1319      };
1320
1321      var Things = new List<string>();
1322      var SelectedColumn = this._ShellListView.Collumns[e.ColumnIndex];
1323      if (SelectedColumn.CollumnType == typeof(String)) {
1324        Things.AddRange(new[] { "0 - 9", "A - H", "I - P", "Q - Z", "Other" });
1325      } else if (SelectedColumn.CollumnType == typeof(DateTime)) {
1326        var Container = new ItemsControl();
1327        Container.Items.Add(new MenuItem() { Icon = new ImageSourceConverter().ConvertFromString(packUri) as ImageSource, Header = "Select a date or date range:", HorizontalContentAlignment = HorizontalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch, IsCheckable = true, StaysOpenOnClick = true });
1328        Container.Items.Add(new Calendar() { SelectionMode = CalendarSelectionMode.SingleRange, Margin = new Thickness(30, 0, 0, 0) });
1329        menu.AddItem(Container);
1330
1331        Things.AddRange(new[] { "A long time ago", "Earlier this year", "Earlier this month", "Last week", "Today" });
1332      } else if (SelectedColumn.CollumnType == typeof(long)) {
1333        Things.AddRange(new[] { "Tiny (0 - 10 KB)", "Small (10 - 100 KB)", "Medium (100 KB - 1 MB)", "Large (1 - 16 MB)", "Huge (16 - 128 MB)", "Unspecified" });
1334      } else if (SelectedColumn.CollumnType == typeof(Type)) {
1335        var distictItems = this._ShellListView.Items.Select(s => s.GetPropertyValue(SelectedColumn.pkey, SelectedColumn.CollumnType).Value).Distinct().Cast<String>().ToArray().OrderBy(o => o);
1336        Things.AddRange(distictItems);
1337      }
1338
1339      foreach (var item in Things) {
1340        var mnuItem = new MenuItem() {
1341          Icon = new ImageSourceConverter().ConvertFromString(packUri) as ImageSource,
1342          IsCheckable = true,
1343          Header = item,
1344          HorizontalContentAlignment = HorizontalAlignment.Stretch,
1345          HorizontalAlignment = HorizontalAlignment.Stretch,
1346          StaysOpenOnClick = true
1347        };
1348
1349        mnuItem.Click += new RoutedEventHandler(delegate (object s, RoutedEventArgs re) {
1350          var over = Mouse.DirectlyOver;
1351          if (!(over is Image)) {
1352            menu.IsOpen = false;
1353          }
1354        });
1355        menu.AddItem(mnuItem);
1356      }
1357    }
1358
1359    protected override void OnSourceInitialized(EventArgs e) {
1360      base.OnSourceInitialized(e);
1361      Handle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
1362    }
1363
1364    private void LoadRegistryRelatedSettings() {
1365      BESettings.LoadSettings();
1366      RegistryKey rk = Registry.CurrentUser;
1367      RegistryKey rks = rk.CreateSubKey(@"Software\BExplorer");
1368
1369      switch (BESettings.CurrentTheme) {
1370        case "Blue":
1371          btnBlue.IsChecked = true;
1372          break;
1373        case "Silver":
1374          btnSilver.IsChecked = true;
1375          break;
1376        case "Black":
1377          btnBlack.IsChecked = true;
1378          break;
1379        case "Metro":
1380          btnMetro.IsChecked = true;
1381          break;
1382        default:
1383          btnBlue.IsChecked = true;
1384          break;
1385      }
1386
1387      switch (Settings.BESettings.UpdateCheckInterval) {
1388        case 1:
1389          rbDaily.IsChecked = true;
1390          break;
1391        case 7:
1392          rbWeekly.IsChecked = true;
1393          break;
1394        case 30:
1395          rbMonthly.IsChecked = true;
1396          break;
1397      }
1398
1399      switch (Settings.BESettings.UpdateCheckType) {
1400        case 0:
1401          rbReleases.IsChecked = true;
1402          break;
1403        case 1:
1404          rbReleasTest.IsChecked = true;
1405          break;
1406      }
1407
1408      chkUpdateCheck.IsChecked = Settings.BESettings.IsUpdateCheck;
1409      chkUpdateStartupCheck.IsChecked = Settings.BESettings.IsUpdateCheckStartup;
1410
1411      btnConsolePane.IsChecked = BESettings.IsConsoleShown;
1412      chkIsFlyout.IsChecked = BESettings.HFlyoutEnabled;//
1413      btnInfoPane.IsChecked = BESettings.IsInfoPaneEnabled;
1414
1415      if (BESettings.IsInfoPaneEnabled) {
1416        rPreviewPane.Height = new GridLength(BESettings.InfoPaneHeight);
1417        rPreviewPaneSplitter.Height = new GridLength(1);
1418      } else {
1419        rPreviewPane.Height = new GridLength(0);
1420        rPreviewPaneSplitter.Height = new GridLength(0);
1421      }
1422
1423      btnPreviewPane.IsChecked = BESettings.IsPreviewPaneEnabled;
1424
1425      if (BESettings.IsPreviewPaneEnabled) {
1426        clPreview.Width = new GridLength(BESettings.PreviewPaneWidth);
1427        clPreviewSplitter.Width = new GridLength(1);
1428      } else {
1429        clPreview.Width = new GridLength(0);
1430        clPreviewSplitter.Width = new GridLength(0);
1431      }
1432
1433      btnNavigationPane.IsChecked = BESettings.IsNavigationPaneEnabled;
1434
1435      this._ShellListView.ShowCheckboxes = BESettings.ShowCheckboxes;
1436      this.chkShowCheckBoxes.IsChecked = this._ShellListView.ShowCheckboxes;
1437      this.chkIsTerraCopyEnabled.IsChecked = BESettings.IsFileOpExEnabled;
1438
1439      this.chkIsCFO.IsChecked = BESettings.IsCustomFO;
1440      this.chkIsRestoreTabs.IsChecked = BESettings.IsRestoreTabs;
1441      this.chkTraditionalNameGrouping.IsChecked = BESettings.IsTraditionalNameGrouping;
1442
1443      // if this instance has the /norestore switch, do not load tabs from previous session, even if it is set in the Registry
1444      if (App.IsStartWithStartupTab) {
1445        BESettings.IsRestoreTabs = false;
1446      }
1447
1448      //this.chkIsLastTabCloseApp.IsChecked = (int)rks.GetValue("IsLastTabCloseApp", 1) == 1;
1449
1450      chkLogHistory.IsChecked = BESettings.EnableActionLog;
1451      if (BESettings.EnableActionLog) {
1452        chkLogHistory.Visibility = Visibility.Visible;
1453        ShowLogsBorder.Visibility = Visibility.Visible;
1454        paddinglbl8.Visibility = Visibility.Visible;
1455      }
1456
1457
1458      chkFolder.IsChecked = BESettings.AutoSwitchFolderTools;
1459      chkArchive.IsChecked = BESettings.AutoSwitchArchiveTools;
1460      chkImage.IsChecked = BESettings.AutoSwitchImageTools;
1461      chkApp.IsChecked = BESettings.AutoSwitchApplicationTools;
1462      chkLibrary.IsChecked = BESettings.AutoSwitchLibraryTools;
1463      chkDrive.IsChecked = BESettings.AutoSwitchDriveTools;
1464      chkVirtualTools.IsChecked = BESettings.AutoSwitchVirtualDriveTools;
1465
1466      // load OverwriteOnImages setting (default is false)
1467      chkOverwriteImages.IsChecked = BESettings.OverwriteImageWhileEditing;
1468
1469      // load Saved Tabs Directory location (if different from default)
1470      txtDefSaveTabs.Text = BESettings.SavedTabsDirectory;
1471
1472      if (tcMain.StartUpLocation == "") {
1473        tcMain.StartUpLocation = BESettings.StartupLocation;
1474      }
1475
1476      try {
1477        var rkbe = Registry.ClassesRoot;
1478        var rksbe = rkbe.OpenSubKey(@"Folder\shell\open\command", RegistryKeyPermissionCheck.ReadSubTree);
1479        chkIsDefault.IsChecked = rksbe.GetValue("DelegateExecute", "-1").ToString() == "-1";
1480        chkIsDefault.IsEnabled = true;
1481        rksbe.Close();
1482        rkbe.Close();
1483      } catch (Exception) {
1484        chkIsDefault.IsChecked = false;
1485        chkIsDefault.IsEnabled = false;
1486      }
1487
1488      var rkfe = Registry.CurrentUser;
1489      var rksfe = rk.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", RegistryKeyPermissionCheck.ReadSubTree);
1490      chkTreeExpand.IsChecked = (int)rksfe.GetValue("NavPaneExpandToCurrentFolder", 0) == 1;
1491      rksfe.Close();
1492      rkfe.Close();
1493
1494      rks.Close();
1495      rk.Close();
1496
1497
1498      var sho = new ShellItem(BESettings.StartupLocation.ToShellParsingName());
1499      btnSetCurrentasStartup.Header = sho.DisplayName;
1500      sho.Thumbnail.FormatOption = ShellThumbnailFormatOption.IconOnly;
1501      btnSetCurrentasStartup.Icon = sho.Thumbnail.SmallBitmapSource;
1502
1503
1504      miTabManager.IsEnabled = Directory.Exists(BESettings.SavedTabsDirectory);
1505      autoUpdater.DaysBetweenChecks = Settings.BESettings.UpdateCheckInterval;
1506
1507      try {
1508        autoUpdater.UpdateType = Settings.BESettings.IsUpdateCheck ? UpdateType.OnlyCheck : UpdateType.DoNothing;
1509        if (Settings.BESettings.IsUpdateCheckStartup) this.CheckForUpdate();
1510      } catch (IOException) {
1511        this.stiUpdate.Content = "Switch to another BetterExplorer window or restart to check for updates.";
1512        this.btnUpdateCheck.IsEnabled = false;
1513      }
1514
1515      if (App.IsStartMinimized) {
1516        this.Visibility = Visibility.Hidden;
1517        this.WindowState = WindowState.Minimized;
1518      }
1519
1520      if (!TheRibbon.IsMinimized) {
1521        TheRibbon.SelectedTabItem = HomeTab;
1522        this.TheRibbon.SelectedTabIndex = 0;
1523      }
1524    }
1525
1526    private void SetsUpJumpList() {
1527      //sets up Jump List
1528      try {
1529        AppJL.ShowRecentCategory = true;
1530        AppJL.ShowFrequentCategory = true;
1531        JumpList.SetJumpList(Application.Current, AppJL);
1532        AppJL.JumpItems.Add(new JumpTask() {
1533          ApplicationPath = Process.GetCurrentProcess().MainModule.FileName,
1534          Arguments = "t",
1535          Title = "Open Tab",
1536          Description = "Opens new tab with default location"
1537        });
1538        AppJL.JumpItems.Add(new JumpTask() {
1539          ApplicationPath = Process.GetCurrentProcess().MainModule.FileName,
1540          Arguments = "/nw",
1541          Title = "New Window",
1542          Description = "Creates a new window with default location"
1543        });
1544
1545        AppJL.Apply();
1546      } catch {
1547      }
1548    }
1549
1550    private void Window_Loaded(object sender, RoutedEventArgs e) {
1551      this._ProgressTimer.Tick += (obj, args) => {
1552        if (this.bcbc.ProgressValue + 2 == this.bcbc.ProgressMaximum) {
1553          this.bcbc.ProgressMaximum = this.bcbc.ProgressMaximum + 2;
1554          this.bcbc.SetProgressValue(this.bcbc.ProgressValue + 2, TimeSpan.FromMilliseconds(0));
1555        } else {
1556          this.bcbc.SetProgressValue(this.bcbc.ProgressValue + 2, TimeSpan.FromMilliseconds(450));
1557        }
1558      };
1559
1560      this._ProgressTimer.Stop();
1561      TheRibbon.UpdateLayout();
1562      this.grdItemTextColor.ItemsSource = this.LVItemsColorCol;
1563      _keyjumpTimer.Interval = 1000;
1564      _keyjumpTimer.Tick += _keyjumpTimer_Tick;
1565      ShellTreeHost.Child = ShellTree;
1566      ShellViewHost.Child = _ShellListView;
1567
1568      ShellTree.ShellListView = _ShellListView;
1569      this.ctrlConsole.ShellListView = this._ShellListView;
1570      this.autoUpdater.UpdateAvailable += AutoUpdater_UpdateAvailable;
1571      this.updateCheckTimer.Interval = 10000;//3600000 * 3;
1572      this.updateCheckTimer.Tick += new EventHandler(updateCheckTimer_Tick);
1573      this.updateCheckTimer.Enabled = false;
1574
1575      UpdateRecycleBinInfos();
1576      bool exitApp = false;
1577
1578      try {
1579        //Sets up FileSystemWatcher for Favorites folder
1580        var LinksFolderWarcher = new FileSystemWatcher(KnownFolders.Links.ParsingName);
1581        LinksFolderWarcher.Created += LinksFolderWarcher_Created;
1582        LinksFolderWarcher.Deleted += LinksFolderWarcher_Deleted;
1583        LinksFolderWarcher.Renamed += LinksFolderWarcher_Renamed;
1584        LinksFolderWarcher.EnableRaisingEvents = true;
1585
1586        //Set up Favorites Menu
1587
1588        //Task.Run(() => SetUpFavoritesMenu());
1589        SetUpFavoritesMenu();
1590
1591        //Load the ShellSettings
1592        _IsCalledFromLoading = true;
1593        var statef = new BExplorer.Shell.Interop.Shell32.SHELLSTATE();
1594        BExplorer.Shell.Interop.Shell32.SHGetSetSettings(ref statef, BExplorer.Shell.Interop.Shell32.SSF.SSF_SHOWALLOBJECTS | BExplorer.Shell.Interop.Shell32.SSF.SSF_SHOWEXTENSIONS, false);
1595        chkHiddenFiles.IsChecked = statef.fShowAllObjects == 1;
1596        _ShellListView.ShowHidden = chkHiddenFiles.IsChecked.Value;
1597        ShellTree.IsShowHiddenItems = chkHiddenFiles.IsChecked.Value;
1598        chkExtensions.IsChecked = statef.fShowExtensions == 1;
1599        this._ShellListView.IsFileExtensionShown = statef.fShowExtensions == 1;
1600        _IsCalledFromLoading = false;
1601
1602        isOnLoad = true;
1603
1604        //'load from Registry
1605        this.LoadRegistryRelatedSettings();
1606
1607        //'set up Explorer control
1608        InitializeExplorerControl();
1609
1610        ViewGallery.SelectedIndex = 2;
1611
1612        if (this.chkUpdateCheck.IsChecked.Value) {
1613          this.updateCheckTimer.Start();
1614        }
1615
1616        AddToLog("Session Began");
1617        isOnLoad = false;
1618        SetsUpJumpList();
1619
1620        //Setup Clipboard monitor
1621        cbm.ClipboardChanged += cbm_ClipboardChanged;
1622
1623        if (exitApp) {
1624          Application.Current.Shutdown();
1625          return;
1626        }
1627
1628        // Set up Column Header menu
1629        chcm = new ContextMenu() { Placement = PlacementMode.MousePoint };
1630
1631        //Set up Version Info
1632        verNumber.Content = "Version " + (Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false).FirstOrDefault() as AssemblyInformationalVersionAttribute).InformationalVersion;
1633        lblArchitecture.Content = Kernel32.IsThis64bitProcess() ? "64-bit version" : "32-bit version";
1634
1635        tcMain_Setup(null, null);
1636        //'set StartUp location
1637        if (Application.Current.Properties["cmd"] != null && Application.Current.Properties["cmd"].ToString() != "-minimized") {
1638          var cmd = Application.Current.Properties["cmd"].ToString();
1639          if (cmd != "/nw" && cmd != "/t") {
1640            var sho = FileSystemListItem.ToFileSystemItem(this._ShellListView.LVHandle, cmd.ToShellParsingName());
1641            tcMain.NewTab(sho, true);
1642          }
1643        } else {
1644          InitializeInitialTabs();
1645        }
1646
1647        if (!File.Exists("Settings.xml")) return;
1648        var Settings = XElement.Load("Settings.xml");
1649
1650        if (Settings.Element("DropDownItems") != null) {
1651          foreach (var item in Settings.Element("DropDownItems").Elements()) {
1652            bcbc.DropDownItems.Add(item.Value);
1653          }
1654        }
1655
1656        focusTimer.Tick += focusTimer_Tick;
1657      } catch (Exception exe) {
1658        MessageBox.Show($"An error occurred while loading the window. Please report this issue at http://bugs.gainedge.org/public/betterexplorer. \r\n\r\n Here is some information about the error: \r\n\r\n{exe.Message}\r\n\r\n{exe}", "Error While Loading", MessageBoxButton.OK, MessageBoxImage.Error);
1659      }
1660    }
1661
1662    private void AutoUpdater_UpdateAvailable(object sender, EventArgs e) {
1663      if (this._IsCheckUpdateFromTimer && !this._IsUpdateNotificationMessageBoxShown) {
1664        this._IsUpdateNotificationMessageBoxShown = true;
1665        var newVersion = this.autoUpdater.Version;
1666        var changes = this.autoUpdater.Changes;
1667        var config = new TaskDialogOptions();
1668
1669        config.Owner = this;
1670        config.Title = "Update";
1671        config.MainInstruction = "There is new updated version " + newVersion + " available!";
1672        config.Content = "The new version have the following changes:\r\n" + changes;
1673        config.ExpandedInfo = "You can download and install the new version immediately by clicking \"Download & Install\" button.\r\nYou can skip this version from autoupdate check by clicking \"Skip this version\" button.";
1674        //config.VerificationText = "Don't show me this message again";
1675        config.CustomButtons = new string[] { "&Download & Install", "Skip this version", "&Close" };
1676        config.MainIcon = VistaTaskDialogIcon.SecurityWarning;
1677
1678        if (newVersion.Contains("RC") || newVersion.Contains("Nightly") || newVersion.Contains("Beta") || newVersion.Contains("Alpha")) {
1679          config.FooterText = "This is an experimental version and may contains bugs. Use at your own risk!";
1680          config.FooterIcon = VistaTaskDialogIcon.Warning;
1681        } else {
1682          config.FooterText = "This is a final version and can be installed safely!";
1683          config.FooterIcon = VistaTaskDialogIcon.SecuritySuccess;
1684        }
1685
1686        config.AllowDialogCancellation = true;
1687        config.Callback = taskDialog_Callback;
1688
1689        TaskDialogResult res = TaskDialog.Show(config);
1690        this._IsCheckUpdateFromTimer = false;
1691        this._IsUpdateNotificationMessageBoxShown = false;
1692      }
1693    }
1694
1695    private bool taskDialog_Callback(IActiveTaskDialog dialog, VistaTaskDialogNotificationArgs args, object callbackData) {
1696      bool result = false;
1697
1698      switch (args.Notification) {
1699        case VistaTaskDialogNotification.ButtonClicked:
1700          if (args.ButtonId == 500) {
1701            this.autoUpdater.ReadyToBeInstalled += AutoUpdater_ReadyToBeInstalled;
1702            this.autoUpdater.InstallNow();
1703          } else if (args.ButtonId == 501) {
1704          }
1705          break;
1706      }
1707
1708      return result;
1709    }
1710
1711    private void AutoUpdater_ReadyToBeInstalled(object sender, EventArgs e) {
1712      this.autoUpdater.ReadyToBeInstalled -= AutoUpdater_ReadyToBeInstalled;
1713      this.autoUpdater.InstallNow();
1714    }
1715
1716    #endregion
1717
1718    #region On Closing
1719
1720    private void SaveSettings(String openedTabs) {
1721      BESettings.LastWindowWidth = this.Width;
1722      BESettings.LastWindowHeight = this.Height;
1723      BESettings.LastWindowPosLeft = this.Left;
1724      BESettings.LastWindowPosTop = this.Top;
1725
1726      if (btnBlue.IsChecked == true)
1727        BESettings.CurrentTheme = "Blue";
1728      else if (btnSilver.IsChecked == true)
1729        BESettings.CurrentTheme = "Silver";
1730      else if (btnBlack.IsChecked == true)
1731        BESettings.CurrentTheme = "Black";
1732      else if (btnMetro.IsChecked == true)
1733        BESettings.CurrentTheme = "Metro";
1734
1735      switch (this.WindowState) {
1736        case WIN.WindowState.Maximized:
1737          BESettings.LastWindowState = 2;
1738          break;
1739        case WIN.WindowState.Minimized:
1740          BESettings.LastWindowState = 1;
1741          break;
1742        case WIN.WindowState.Normal:
1743          BESettings.LastWindowState = 0;
1744          break;
1745        default:
1746          BESettings.LastWindowState = -1;
1747          break;
1748      }
1749
1750      BESettings.IsRibonMinimized = TheRibbon.IsMinimized;
1751      BESettings.OpenedTabs = openedTabs;
1752      BESettings.RTLMode = FlowDirection == FlowDirection.RightToLeft;
1753      BESettings.ShowCheckboxes = this._ShellListView.ShowCheckboxes;
1754      BESettings.TabBarAlignment = this.TabbaBottom.IsChecked == true ? "bottom" : "top";
1755
1756      if (BESettings.IsPreviewPaneEnabled)
1757        BESettings.PreviewPaneWidth = clPreview.ActualWidth;
1758      if (BESettings.IsInfoPaneEnabled)
1759        BESettings.InfoPaneHeight = rPreviewPane.ActualHeight;
1760      if (BESettings.IsConsoleShown)
1761        BESettings.CmdWinHeight = rCommandPrompt.ActualHeight;
1762
1763      BESettings.SaveSettings();
1764    }
1765
1766    private void RibbonWindow_Closing(object sender, CancelEventArgs e) {
1767      var itemColorSettingsLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"BExplorer\itemcolors.cfg");
1768      var doc = new XmlDocument();
1769      XmlElement elementRoot = doc.CreateElement(string.Empty, "Root", string.Empty);
1770      foreach (var element in this.LVItemsColorCol) {
1771        XmlElement elementRow = doc.CreateElement(string.Empty, "ItemColorRow", string.Empty);
1772        XmlElement elementExtension = doc.CreateElement(string.Empty, "Extensions", string.Empty);
1773        elementExtension.InnerText = element.ExtensionList;
1774        XmlElement elementColor = doc.CreateElement(string.Empty, "Color", string.Empty);
1775        elementColor.InnerText = BitConverter.ToInt32(new byte[] { element.TextColor.A, element.TextColor.R, element.TextColor.G, element.TextColor.B }, 0).ToString();
1776        elementRow.AppendChild(elementExtension);
1777        elementRow.AppendChild(elementColor);
1778        elementRoot.AppendChild(elementRow);
1779      }
1780      doc.AppendChild(elementRoot);
1781      doc.Save(itemColorSettingsLocation);
1782
1783      if (this.OwnedWindows.OfType<FileOperationDialog>().Any()) {
1784        if (MessageBox.Show("Are you sure you want to cancel all running file operation tasks?", "", MessageBoxButton.YesNo) == MessageBoxResult.No) {
1785          e.Cancel = true;
1786          return;
1787        }
1788      }
1789
1790      if (this.WindowState != WindowState.Minimized) {
1791        SaveSettings(string.Concat(from item in tcMain.Items.Cast<Wpf.Controls.TabItem>() select ";" + item.ShellObject.ParsingName));
1792      }
1793
1794      this._ShellListView.SaveSettingsToDatabase(this._ShellListView.CurrentFolder);
1795      //SaveHistoryToFile(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\history.txt", this.bcbc.DropDownItems.OfType<String>().Select(s => s).ToList());
1796      AddToLog("Session Ended");
1797      if (!this.IsMultipleWindowsOpened) {
1798        e.Cancel = true;
1799        App.IsStartMinimized = true;
1800
1801        this.WindowState = WindowState.Minimized;
1802        this.Visibility = Visibility.Hidden;
1803      } else {
1804        beNotifyIcon.Visibility = Visibility.Collapsed;
1805      }
1806
1807      if (!File.Exists("Settings.xml")) new XElement("Settings").Save("Settings.xml");
1808      //var Data = bcbc.DropDownItems;
1809
1810      var Settings = XElement.Load("Settings.xml");
1811      if (Settings.Element("DropDownItems") == null)
1812        Settings.Add(new XElement("DropDownItems"));
1813      else
1814        Settings.Element("DropDownItems").RemoveAll();
1815
1816      foreach (var item in bcbc.DropDownItems.OfType<string>().Reverse().Take(15)) {
1817        Settings.Element("DropDownItems").Add(new XElement("Item", item));
1818      }
1819
1820      //Settings.Save("Settings.xml");
1821    }
1822
1823    #endregion
1824
1825    #region Change Ribbon Color (Theme)
1826
1827    public void ChangeRibbonTheme(string ThemeName, bool IsMetro = false) {
1828      Dispatcher.BeginInvoke(IsMetro ? DispatcherPriority.ApplicationIdle : DispatcherPriority.Render, (ThreadStart)(() => {
1829        var owner = Window.GetWindow(this);
1830        Application.Current.Resources.BeginInit();
1831        Application.Current.Resources.MergedDictionaries.RemoveAt(1);
1832
1833        if (IsMetro)
1834          Application.Current.Resources.MergedDictionaries.Insert(1, new ResourceDictionary() { Source = new Uri("pack://application:,,,/Fluent;component/Themes/Office2013/Generic.xaml") });
1835        else
1836          Application.Current.Resources.MergedDictionaries.Insert(1, new ResourceDictionary() { Source = new Uri($"pack://application:,,,/Fluent;component/Themes/Office2010/{ThemeName}.xaml") });
1837
1838        Application.Current.Resources.EndInit();
1839
1840        if (owner is RibbonWindow) {
1841          owner.Style = null;
1842          owner.Style = owner.FindResource("RibbonWindowStyle") as Style;
1843          owner.Style = null;
1844
1845          // Resize Window to work around alignment issues caused by theme change
1846          ++owner.Width;
1847          --owner.Width;
1848        }
1849
1850        Settings.BESettings.CurrentTheme = ThemeName;
1851        Settings.BESettings.SaveSettings();
1852      }));
1853    }
1854
1855    private void btnSilver_Click(object sender, RoutedEventArgs e) {
1856      ChangeRibbonTheme("Silver");
1857      KeepBackstageOpen = true;
1858    }
1859
1860    private void btnBlue_Click(object sender, RoutedEventArgs e) {
1861      ChangeRibbonTheme("Blue");
1862      KeepBackstageOpen = true;
1863    }
1864
1865    private void btnBlack_Click(object sender, RoutedEventArgs e) {
1866      ChangeRibbonTheme("Black");
1867      KeepBackstageOpen = true;
1868    }
1869
1870    private void btnGreen_Click(object sender, RoutedEventArgs e) {
1871      ChangeRibbonTheme("Metro", true);
1872      KeepBackstageOpen = true;
1873    }
1874
1875    #endregion
1876
1877    #region Archive Commands
1878
1879    private void btnExtractNow_Click(object sender, RoutedEventArgs e) {
1880      if (chkUseNewFolder.IsChecked == true) {
1881        string OutputLoc = $"{txtExtractLocation.Text}\\{Utilities.RemoveExtensionsFromFile(_ShellListView.GetFirstSelectedItem().ParsingName, new FileInfo(_ShellListView.GetFirstSelectedItem().ParsingName).Extension)}";
1882
1883        try {
1884          Directory.CreateDirectory(OutputLoc);
1885          ExtractToLocation(SelectedArchive, OutputLoc);
1886        } catch (Exception) {
1887          MessageBoxResult wtd = MessageBox.Show($"The directory {OutputLoc} already exists. Would you like for BetterExplorer to extract there instead?", "Folder Exists", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
1888          switch (wtd) {
1889            case MessageBoxResult.Cancel:
1890              break;
1891            case MessageBoxResult.No:
1892              break;
1893            case MessageBoxResult.None:
1894              break;
1895            case MessageBoxResult.OK:
1896              break;
1897            case MessageBoxResult.Yes:
1898              ExtractToLocation(SelectedArchive, OutputLoc);
1899              break;
1900            default:
1901              break;
1902          }
1903        }
1904      } else {
1905        ExtractToLocation(SelectedArchive, txtExtractLocation.Text);
1906      }
1907    }
1908
1909    private void btnChooseLocation_Click(object sender, RoutedEventArgs e) {
1910      var dlg = new FolderSelectDialog();
1911      if (dlg.ShowDialog())
1912        txtExtractLocation.Text = dlg.FileName;
1913    }
1914
1915    private void ExtractToLocation(string archive, string output) {
1916      var selectedItems = new List<string>() { archive };
1917      var archiveProcressScreen = new ArchiveProcressScreen(selectedItems, output, ArchiveAction.Extract, "");
1918      archiveProcressScreen.ExtractionCompleted += new ArchiveProcressScreen.ExtractionCompleteEventHandler(ExtractionHasCompleted);
1919      AddToLog($"Archive Extracted to {output} from source {archive}");
1920      archiveProcressScreen.Show();
1921    }
1922
1923    private void ExtractionHasCompleted(object sender, ArchiveEventArgs e) {
1924      if (chkOpenResults.IsChecked == true) tcMain.NewTab(e.OutputLocation);
1925    }
1926
1927    private void miExtractToLocation_Click(object sender, RoutedEventArgs e) {
1928      var selectedItems = _ShellListView.SelectedItems.Select(item => item.ParsingName).ToList();
1929
1930      try {
1931        var CAI = new CreateArchive(selectedItems, false, _ShellListView.GetFirstSelectedItem().ParsingName);
1932        CAI.Show(this.GetWin32Window());
1933      } catch {
1934
1935      }
1936    }
1937
1938    private void miExtractHere_Click(object sender, RoutedEventArgs e) {
1939      string FileName = _ShellListView.GetFirstSelectedItem().ParsingName;
1940      var extractor = new SevenZipExtractor(FileName);
1941      string DirectoryName = Path.GetDirectoryName(FileName);
1942      string ArchName = Path.GetFileNameWithoutExtension(FileName);
1943      extractor.Extracting += new EventHandler<ProgressEventArgs>(extractor_Extracting);
1944      extractor.ExtractionFinished += new EventHandler<EventArgs>(extractor_ExtractionFinished);
1945      extractor.FileExtractionStarted += new EventHandler<FileInfoEventArgs>(extractor_FileExtractionStarted);
1946      extractor.FileExtractionFinished += new EventHandler<FileInfoEventArgs>(extractor_FileExtractionFinished);
1947      extractor.PreserveDirectoryStructure = true;
1948      string Separator = "";
1949      if (DirectoryName[DirectoryName.Length - 1] != Char.Parse(@"\")) Separator = @"\";
1950      AddToLog($"Extracted Archive to {DirectoryName}{Separator}{ArchName} from source {FileName}");
1951      extractor.BeginExtractArchive(DirectoryName + Separator + ArchName);
1952    }
1953
1954    void extractor_FileExtractionFinished(object sender, FileInfoEventArgs e) {
1955      //throw new NotImplementedException();
1956    }
1957
1958    void extractor_FileExtractionStarted(object sender, FileInfoEventArgs e) {
1959      //throw new NotImplementedException();
1960    }
1961
1962    void extractor_ExtractionFinished(object sender, EventArgs e) {
1963      //throw new NotImplementedException();
1964      (sender as SevenZipExtractor)?.Dispose();
1965    }
1966
1967    void extractor_Extracting(object sender, ProgressEventArgs e) {
1968      //throw new NotImplementedException();
1969    }
1970
1971    private void btnExtract_Click(object sender, RoutedEventArgs e) => miExtractHere_Click(sender, e);
1972
1973    private void btnCheckArchive_Click(object sender, RoutedEventArgs e) => new Thread(new ThreadStart(DoCheck)).Start();
1974
1975    private void DoCheck() {
1976      string FileName = _ShellListView.GetFirstSelectedItem().ParsingName;
1977      var extractor = new SevenZipExtractor(FileName);
1978      if (!extractor.Check())
1979        MessageBox.Show("Not Pass");
1980      else
1981        MessageBox.Show("Pass");
1982
1983      extractor.Dispose();
1984    }
1985
1986    private void btnViewArchive_Click(object sender, RoutedEventArgs e) {
1987      var name = _ShellListView.SelectedItems.First().ParsingName;
1988      string ICON_DLLPATH = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "shell32.dll");
1989      var archiveDetailView = new ArchiveDetailView(ICON_DLLPATH, name);
1990      archiveDetailView.Show(this.GetWin32Window());
1991
1992      //ArchiveViewWindow g = new ArchiveViewWindow( ShellListView.GetFirstSelectedItem(), IsPreviewPaneEnabled, IsInfoPaneEnabled);
1993      //g.Show();
1994    }
1995
1996    private void btnCreateArchive_Click(object sender, RoutedEventArgs e) {
1997      //ArchiveCreateWizard acw = new ArchiveCreateWizard(ShellListView.SelectedItems, ShellListView.CurrentFolder.ParsingName);
1998      //         acw.win = this;
1999      //         acw.LoadStrings();
2000      //acw.Show();
2001      //AddToLog("Archive Creation Wizard begun. Current location: " + ShellListView.CurrentFolder.ParsingName);
2002    }
2003
2004    #endregion
2005
2006    #region Library Commands
2007
2008    private void btnChangeLibIcon_Click(object sender, RoutedEventArgs e) => new IconView().LoadIcons(_ShellListView, true);
2009
2010    private void btnOLItem_Click(object sender, RoutedEventArgs e) {
2011      //this._ShellListView.IsLibraryInModify = true;
2012      this._ShellListView.CurrentRefreshedItemIndex = this._ShellListView.GetFirstSelectedItemIndex();
2013      var NeededFile = _ShellListView.GetSelectedCount() == 1 ? _ShellListView.GetFirstSelectedItem() : _ShellListView.CurrentFolder;
2014      var lib = ShellLibrary.Load(Path.GetFileNameWithoutExtension(NeededFile.ParsingName), false);
2015
2016      switch ((sender as MenuItem).Tag.ToString()) {
2017        case "gu":
2018          lib.LibraryType = LibraryFolderType.Generic;
2019          lib.Close();
2020          break;
2021        case "doc":
2022          lib.LibraryType = LibraryFolderType.Documents;
2023          lib.Close();
2024          break;
2025        case "pic":
2026          lib.LibraryType = LibraryFolderType.Pictures;
2027          lib.Close();
2028          break;
2029        case "vid":
2030          lib.LibraryType = LibraryFolderType.Videos;
2031          lib.Close();
2032          break;
2033        case "mu":
2034          lib.LibraryType = LibraryFolderType.Music;
2035          lib.Close();
2036          break;
2037        default:
2038          break;
2039      }
2040    }
2041
2042    private void chkPinNav_CheckChanged(object sender, RoutedEventArgs e) {
2043      //this._ShellListView.IsLibraryInModify = true;
2044      this._ShellListView.CurrentRefreshedItemIndex = this._ShellListView.GetFirstSelectedItemIndex();
2045      var NeededFile = _ShellListView.GetSelectedCount() == 1 ? _ShellListView.GetFirstSelectedItem() : _ShellListView.CurrentFolder;
2046      try {
2047        var lib = ShellLibrary.Load(Path.GetFileNameWithoutExtension(NeededFile.ParsingName), false);
2048        if (!IsFromSelectionOrNavigation)
2049          lib.IsPinnedToNavigationPane = e.RoutedEvent.Name == "Checked";
2050
2051        lib.Close();
2052      } catch (FileNotFoundException) { }
2053    }
2054
2055    private void btnManageLib_Click(object sender, RoutedEventArgs e) {
2056      this._ShellListView.CurrentRefreshedItemIndex = this._ShellListView.GetFirstSelectedItemIndex();
2057      try {
2058        ShellLibrary.ShowManageLibraryUI(_ShellListView.GetFirstSelectedItem().ComInterface,
2059                                        this.Handle, "Choose which folders will be in this library", "A library gathers content from all of the folders listed below and puts it all in one window for you to see.", true);
2060      } catch {
2061        ShellLibrary.ShowManageLibraryUI(_ShellListView.CurrentFolder.ComInterface,
2062                                        this.Handle, "Choose which folders will be in this library", "A library gathers content from all of the folders listed below and puts it all in one window for you to see.", true);
2063      }
2064    }
2065
2066    #endregion
2067
2068    #region Navigation (Back/Forward Arrows) and Up Button
2069
2070    private void leftNavBut_Click(object sender, RoutedEventArgs e) {
2071      tcMain.isGoingBackOrForward = true;
2072      NavigationController((tcMain.SelectedItem as Wpf.Controls.TabItem).log.NavigateBack());
2073    }
2074
2075    private void rightNavBut_Click(object sender, RoutedEventArgs e) {
2076      tcMain.isGoingBackOrForward = true;
2077      NavigationController((tcMain.SelectedItem as Wpf.Controls.TabItem).log.NavigateForward());
2078    }
2079
2080    private void downArrow_Click(object sender, RoutedEventArgs e) {
2081      _CMHistory.Items.Clear();
2082      if (tcMain.SelectedItem == null) return;
2083      var nl = ((Wpf.Controls.TabItem)tcMain.SelectedItem).log;
2084      var i = 0;
2085      foreach (var item in nl.HistoryItemsList) {
2086        if (item != null) {
2087          var itemCopy = item.Clone();
2088          _CMHistory.Items.Add(Utilities.Build_MenuItem(itemCopy.DisplayName, itemCopy, itemCopy.ThumbnailSource(16, ShellThumbnailFormatOption.IconOnly, ShellThumbnailRetrievalOption.Default),
2089                                                                                                           checkable: true, isChecked: i == nl.CurrentLocPos, GroupName: "G1", onClick: miItems_Click));
2090        }
2091        i++;
2092      }
2093
2094      _CMHistory.Placement = PlacementMode.Bottom;
2095      _CMHistory.PlacementTarget = navBarGrid;
2096      _CMHistory.IsOpen = true;
2097    }
2098
2099    void miItems_Click(object sender, RoutedEventArgs e) {
2100      var item = (IListItemEx)(sender as MenuItem).Tag;
2101      if (item != null) {
2102        tcMain.isGoingBackOrForward = true;
2103        NavigationLog nl = (tcMain.Items[tcMain.SelectedIndex] as Wpf.Controls.TabItem).log;
2104        (sender as MenuItem).IsChecked = true;
2105        nl.CurrentLocPos = _CMHistory.Items.IndexOf(sender);
2106        NavigationController(item);
2107      }
2108    }
2109
2110    private void btnUpLevel_Click(object sender, RoutedEventArgs e) {
2111      if (_ShellListView.CanNavigateParent) {
2112        this.IsNeedEnsureVisible = true;
2113        _ShellListView.NavigateParent();
2114      }
2115    }
2116
2117    #endregion
2118
2119    #region View Tab/Status Bar
2120
2121    private void btnMoreColls_Click(object sender, RoutedEventArgs e) => micm_Click(sender, e);
2122    private void btnAutosizeColls_Click(object sender, RoutedEventArgs e) => this._ShellListView.AutosizeAllColumns(-1);
2123
2124    private void zoomSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) {
2125      if (this._IsShouldRiseViewChanged)
2126        _ShellListView.ResizeIcons((int)e.NewValue);
2127    }
2128
2129    void mig_Click(object sender, RoutedEventArgs e) {
2130      this._ShellListView.EnableGroups();
2131      this._ShellListView.GenerateGroupsFromColumn((sender as MenuItem).Tag as Collumns);
2132    }
2133
2134    private Boolean _IsShouldRiseViewChanged = true;
2135
2136    private void StatusBar_Folder_Buttons(object sender, RoutedEventArgs e) {
2137      this._IsShouldRiseViewChanged = false;
2138      if (_ShellListView == null)
2139        return;
2140      else if (sender == btnSbDetails)
2141        _ShellListView.View = ShellViewStyle.Details;
2142      else if (sender == btnSbIcons)
2143        _ShellListView.View = ShellViewStyle.Medium;
2144      else if (sender == btnSbTiles)
2145        _ShellListView.View = ShellViewStyle.Tile;
2146      this._IsShouldRiseViewChanged = true;
2147    }
2148
2149    void mi_Click(object sender, RoutedEventArgs e) {
2150      var item = (sender as MenuItem);
2151      var parentButton = item.Parent as DropDownButton;
2152      var ascitem = (MenuItem)parentButton.Items[parentButton.Items.IndexOf(misa)];
2153
2154      var Sort = ascitem.IsChecked ? WIN.Forms.SortOrder.Ascending : WIN.Forms.SortOrder.Descending;
2155      _ShellListView.SetSortCollumn(true, (Collumns)item.Tag, Sort);
2156    }
2157
2158    void misng_Click(object sender, RoutedEventArgs e) {
2159      (sender as MenuItem).IsChecked = true;
2160      if (this._ShellListView.IsGroupsEnabled) this._ShellListView.DisableGroups();
2161    }
2162
2163    private void inRibbonGallery1_SelectionChanged(object sender, SelectionChangedEventArgs e) {
2164      if (!this._IsShouldRiseViewChanged || !this._ShellListView.IsViewSelectionAllowed) return;
2165      e.Handled = true;
2166      if (e.AddedItems.Count == 0) return;
2167      var selectedItem = e.AddedItems[0];
2168      var selectedItemIndex = ViewGallery.Items.IndexOf(selectedItem);
2169      this._IsShouldRiseViewChanged = false;
2170      switch (selectedItemIndex) {
2171        case 0:
2172          _ShellListView.View = ShellViewStyle.ExtraLargeIcon;
2173          break;
2174        case 1:
2175          _ShellListView.View = ShellViewStyle.LargeIcon;
2176          break;
2177        case 2:
2178          _ShellListView.View = ShellViewStyle.Medium;
2179          break;
2180        case 3:
2181          _ShellListView.View = ShellViewStyle.SmallIcon;
2182          break;
2183        case 4:
2184          _ShellListView.View = ShellViewStyle.List;
2185          break;
2186        case 5:
2187          _ShellListView.View = ShellViewStyle.Details;
2188          break;
2189        case 6:
2190          _ShellListView.View = ShellViewStyle.Tile;
2191          break;
2192        case 7:
2193          _ShellListView.View = ShellViewStyle.Content;
2194          break;
2195        case 8:
2196          _ShellListView.View = ShellViewStyle.Thumbstrip;
2197          break;
2198        default:
2199          break;
2200      }
2201      this._IsShouldRiseViewChanged = true;
2202    }
2203
2204    private void chkHiddenFiles_Checked(object sender, RoutedEventArgs e) {
2205      if (_IsCalledFromLoading) return;
2206      Dispatcher.BeginInvoke(new Action(
2207                      delegate () {
2208                        var state = new BExplorer.Shell.Interop.Shell32.SHELLSTATE() { fShowAllObjects = 1 };
2209                        BExplorer.Shell.Interop.Shell32.SHGetSetSettings(ref state, BExplorer.Shell.Interop.Shell32.SSF.SSF_SHOWALLOBJECTS, true);
2210                        _ShellListView.ShowHidden = true;
2211
2212                        ShellTree.IsShowHiddenItems = true;
2213                        ShellTree.RefreshContents();
2214                      }
2215      ));
2216    }
2217
2218    private void chkHiddenFiles_Unchecked(object sender, RoutedEventArgs e) {
2219      if (_IsCalledFromLoading) return;
2220      Dispatcher.BeginInvoke(new Action(
2221                      delegate () {
2222                        var state = new BExplorer.Shell.Interop.Shell32.SHELLSTATE() { fShowAllObjects = 0 };
2223                        BExplorer.Shell.Interop.Shell32.SHGetSetSettings(ref state, BExplorer.Shell.Interop.Shell32.SSF.SSF_SHOWALLOBJECTS, true);
2224                        _ShellListView.ShowHidden = false;
2225
2226                        ShellTree.IsShowHiddenItems = false;
2227                        ShellTree.RefreshContents();
2228                      }
2229      ));
2230    }
2231
2232    private void chkExtensions_Checked(object sender, RoutedEventArgs e) {
2233      if (_IsCalledFromLoading) return;
2234      Dispatcher.BeginInvoke(new Action(
2235                      delegate () {
2236                        var state = new BExplorer.Shell.Interop.Shell32.SHELLSTATE();
2237                        state.fShowExtensions = 1;
2238                        BExplorer.Shell.Interop.Shell32.SHGetSetSettings(ref state, BExplorer.Shell.Interop.Shell32.SSF.SSF_SHOWEXTENSIONS, true);
2239                        this._ShellListView.IsFileExtensionShown = true;
2240                        _ShellListView.RefreshContents();
2241                      }
2242      ));
2243    }
2244
2245    private void chkExtensions_Unchecked(object sender, RoutedEventArgs e) {
2246      if (_IsCalledFromLoading) return;
2247      Dispatcher.BeginInvoke(new Action(
2248                      delegate () {
2249                        var state = new BExplorer.Shell.Interop.Shell32.SHELLSTATE();
2250                        state.fShowExtensions = 0;
2251                        BExplorer.Shell.Interop.Shell32.SHGetSetSettings(ref state, BExplorer.Shell.Interop.Shell32.SSF.SSF_SHOWEXTENSIONS, true);
2252                        this._ShellListView.IsFileExtensionShown = false;
2253                        _ShellListView.RefreshContents();
2254                      }
2255      ));
2256    }
2257
2258    #endregion
2259
2260    #region Hide items
2261
2262    private void btnHideSelItems_Click(object sender, RoutedEventArgs e) {
2263      foreach (var item in _ShellListView.SelectedItems.Where(x => x.IsFolder)) {
2264        var di = new DirectoryInfo(item.ParsingName);
2265        di.Attributes |= System.IO.FileAttributes.Hidden;
2266      }
2267      foreach (var item in _ShellListView.SelectedItems.Where(x => !x.IsFolder & !x.IsNetworkPath & !x.IsDrive)) {
2268        var di = new FileInfo(item.ParsingName);
2269        di.Attributes |= System.IO.FileAttributes.Hidden;
2270      }
2271
2272      _ShellListView.RefreshContents();
2273    }
2274
2275    [Obsolete("Why do we have this")]
2276    private void miHideItems_Click(object sender, RoutedEventArgs e) {
2277      //FIXME:
2278      //ShellItemCollection SelItems = ShellListView.SelectedItems;
2279      //pd = new IProgressDialog(this.Handle);
2280      //pd.Title = "Applying attributes";
2281      //pd.CancelMessage = "Please wait while the operation is cancelled";
2282      //pd.Maximum = 100;
2283      //pd.Value = 0;
2284      //pd.Line1 = "Applying attributes to:";
2285      //pd.Line3 = "Calculating Time Remaining...";
2286      //pd.ShowDialog(IProgressDialog.PROGDLG.Normal, IProgressDialog.PROGDLG.AutoTime, IProgressDialog.PROGDLG.NoMinimize);
2287      //Thread hthread = new Thread(new ParameterizedThreadStart(DoHideShowWithChilds));
2288      //hthread.Start(SelItems);
2289    }
2290
2291    #endregion
2292
2293    #region Share Tab Commands (excluding Archive)
2294
2295    private void btnDisconectDrive_Click(object sender, RoutedEventArgs e) => BExplorer.Shell.Interop.Shell32.WNetDisconnectDialog(this.Handle, 1);
2296    private void Button_Click_4(object sender, RoutedEventArgs e) => this._ShellListView.OpenShareUI(); //TODO: Rename Button_Click_4
2297
2298    private void btnMapDrive_Click(object sender, RoutedEventArgs e) {
2299      BExplorer.Shell.Interop.Shell32.MapDrive(this.Handle, this._ShellListView.SelectedItems.Count() == 1 ? this._ShellListView.GetFirstSelectedItem().ParsingName : String.Empty);
2300    }
2301
2302    private void btnAdvancedSecurity_Click(object sender, RoutedEventArgs e) {
2303      _ShellListView.ShowPropPage(this.Handle, _ShellListView.GetFirstSelectedItem().ParsingName, User32.LoadResourceString(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "shell32.dll"), 9046, "Security1"));
2304    }
2305
2306    #endregion
2307
2308    #region Change Language
2309
2310    private void TranslationComboBox_DropDownOpened(object sender, EventArgs e) => (sender as Fluent.ComboBox).Focus();
2311    private void TranslationHelp_Click(object sender, RoutedEventArgs e) => Process.Start(TranslationURL.Text);
2312
2313    private void TranslationComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
2314      e.Handled = true;
2315      if (this.IsLoaded) {
2316        BESettings.Locale = ((TranslationComboBoxItem)e.AddedItems[0]).LocaleCode;
2317        BESettings.SaveSettings();
2318        ((App)Application.Current).SelectCulture(((TranslationComboBoxItem)e.AddedItems[0]).LocaleCode);
2319
2320        if (_ShellListView.CurrentFolder.Parent.ParsingName == KnownFolders.Libraries.ParsingName) {
2321          btnCreateFolder.Header = FindResource("btnNewLibraryCP");       //"New Library";
2322          stNewFolder.Title = FindResource("btnNewLibraryCP").ToString(); //"New Library";
2323          stNewFolder.Text = "Creates a new library in the current folder.";
2324        } else {
2325          btnCreateFolder.Header = FindResource("btnNewFolderCP");        //"New Folder";
2326          stNewFolder.Title = FindResource("btnNewFolderCP").ToString();  //"New Folder";
2327          stNewFolder.Text = "Creates a new folder in the current folder";
2328        }
2329      }
2330    }
2331
2332    private void btnRemoveLangSetting_Click(object sender, RoutedEventArgs e) {
2333      RegistryKey rk = Registry.CurrentUser;
2334      RegistryKey rks = rk.OpenSubKey(@"Software\BExplorer", true);
2335
2336      rks.DeleteValue(@"Locale");
2337
2338      rks.Close();
2339      rk.Close();
2340    }
2341
2342    #endregion
2343
2344    #region Image Editing
2345
2346    private void btnResize_Click(object sender, RoutedEventArgs e) => ResizeImage.Open(_ShellListView.GetFirstSelectedItem());
2347
2348    private void Convert_Images(object sender, RoutedEventArgs e) {
2349      ImageFormat format = null; string extension = null;
2350
2351      if (sender == ConvertToJPG) {
2352        format = ImageFormat.Jpeg;
2353        extension = ".jpg";
2354      } else if (sender == ConvertToPNG) {
2355        format = ImageFormat.Png;
2356        extension = ".png";
2357      } else if (sender == ConvertToGIF) {
2358        format = ImageFormat.Gif;
2359        extension = ".gif";
2360      } else if (sender == ConvertToBMP) {
2361        format = ImageFormat.Bmp;
2362        extension = ".bmp";
2363      } else if (sender == ConvertToJPG) {
2364        format = ImageFormat.Wmf;
2365        extension = ".wmf";
2366      } else {
2367        throw new Exception("Invalid Sender");
2368      }
2369
2370      foreach (var item in _ShellListView.SelectedItems) {
2371        var cvt = new Bitmap(item.ParsingName);
2372        string namen = Utilities.RemoveExtensionsFromFile(item.ParsingName, new FileInfo(item.ParsingName).Extension);
2373        try {
2374          AddToLog("Converted Image from " + item.ParsingName + " to new file " + namen + extension);
2375          var newFilePath = namen + extension;
2376          cvt.Save(newFilePath, format);
2377          this._ShellListView.UnvalidateDirectory();
2378        } catch (Exception) {
2379          MessageBox.Show("There appears to have been an issue with converting the file. Make sure the filename \"" + Utilities.RemoveExtensionsFromFile(_ShellListView.GetFirstSelectedItem().DisplayName, new System.IO.FileInfo(item.ParsingName).Extension) + extension + "\" does already not exist.", "Conversion Error", MessageBoxButton.OK, MessageBoxImage.Error);
2380        }
2381        cvt.Dispose();
2382      }
2383    }
2384
2385    /// <summary>
2386    /// Sets the wallpaper based on the sender
2387    /// </summary>
2388    /// <param name="sender"></param>
2389    /// <param name="e"></param>
2390    private void Set_Wallpaper(object sender, RoutedEventArgs e) {
2391      Wallpaper.Style ThisStyle;
2392
2393      if (sender == btnWallpaper)
2394        ThisStyle = Wallpaper.Style.Stretched;
2395      else if (sender == miWallFill)
2396        ThisStyle = Wallpaper.Style.Fill;
2397      else if (sender == miWallFit)
2398        ThisStyle = Wallpaper.Style.Fit;
2399      else if (sender == miWallStretch)
2400        ThisStyle = Wallpaper.Style.Stretched;
2401      else if (sender == miWallTile)
2402        ThisStyle = Wallpaper.Style.Tiled;
2403      else if (sender == miWallCenter)
2404        ThisStyle = Wallpaper.Style.Centered;
2405      else
2406        throw new Exception("Invalid Sender");
2407
2408      Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => {
2409        var TheWall = new Wallpaper();
2410        TheWall.Set(new Uri(_ShellListView.GetFirstSelectedItem().ParsingName), ThisStyle);
2411      }));
2412    }
2413
2414    private void RotateImages(object sender, RoutedEventArgs e) {
2415      RotateFlipType Rotation;
2416      string DefaultName_Addon = null;
2417
2418      switch ((sender as Control).Name) {
2419        case "btnRotateLeft":
2420          Rotation = RotateFlipType.Rotate270FlipNone;
2421          DefaultName_Addon = "_Rotated270";
2422          break;
2423        case "btnRotateRight":
2424          Rotation = RotateFlipType.Rotate90FlipNone;
2425          DefaultName_Addon = "_Rotated90";
2426          break;
2427        case "btnFlipX":
2428          Rotation = RotateFlipType.RotateNoneFlipX;
2429          DefaultName_Addon = "_FlippedX";
2430          break;
2431        case "btnFlipY":
2432          Rotation = RotateFlipType.RotateNoneFlipY;
2433          DefaultName_Addon = "_FlippedY";
2434          break;
2435        default:
2436          throw new Exception("Invalid sender");
2437      }
2438
2439      foreach (FileSystemListItem item in _ShellListView.SelectedItems) {
2440        var cvt = new Bitmap(item.ParsingName);
2441        cvt.RotateFlip(Rotation);
2442        if (BESettings.OverwriteImageWhileEditing) {
2443          cvt.Save(item.ParsingName);
2444        } else {
2445          string ext = item.ParsingName.Substring(item.ParsingName.LastIndexOf(".", StringComparison.Ordinal));
2446          string name = item.ParsingName;
2447          string namen = Utilities.RemoveExtensionsFromFile(name, new System.IO.FileInfo(name).Extension);
2448          var newFilePath = namen + DefaultName_Addon + ext;
2449          cvt.Save(newFilePath);
2450          this._ShellListView.UnvalidateDirectory();
2451        }
2452        cvt.Dispose();
2453        AddToLog("Rotated image " + item.ParsingName);
2454      }
2455    }
2456
2457    #endregion
2458
2459    #region Folder Tools Commands
2460
2461    private void btnChangeFoldericon_Click(object sender, RoutedEventArgs e) => new IconView().LoadIcons(this._ShellListView, false);
2462
2463    private void btnClearFoldericon_Click(object sender, RoutedEventArgs e) => _ShellListView.ClearFolderIcon(_ShellListView.GetFirstSelectedItem().ParsingName);
2464
2465    #endregion
2466
2467    #region Registry Setting Changes / BetterExplorerOperations Calls / Action Log
2468
2469    //private void chkIsRestoreTabs_CheckChanged(object sender, RoutedEventArgs e) => Utilities.SetRegistryValue("IsRestoreTabs", e.RoutedEvent.Name == "Checked" ? 1 : 0);
2470    //private void gridSplitter1_DragCompleted(object sender, DragCompletedEventArgs e) => Utilities.SetRegistryValue("SearchBarWidth", SearchBarColumn.Width.Value);
2471    //private void SearchBarReset_Click(object sender, RoutedEventArgs e) => Utilities.SetRegistryValue("SearchBarWidth", SearchBarColumn.Width.Value);
2472    //private void chkIsCFO_Click(object sender, RoutedEventArgs e) => Utilities.SetRegistryValue("IsCustomFO", chkIsCFO.IsChecked.Value == true ? 1 : 0);
2473
2474    private void chkIsRestoreTabs_CheckChanged(object sender, RoutedEventArgs e) {
2475      BESettings.IsRestoreTabs = e.RoutedEvent.Name == "Checked";
2476      BESettings.SaveSettings();
2477    }
2478    private void gridSplitter1_DragCompleted(object sender, DragCompletedEventArgs e) {
2479      BESettings.SearchBarWidth = SearchBarColumn.Width.Value;
2480      BESettings.SaveSettings();
2481    }
2482    private void SearchBarReset_Click(object sender, RoutedEventArgs e) {
2483      BESettings.SearchBarWidth = SearchBarColumn.Width.Value;
2484      BESettings.SaveSettings();
2485    }
2486    private void chkIsCFO_Click(object sender, RoutedEventArgs e) {
2487      BESettings.IsCustomFO = chkIsCFO.IsChecked.Value == true;
2488      BESettings.SaveSettings();
2489    }
2490
2491    private Process Rename_CheckChanged_Helper() {
2492      string ExePath = Utilities.AppDirectoryItem("BetterExplorerOperations.exe");
2493      Process proc = new Process();
2494      proc.StartInfo = new ProcessStartInfo {
2495        FileName = ExePath,
2496        Verb = "runas",
2497        UseShellExecute = true,
2498        Arguments = $"/env /user:Administrator \"{ExePath}\""
2499      };
2500      proc.Start();
2501      Thread.Sleep(1000);
2502
2503      return proc;
2504    }
2505
2506    private void chkIsDefault_CheckChanged(object sender, RoutedEventArgs e) {
2507      //TODO: Delete Dead Code!!
2508      if (isOnLoad) return;
2509      var proc = Rename_CheckChanged_Helper();
2510
2511      if (chkIsDefault.IsChecked == true) {
2512        //int h = (int)WindowsAPI.getWindowId(null, "BetterExplorerOperations");
2513        //int jj = WindowsAPI.sendWindowsStringMessage((int)WindowsAPI.getWindowId(null, "BetterExplorerOperations"), 0, "0x77654");
2514        //proc.WaitForExit();
2515        //if (proc.ExitCode == -1) {
2516        //	isOnLoad = true;
2517        //	(sender as Fluent.CheckBox).IsChecked = false;
2518        //	isOnLoad = false;
2519        //	MessageBox.Show("Can't set Better Explorer as default!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
2520        //}
2521      } else {
2522        //WindowsAPI.sendWindowsStringMessage((int)WindowsAPI.getWindowId(null, "BetterExplorerOperations"), 0, "0x77655");
2523        //proc.WaitForExit();
2524        //if (proc.ExitCode == -1) {
2525        //	isOnLoad = true;
2526        //	(sender as Fluent.CheckBox).IsChecked = true;
2527        //	isOnLoad = false;
2528        //	MessageBox.Show("Can't restore default filemanager!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
2529        //}
2530      }
2531    }
2532
2533    private void chkTreeExpand_CheckChanged(object sender, RoutedEventArgs e) {
2534      //TODO: Delete Dead Code!!
2535      if (isOnLoad) return;
2536      var proc = Rename_CheckChanged_Helper();
2537
2538      if (chkTreeExpand.IsChecked == true) {
2539        //int h = (int)WindowsAPI.getWindowId(null, "BetterExplorerOperations");
2540        //int jj = WindowsAPI.sendWindowsStringMessage((int)WindowsAPI.getWindowId(null, "BetterExplorerOperations"), 0, "0x88775");
2541        //proc.WaitForExit();
2542      } else {
2543        //int h = (int)WindowsAPI.getWindowId(null, "BetterExplorerOperations");
2544        //int jj = WindowsAPI.sendWindowsStringMessage((int)WindowsAPI.getWindowId(null, "BetterExplorerOperations"), 0, "0x88776");
2545        //proc.WaitForExit();
2546      }
2547    }
2548
2549    private void btnSetCurrentasStartup_Click(object sender, RoutedEventArgs e) {
2550      backstage.IsOpen = true;
2551      string CurrentLocString = _ShellListView.CurrentFolder.ParsingName;
2552      tcMain.StartUpLocation = CurrentLocString;
2553      btnSetCurrentasStartup.Header = _ShellListView.CurrentFolder.DisplayName;
2554      //btnSetCurrentasStartup.Icon = ShellListView.CurrentFolder.Thumbnail.BitmapSource;
2555
2556      BESettings.StartupLocation = CurrentLocString;
2557      BESettings.SaveSettings();
2558    }
2559
2560    private void chkIsFlyout_CheckChanged(object sender, RoutedEventArgs e) {
2561      if (!isOnLoad) {
2562        BESettings.IsFileOpExEnabled = e.RoutedEvent.Name == "Checked";
2563        BESettings.SaveSettings();
2564      }
2565    }
2566
2567    private void chkIsTerraCopyEnabled_CheckChanged(object sender, RoutedEventArgs e) {
2568      if (!isOnLoad) {
2569        BESettings.IsFileOpExEnabled = e.RoutedEvent.Name == "Checked";
2570        BESettings.SaveSettings();
2571      }
2572    }
2573
2574    private void chkShowCheckBoxes_CheckChanged(object sender, RoutedEventArgs e) {
2575      _ShellListView.ShowCheckboxes = e.RoutedEvent.Name == "Checked";
2576      _ShellListView.RefreshContents();
2577    }
2578
2579    private void chkOverwriteImages_Checked(object sender, RoutedEventArgs e) {
2580      BESettings.OverwriteImageWhileEditing = e.RoutedEvent.Name == "Checked";
2581      BESettings.SaveSettings();
2582    }
2583
2584    private void chkRibbonMinimizedGlass_Click(object sender, RoutedEventArgs e) {
2585      BESettings.IsGlassOnRibonMinimized = chkRibbonMinimizedGlass.IsChecked.Value == true;
2586      BESettings.SaveSettings();
2587
2588      if (!TheRibbon.IsMinimized) {
2589      } else if (chkRibbonMinimizedGlass.IsChecked.Value) {
2590        var p = ShellViewHost.TransformToAncestor(this).Transform(new WIN.Point(0, 0));
2591        this.GlassFrameThickness = new Thickness(8, p.Y, 8, 8);
2592      } else {
2593        var p = backstage.TransformToAncestor(this).Transform(new WIN.Point(0, 0));
2594        this.GlassFrameThickness = new Thickness(8, p.Y + backstage.ActualHeight, 8, 8);
2595      }
2596    }
2597
2598    private void chkLogHistory_CheckChanged(object sender, RoutedEventArgs e) {
2599      BESettings.EnableActionLog = e.RoutedEvent.Name == "Checked";
2600      BESettings.EnableActionLog = e.RoutedEvent.Name == "Checked";
2601      BESettings.SaveSettings();
2602    }
2603
2604    private void btnShowLogs_Click(object sender, RoutedEventArgs e) {
2605      try {
2606        if (!Directory.Exists(logdir)) Directory.CreateDirectory(logdir);
2607        tcMain.NewTab(logdir);
2608        this.backstage.IsOpen = false;
2609      } catch (Exception exe) {
2610        MessageBox.Show("An error occurred while trying to open the logs folder. Please report this issue at http://bugs.gainedge.org/public/betterexplorer. \r\n\r\n Here is some information about the error: \r\n\r\n" + exe.Message + "\r\n\r\n" + exe.ToString(), "Error While Opening Log Folder", MessageBoxButton.OK, MessageBoxImage.Error);
2611      }
2612    }
2613
2614    #endregion
2615
2616    #region Change Pane Visibility
2617
2618    private void btnNavigationPane_CheckChanged(object sender, RoutedEventArgs e) {
2619      if (isOnLoad) {
2620      } else if (e.RoutedEvent.Name == "Checked") {
2621        TreeGrid.ColumnDefinitions[0].Width = new GridLength(200);
2622        BESettings.IsNavigationPaneEnabled = true;
2623        BESettings.SaveSettings();
2624      } else {
2625        TreeGrid.ColumnDefinitions[0].Width = new GridLength(1);
2626        BESettings.IsNavigationPaneEnabled = false;
2627        BESettings.SaveSettings();
2628      }
2629    }
2630
2631    private void btnPreviewPane_CheckChanged(object sender, RoutedEventArgs e) {
2632      if (isOnLoad) {
2633      } else if (e.RoutedEvent.Name == "Checked") {
2634        this.clPreview.Width = new GridLength(BESettings.PreviewPaneWidth);
2635        this.clPreviewSplitter.Width = new GridLength(1);
2636        var selectedItem = _ShellListView.SelectedItems.FirstOrDefault();
2637        if (selectedItem != null && selectedItem.IsFileSystem && _ShellListView.GetSelectedCount() == 1 && !selectedItem.IsFolder) {
2638          this.Previewer.FileName = selectedItem.ParsingName;
2639        }
2640
2641        BESettings.IsPreviewPaneEnabled = true;
2642        BESettings.SaveSettings();
2643      } else {
2644        this.clPreview.Width = new GridLength(0);
2645        this.clPreviewSplitter.Width = new GridLength(0);
2646        this.Previewer.FileName = null;
2647        BESettings.IsPreviewPaneEnabled = false;
2648        BESettings.SaveSettings();
2649      }
2650    }
2651
2652    private void btnInfoPane_CheckChanged(object sender, RoutedEventArgs e) {
2653      if (isOnLoad) {
2654      } else if (e.RoutedEvent.Name == "Checked") {
2655        this.rPreviewPane.Height = new GridLength(BESettings.InfoPaneHeight);
2656        this.rPreviewPaneSplitter.Height = new GridLength(1);
2657        BESettings.IsInfoPaneEnabled = true;
2658        BESettings.SaveSettings();
2659      } else {
2660        this.rPreviewPane.Height = new GridLength(0);
2661        this.rPreviewPaneSplitter.Height = new GridLength(0);
2662        BESettings.IsInfoPaneEnabled = false;
2663        BESettings.SaveSettings();
2664      }
2665    }
2666
2667    #endregion
2668
2669    #region Search
2670
2671    private void edtSearchBox_BeginSearch(object sender, SearchRoutedEventArgs e) => DoSearch();
2672
2673    public void DoSearch() {
2674      try {
2675        if (edtSearchBox.FullSearchTerms != "") this._ShellListView.Navigate_Full(edtSearchBox.FullSearchTerms, true, true);
2676      } catch (Exception ex) {
2677        MessageBox.Show(ex.Message, ex.GetType().ToString(), MessageBoxButton.OK);
2678      }
2679    }
2680
2681    private void btnSearch_Click(object sender, RoutedEventArgs e) => DoSearch();
2682
2683    private void edtSearchBox_RequestCriteriaChange(object sender, SearchRoutedEventArgs e) {
2684      if (e.SearchTerms.StartsWith("author:"))
2685        AuthorToggle_Click(sender, new RoutedEventArgs(e.RoutedEvent));
2686      else if (e.SearchTerms.StartsWith("ext:"))
2687        ToggleButton_Click_1(sender, new RoutedEventArgs(e.RoutedEvent));
2688      else if (e.SearchTerms.StartsWith("subject:"))
2689        SubjectToggle_Click(sender, new RoutedEventArgs(e.RoutedEvent));
2690      else if (e.SearchTerms.StartsWith("size:"))
2691        miCustomSize_Click(sender, new RoutedEventArgs(e.RoutedEvent));
2692      else if (e.SearchTerms.StartsWith("date:"))
2693        dcCustomTime_Click(sender, new RoutedEventArgs(e.RoutedEvent));
2694      else if (e.SearchTerms.StartsWith("modified:"))
2695        dmCustomTime_Click(sender, new RoutedEventArgs(e.RoutedEvent));
2696      else {
2697        var T = "You have discovered an error in this program. Please tell us which filter you were trying to edit and any other details we should know. \r\n\r\nYour filter: ";
2698        MessageBox.Show(T + e.SearchTerms, "Oops! Found a Bug!", MessageBoxButton.OK, MessageBoxImage.Error);
2699      }
2700    }
2701
2702    private void edtSearchBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
2703      ctgSearch.Visibility = Visibility.Visible;
2704      if (!TheRibbon.IsMinimized) TheRibbon.SelectedTabItem = tbSearch;
2705    }
2706
2707    private void edtSearchBox_FiltersCleared(object sender, EventArgs e) {
2708      scSize.IsChecked = false;
2709      ExtToggle.IsChecked = false;
2710      AuthorToggle.IsChecked = false;
2711      SubjectToggle.IsChecked = false;
2712      dcsplit.IsChecked = false;
2713      dmsplit.IsChecked = false;
2714
2715
2716      foreach (var item in scSize.Items.OfType<MenuItem>().Union(dcsplit.Items.OfType<MenuItem>()).Union(dmsplit.Items.OfType<MenuItem>())) {
2717        item.IsChecked = false;
2718      }
2719    }
2720
2721    private void MenuItem_Click_3(object sender, RoutedEventArgs e) {
2722      edtSearchBox.ModifiedCondition = (string)((FrameworkElement)sender).Tag;
2723      dmsplit.IsChecked = true;
2724    }
2725
2726    private void MenuItem_Click_4(object sender, RoutedEventArgs e) {
2727      edtSearchBox.DateCondition = (string)((FrameworkElement)sender).Tag;
2728      dcsplit.IsChecked = true;
2729    }
2730
2731    private void ToggleButton_Click(object sender, RoutedEventArgs e) {
2732      ((Fluent.ToggleButton)sender).IsChecked = true;
2733      edtSearchBox.KindCondition = (string)((FrameworkElement)sender).Tag;
2734      edtSearchBox.Focus();
2735    }
2736
2737    private void MenuItem_Click_5(object sender, RoutedEventArgs e) {
2738      edtSearchBox.SizeCondition = (string)((FrameworkElement)sender).Tag;
2739      scSize.IsChecked = true;
2740    }
2741
2742    private void ToggleButton_Click_1(object sender, RoutedEventArgs e) {
2743      var dat = new StringSearchCriteriaDialog("ext", edtSearchBox.ExtensionCondition, FindResource("btnExtCP") as string);
2744      dat.ShowDialog();
2745      if (dat.Confirm) {
2746        edtSearchBox.ExtensionCondition = "ext:" + dat.textBox1.Text;
2747        ExtToggle.IsChecked = dat.textBox1.Text.Any();
2748      } else {
2749        ExtToggle.IsChecked = Utilities.GetValueOnly("ext", edtSearchBox.ExtensionCondition).Any();
2750      }
2751    }
2752
2753    private void AuthorToggle_Click(object sender, RoutedEventArgs e) {
2754      var dat = new StringSearchCriteriaDialog("author", edtSearchBox.AuthorCondition, FindResource("btnAuthorCP") as string);
2755      dat.ShowDialog();
2756      if (dat.Confirm) {
2757        edtSearchBox.AuthorCondition = "author:" + dat.textBox1.Text;
2758        AuthorToggle.IsChecked = dat.textBox1.Text.Any();
2759      } else {
2760        AuthorToggle.IsChecked = Utilities.GetValueOnly("author", edtSearchBox.AuthorCondition).Any();
2761      }
2762    }
2763
2764    private void SubjectToggle_Click(object sender, RoutedEventArgs e) {
2765      var dat = new StringSearchCriteriaDialog("subject", edtSearchBox.SubjectCondition, FindResource("btnSubjectCP") as string);
2766      dat.ShowDialog();
2767      if (dat.Confirm) {
2768        edtSearchBox.SubjectCondition = "subject:" + dat.textBox1.Text;
2769        SubjectToggle.IsChecked = dat.textBox1.Text.Any();
2770      } else {
2771        SubjectToggle.IsChecked = Utilities.GetValueOnly("subject", edtSearchBox.SubjectCondition).Any();
2772      }
2773    }
2774
2775    private void miCustomSize_Click(object sender, RoutedEventArgs e) {
2776      var dat = new SizeSearchCriteriaDialog();
2777      string sd = Utilities.GetValueOnly("size", edtSearchBox.SizeCondition);
2778      dat.curval.Text = sd;
2779      dat.ShowDialog();
2780
2781      if (dat.Confirm) {
2782        edtSearchBox.SizeCondition = "size:" + dat.GetSizeQuery();
2783        scSize.IsChecked = dat.GetSizeQuery().Any();
2784      } else {
2785        scSize.IsChecked = dat.GetSizeQuery().Length > 5;
2786      }
2787    }
2788
2789    private void dcCustomTime_Click(object sender, RoutedEventArgs e) {
2790      var star = new SDateSearchCriteriaDialog(FindResource("btnODateCCP") as string);
2791
2792      star.DateCriteria = Utilities.GetValueOnly("date", edtSearchBox.DateCondition);
2793      //star.textBlock1.Text = "Set Date Created Filter";
2794      star.ShowDialog();
2795
2796      if (star.Confirm) edtSearchBox.DateCondition = "date:" + star.DateCriteria;
2797      dcsplit.IsChecked = edtSearchBox.UseDateCondition;
2798    }
2799
2800    private void dmCustomTime_Click(object sender, RoutedEventArgs e) {
2801      var star = new SDateSearchCriteriaDialog(FindResource("btnODateModCP") as string);
2802
2803      star.DateCriteria = Utilities.GetValueOnly("modified", edtSearchBox.ModifiedCondition);
2804      //star.textBlock1.Text = "Set Date Modified Filter";
2805      star.ShowDialog();
2806
2807      if (star.Confirm) edtSearchBox.ModifiedCondition = "modified:" + star.DateCriteria;
2808      dmsplit.IsChecked = edtSearchBox.UseModifiedCondition;
2809    }
2810
2811    #endregion
2812
2813    #region AutoSwitch
2814
2815    private void chkFolder_CheckChanged(object sender, RoutedEventArgs e) => BESettings.AutoSwitchFolderTools = e.RoutedEvent.Name == "Checked";
2816    private void chkDrive_CheckChanged(object sender, RoutedEventArgs e) => BESettings.AutoSwitchDriveTools = e.RoutedEvent.Name == "Checked";
2817    private void chkArchive_CheckChanged(object sender, RoutedEventArgs e) => BESettings.AutoSwitchArchiveTools = e.RoutedEvent.Name == "Checked";
2818    private void chkApp_CheckChanged(object sender, RoutedEventArgs e) => BESettings.AutoSwitchApplicationTools = e.RoutedEvent.Name == "Checked";
2819    private void chkImage_CheckChanged(object sender, RoutedEventArgs e) => BESettings.AutoSwitchImageTools = e.RoutedEvent.Name == "Checked";
2820    private void chkLibrary_CheckChanged(object sender, RoutedEventArgs e) => BESettings.AutoSwitchLibraryTools = e.RoutedEvent.Name == "Checked";
2821    private void chkVirtualTools_CheckChanged(object sender, RoutedEventArgs e) => BESettings.AutoSwitchVirtualDriveTools = e.RoutedEvent.Name == "Checked";
2822
2823    #endregion
2824
2825    #region Tabs
2826
2827    private void btnNewTab_Click(object sender, RoutedEventArgs e) => tcMain.NewTab();
2828    private void btnTabClone_Click(object sender, RoutedEventArgs e) => tcMain.CloneTabItem(tcMain.SelectedItem as Wpf.Controls.TabItem);
2829    private void btnTabCloseC_Click(object sender, RoutedEventArgs e) => tcMain.RemoveTabItem(tcMain.SelectedItem as Wpf.Controls.TabItem);
2830    private void RibbonWindow_SizeChanged(object sender, SizeChangedEventArgs e) => (tcMain.SelectedItem as Wpf.Controls.TabItem)?.BringIntoView();
2831    void newt_PreviewMouseDown(object sender, MouseButtonEventArgs e) => tcMain.IsInTabDragDrop = false;
2832    void newt_Leave(object sender, DragEventArgs e) => DropTarget.Create.DragLeave();
2833    void mim_Click(object sender, RoutedEventArgs e) => SetFOperation(((sender as MenuItem).Tag as IListItemEx), OperationType.Move);
2834    void mico_Click(object sender, RoutedEventArgs e) => SetFOperation(((sender as MenuItem).Tag as IListItemEx), OperationType.Copy);
2835
2836    private void btnUndoClose_Click(object sender, RoutedEventArgs e) {
2837      tcMain.ReOpenTab(tcMain.ReopenableTabs[tcMain.ReopenableTabs.Count - 1]);
2838      btnUndoClose.IsEnabled = tcMain.ReopenableTabs.Any();
2839    }
2840
2841    void gli_Click(object sender, NavigationLogEventArgs e) {
2842      tcMain.ReOpenTab(e.NavigationLog);
2843      btnUndoClose.IsEnabled = tcMain.ReopenableTabs.Any();
2844    }
2845
2846    void gli_Click(object sender, Tuple<string> e) {
2847      var list = SaveTabs.LoadTabList($"{BESettings.SavedTabsDirectory}{e.Item1}.txt");
2848      if (list.Count > 0) {
2849        foreach (var tabItem in tcMain.Items.OfType<Wpf.Controls.TabItem>().ToArray()) {
2850          tcMain.RemoveTabItem(tabItem, true, true);
2851        }
2852      }
2853      for (int i = 0; i < list.Count; i++) {
2854        var tabitem = tcMain.NewTab(list[i].ToShellParsingName());
2855        if (i == list.Count - 1)
2856          tcMain.SelectedItem = tabitem;
2857      }
2858    }
2859
2860    private void GoToSearchBox(object sender, ExecutedRoutedEventArgs e) {
2861      edtSearchBox.Focus();
2862      Keyboard.Focus(edtSearchBox);
2863    }
2864    void newt_PreviewMouseMove(object sender, MouseEventArgs e) {
2865      var tabItem = e.Source as Wpf.Controls.TabItem;
2866
2867      if (tabItem == null)
2868        tcMain.IsInTabDragDrop = false;
2869      else if (Mouse.PrimaryDevice.LeftButton == MouseButtonState.Pressed)
2870        DragDrop.DoDragDrop(tabItem, tabItem, DragDropEffects.All);
2871    }
2872    void newt_Drop(object sender, DragEventArgs e) {
2873      e.Handled = true;
2874      var tabItemTarget = e.Source as Wpf.Controls.TabItem;
2875
2876      var tabItemSource = e.Data.GetData(typeof(Wpf.Controls.TabItem)) as Wpf.Controls.TabItem;
2877
2878      if (tabItemSource == null) {
2879        if ((sender as Wpf.Controls.TabItem).ShellObject.IsFileSystem) {
2880          e.Effects = (e.KeyStates & DragDropKeyStates.ControlKey) == DragDropKeyStates.ControlKey ? DragDropEffects.Copy : DragDropEffects.Move;
2881
2882          switch (e.Effects) {
2883            case DragDropEffects.All:
2884              break;
2885            case DragDropEffects.Copy:
2886              this._ShellListView.DoCopy(e.Data, (sender as Wpf.Controls.TabItem).ShellObject);
2887              break;
2888            case DragDropEffects.Link:
2889              break;
2890            case DragDropEffects.Move:
2891              this._ShellListView.DoMove(e.Data, (sender as Wpf.Controls.TabItem).ShellObject);
2892              break;
2893            case DragDropEffects.None:
2894              break;
2895            case DragDropEffects.Scroll:
2896              break;
2897            default:
2898              break;
2899          }
2900        } else {
2901          e.Effects = DragDropEffects.None;
2902        }
2903
2904        WIN.Point pt = e.GetPosition(sender as IInputElement);
2905        var wpt = new BExplorer.Shell.DataObject.Win32Point() { X = (int)pt.X, Y = (int)pt.Y };
2906        DropTarget.Create.Drop((System.Runtime.InteropServices.ComTypes.IDataObject)e.Data, ref wpt, (int)e.Effects);
2907        this._TabDropData = null;
2908      } else if (!tabItemTarget.Equals(tabItemSource)) {
2909        var tabControl = tabItemTarget.Parent as TabControl;
2910        int targetIndex = tabControl.Items.IndexOf(tabItemTarget);
2911
2912        int tabState = tabItemSource == this._CurrentlySelectedItem ? 0 : 1;
2913
2914        tabControl.Items.Remove(tabItemSource);
2915        tabControl.Items.Insert(targetIndex, tabItemSource);
2916        tcMain.IsInTabDragDrop = false;
2917        if (tabState == 1)
2918          tabControl.SelectedItem = this._CurrentlySelectedItem;
2919        else if (tabState == 0)
2920          tabControl.SelectedIndex = targetIndex;
2921
2922        tcMain.IsInTabDragDrop = true;
2923      }
2924      //tcMain.IsSelectionHandled = false;
2925    }
2926
2927    void newt_DragOver(object sender, DragEventArgs e) {
2928      e.Handled = true;
2929
2930      var tabItemSource = e.Data.GetData(typeof(Wpf.Controls.TabItem)) as Wpf.Controls.TabItem;
2931
2932      if ((sender as Wpf.Controls.TabItem).ShellObject.IsFileSystem)
2933        e.Effects = (e.KeyStates & DragDropKeyStates.ControlKey) == DragDropKeyStates.ControlKey ? DragDropEffects.Copy : DragDropEffects.Move;
2934      else if (tabItemSource != null)
2935        e.Effects = DragDropEffects.Move;
2936      else
2937        e.Effects = DragDropEffects.None;
2938
2939      var desc = new BExplorer.Shell.DataObject.DropDescription();
2940
2941      switch (e.Effects) {
2942        case DragDropEffects.Copy:
2943          desc.type = (int)BExplorer.Shell.DataObject.DropImageType.Copy;
2944          desc.szMessage = "Copy To %1";
2945          break;
2946        case DragDropEffects.Move:
2947          desc.type = (int)BExplorer.Shell.DataObject.DropImageType.Move;
2948          desc.szMessage = "Move To %1";
2949          break;
2950        case DragDropEffects.None:
2951          desc.type = (int)BExplorer.Shell.DataObject.DropImageType.None;
2952          desc.szMessage = "Cant drop here!";
2953          break;
2954        default:
2955          desc.type = (int)BExplorer.Shell.DataObject.DropImageType.Invalid;
2956          desc.szMessage = "";
2957          break;
2958      }
2959      desc.szInsert = (sender as Wpf.Controls.TabItem).ShellObject.DisplayName;
2960      ((System.Runtime.InteropServices.ComTypes.IDataObject)e.Data).SetDropDescription(desc);
2961
2962      var ptw = new BExplorer.Shell.DataObject.Win32Point();
2963      GetCursorPos(ref ptw);
2964
2965      if (e.Data.GetType() != typeof(Wpf.Controls.TabItem)) {
2966        var wpt = new BExplorer.Shell.DataObject.Win32Point() { X = ptw.X, Y = ptw.Y };
2967        DropTarget.Create.DragOver(ref wpt, (int)e.Effects);
2968      }
2969    }
2970    System.Runtime.InteropServices.ComTypes.IDataObject _TabDropData;
2971    void newt_DragEnter(object sender, DragEventArgs e) {
2972      e.Handled = true;
2973      this._CurrentlySelectedItem = tcMain.SelectedItem as Wpf.Controls.TabItem;
2974      var tabItem = e.Source as Wpf.Controls.TabItem;
2975      if (tabItem == null) return;
2976
2977      this._TabDropData = (System.Runtime.InteropServices.ComTypes.IDataObject)e.Data;
2978
2979      if ((sender as Wpf.Controls.TabItem).ShellObject.IsFileSystem)
2980        e.Effects = (e.KeyStates & DragDropKeyStates.ControlKey) == DragDropKeyStates.ControlKey ? DragDropEffects.Copy : DragDropEffects.Move;
2981      else
2982        e.Effects = DragDropEffects.None;
2983
2984      var ptw = new BExplorer.Shell.DataObject.Win32Point();
2985      GetCursorPos(ref ptw);
2986      e.Effects = DragDropEffects.None;
2987      var tabItemSource = e.Data.GetData(typeof(Wpf.Controls.TabItem)) as Wpf.Controls.TabItem;
2988
2989      if (tabItemSource == null) {
2990        var wpt = new BExplorer.Shell.DataObject.Win32Point() { X = ptw.X, Y = ptw.Y };
2991        DropTarget.Create.DragEnter(this.Handle, (System.Runtime.InteropServices.ComTypes.IDataObject)e.Data, ref wpt, (int)e.Effects);
2992      } else if (e.Data.GetDataPresent(typeof(Wpf.Controls.TabItem))) {
2993        e.Effects = DragDropEffects.Move;
2994      }
2995    }
2996
2997    #endregion
2998
2999    #region Tab Controls
3000
3001    private void FolderTabs_Placement(object sender, RoutedEventArgs e) {
3002      if (sender == TabbaTop) {
3003        Grid.SetRow(this.tcMain, 3);
3004        divNav.Visibility = Visibility.Hidden;
3005        this.rTabbarTop.Height = new GridLength(25);
3006        this.rTabbarBot.Height = new GridLength(0);
3007        this.tcMain.TabStripPlacement = Dock.Top;
3008      } else {
3009        Grid.SetRow(this.tcMain, 7);
3010        divNav.Visibility = Visibility.Visible;
3011        this.rTabbarTop.Height = new GridLength(0);
3012        this.rTabbarBot.Height = new GridLength(25);
3013        this.tcMain.TabStripPlacement = Dock.Bottom;
3014      }
3015    }
3016
3017    private void miSaveCurTabs_Click(object sender, RoutedEventArgs e) {
3018      var objs = new List<IListItemEx>(from Wpf.Controls.TabItem x in tcMain.Items select x.ShellObject);
3019      String str = Utilities.CombinePaths(objs, "|");
3020      var list = SaveTabs.CreateFromString(str);
3021
3022      var Name = BetterExplorer.Tabs.NameTabList.Open(this);
3023      if (Name == null) return;
3024
3025      if (!Directory.Exists(BESettings.SavedTabsDirectory))
3026        Directory.CreateDirectory(BESettings.SavedTabsDirectory);
3027
3028      SaveTabs.SaveTabList(list, $"{BESettings.SavedTabsDirectory}{Name}.txt");
3029      miTabManager.IsEnabled = true;
3030    }
3031
3032    private void miClearUndoList_Click(object sender, RoutedEventArgs e) {
3033      tcMain.ReopenableTabs.Clear();
3034      btnUndoClose.IsDropDownOpen = false;
3035      btnUndoClose.IsEnabled = false;
3036
3037      foreach (var item in
3038          from Item in this.tcMain.Items.OfType<Wpf.Controls.TabItem>()
3039          from m in Item.mnu.Items.OfType<MenuItem>()
3040          where m.Tag?.ToString() == "UCTI"
3041          select m) {
3042        item.IsEnabled = false;
3043      }
3044    }
3045
3046    private void btnUndoClose_DropDownOpened(object sender, EventArgs e) {
3047      rotGallery.Items.Clear();
3048      foreach (NavigationLog item in tcMain.ReopenableTabs) {
3049        var gli = new UndoCloseGalleryItem();
3050        gli.LoadData(item);
3051        gli.Click += gli_Click;
3052        rotGallery.Items.Add(gli);
3053      }
3054    }
3055
3056    private void rotGallery_SelectionChanged(object sender, SelectionChangedEventArgs e) {
3057      e.Handled = true;
3058      var Item = (e.AddedItems[0] as UndoCloseGalleryItem);
3059      Item?.PerformClickEvent();
3060    }
3061
3062    private void btnChangeTabsFolder_Click(object sender, RoutedEventArgs e) {
3063      var ctf = new FolderSelectDialog();
3064      ctf.Title = "Change Tab Folder";
3065      ctf.InitialDirectory = new DirectoryInfo(BESettings.SavedTabsDirectory).Parent.FullName;
3066      if (ctf.ShowDialog()) {
3067        BESettings.SavedTabsDirectory = ctf.FileName + "\\";
3068        BESettings.SaveSettings();
3069        txtDefSaveTabs.Text = ctf.FileName + "\\";
3070      }
3071    }
3072
3073    private void stGallery_SelectionChanged(object sender, SelectionChangedEventArgs e) {
3074      e.Handled = true;
3075      if (e.AddedItems.Count > 0)
3076        (e.AddedItems[0] as SavedTabsListGalleryItem).PerformClickEvent();
3077    }
3078
3079    private void btnSavedTabs_DropDownOpened(object sender, EventArgs e) {
3080      var o = new List<string>();
3081
3082      if (Directory.Exists(BESettings.SavedTabsDirectory)) {
3083        foreach (string item in Directory.GetFiles(BESettings.SavedTabsDirectory)) {
3084          o.Add(Utilities.RemoveExtensionsFromFile(new ShellItem(item).GetDisplayName(SIGDN.NORMALDISPLAY), item.Substring(item.LastIndexOf("."))));
3085        }
3086      }
3087
3088      stGallery.Items.Clear();
3089      foreach (string item in o) {
3090        var gli = new SavedTabsListGalleryItem(item);
3091        gli.Directory = BESettings.SavedTabsDirectory;
3092        gli.Click += gli_Click;
3093        gli.SetUpTooltip((FindResource("tabTabsCP") as string));
3094        stGallery.Items.Add(gli);
3095      }
3096    }
3097
3098    private void miTabManager_Click(object sender, RoutedEventArgs e) {
3099      string sstdir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\BExplorer_SavedTabs\\";
3100      if (Directory.Exists(sstdir)) new Tabs.TabManager() { MainForm = this }.Show();
3101    }
3102
3103    #endregion
3104
3105    #region Recycle Bin
3106    BackgroundWorker rb = new BackgroundWorker();
3107
3108    public void UpdateRecycleBinInfos() {
3109      var allDrives = Directory.GetLogicalDrives();
3110      int count = 0;// (int)sqrbi.i64NumItems;
3111      long size = 0;// sqrbi.i64Size;
3112                    //Task.Run(() => {
3113      foreach (var drive in allDrives) {
3114        var sqrbi = new BExplorer.Shell.Interop.Shell32.SHQUERYRBINFO() { cbSize = 24 };
3115        //char[] charsToTrim = { Char.Parse(@"\") };
3116        int hresult = BExplorer.Shell.Interop.Shell32.SHQueryRecycleBin(drive, ref sqrbi);
3117        count += (int)sqrbi.i64NumItems;
3118        size += (long)sqrbi.i64Size;
3119      }
3120
3121      Dispatcher.Invoke(DispatcherPriority.Background,
3122              (Action)(() => {
3123                if (count > 0) {
3124                  miRestoreALLRB.Visibility = Visibility.Visible;
3125                  miEmptyRB.Visibility = Visibility.Visible;
3126                  btnRecycleBin.LargeIcon = @"..\Images\RecycleBinFull32.png";
3127                  btnRecycleBin.Icon = @"..\Images\RecycleBinFull16.png";
3128                  btnRecycleBin.UpdateLayout();
3129                  lblRBItems.Visibility = Visibility.Visible;
3130                  lblRBItems.Text = String.Format("{0} Items", count);
3131                  lblRBSize.Text = ShlWapi.StrFormatByteSize(size);
3132                  lblRBSize.Visibility = Visibility.Visible;
3133
3134                } else {
3135                  miEmptyRB.Visibility = Visibility.Collapsed;
3136                  miRestoreALLRB.Visibility = Visibility.Collapsed;
3137                  miRestoreRBItems.Visibility = Visibility.Collapsed;
3138                  btnRecycleBin.LargeIcon = @"..\Images\RecycleBinEmpty32.png";
3139                  btnRecycleBin.Icon = @"..\Images\RecycleBinEmpty16.png";
3140                  lblRBItems.Text = "0 Items";
3141                  lblRBItems.Visibility = Visibility.Collapsed;
3142                  lblRBSize.Text = "0 bytes";
3143                  lblRBSize.Visibility = Visibility.Collapsed;
3144                }
3145              }));
3146    }
3147
3148    private void miEmptyRB_Click(object sender, RoutedEventArgs e) {
3149      BExplorer.Shell.Interop.Shell32.SHEmptyRecycleBin(this.Handle, string.Empty, 0);
3150      UpdateRecycleBinInfos();
3151    }
3152
3153    private void miOpenRB_Click(object sender, RoutedEventArgs e) {
3154      NavigationController(FileSystemListItem.ToFileSystemItem(IntPtr.Zero, ((ShellItem)KnownFolders.RecycleBin).Pidl));
3155    }
3156
3157    private void miRestoreRBItems_Click(object sender, RoutedEventArgs e) {
3158      foreach (var item in _ShellListView.SelectedItems.ToArray()) {
3159        Folder Recycler = new Shell().NameSpace(10);
3160        for (int i = 0; i < Recycler.Items().Count; i++) {
3161          Shell32.FolderItem FI = Recycler.Items().Item(i);
3162          string FileName = Recycler.GetDetailsOf(FI, 0);
3163          if (Path.GetExtension(FileName) == "") FileName += Path.GetExtension(FI.Path);
3164          //Necessary for systems with hidden file extensions.
3165          string FilePath = Recycler.GetDetailsOf(FI, 1);
3166          if (item.FileSystemPath == Path.Combine(FilePath, FileName)) {
3167            DoVerb(FI, "ESTORE");
3168            break;
3169          }
3170        }
3171      }
3172
3173      UpdateRecycleBinInfos();
3174    }
3175
3176    private bool DoVerb(FolderItem Item, string Verb) {
3177      var Found = Item.Verbs().OfType<FolderItemVerb>().FirstOrDefault(FIVerb => FIVerb.Name.ToUpper().Contains(Verb.ToUpper()));
3178      Found?.DoIt();
3179      return Found != null;
3180    }
3181
3182    private void miRestoreALLRB_Click(object sender, RoutedEventArgs e) {
3183      //TODO: Fix Unreachable Code
3184      Folder Recycler = new Shell().NameSpace(10);
3185
3186      for (int i = 0; i < Recycler.Items().Count; i++) {
3187        FolderItem FI = Recycler.Items().Item(i);
3188        DoVerb(FI, "ESTORE");
3189        //TODO: Why do we have a break here
3190        break;
3191      }
3192
3193      UpdateRecycleBinInfos();
3194    }
3195
3196    #endregion
3197
3198    #region Console
3199    private void ConsoleClear_Click(object sender, RoutedEventArgs e) => this.ctrlConsole.ClearConsole();
3200    void cmi_Click(object sender, RoutedEventArgs e) => this.ctrlConsole.EnqueleInput((sender as Fluent.MenuItem).Header.ToString());
3201
3202    private void ctrlConsole_OnConsoleInput(object sender, Tuple<string> args) {
3203      if (args.Item1.Trim().ToLowerInvariant().StartsWith("cd"))
3204        NavigationController(FileSystemListItem.ToFileSystemItem(this._ShellListView.LVHandle, args.Item1.ToLowerInvariant().Replace("cd", String.Empty).Replace("/d", String.Empty).Trim()));
3205
3206      var cmi = new MenuItem() { Header = args.Item1 };
3207      cmi.Click += cmi_Click;
3208      this.btnConsoleHistory.Items.Add(cmi);
3209    }
3210    #endregion
3211
3212    #region EasyAccess
3213
3214    private void btnEasyAccess_DropDownOpened(object sender, EventArgs e) {
3215      if (_ShellListView.GetSelectedCount() == 1 && _ShellListView.GetFirstSelectedItem().IsFolder) {
3216        mnuIncludeInLibrary.Items.Clear();
3217
3218        foreach (ShellItem lib in KnownFolders.Libraries) {
3219          lib.Thumbnail.CurrentSize = new WIN.Size(16, 16);
3220          mnuIncludeInLibrary.Items.Add(Utilities.Build_MenuItem(
3221              lib.DisplayName, ShellLibrary.Load(Path.GetFileNameWithoutExtension(lib.ParsingName), true), lib.Thumbnail.BitmapSource, onClick: mli_Click)
3222          );
3223        }
3224
3225        mnuIncludeInLibrary.Items.Add(new Separator());
3226
3227        var mln = new MenuItem() { Header = "Create new library" };
3228        mln.Click += mln_Click;
3229        mnuIncludeInLibrary.Items.Add(mln);
3230        mnuIncludeInLibrary.IsEnabled = true;
3231      } else {
3232        mnuIncludeInLibrary.IsEnabled = false;
3233      }
3234    }
3235
3236    void mln_Click(object sender, RoutedEventArgs e) {
3237      var lib = _ShellListView.CreateNewLibrary(_ShellListView.GetFirstSelectedItem().DisplayName);
3238      if (_ShellListView.GetFirstSelectedItem().IsFolder)
3239        lib.Add(_ShellListView.GetFirstSelectedItem().ParsingName);
3240    }
3241
3242    void mli_Click(object sender, RoutedEventArgs e) {
3243      var lib = ShellLibrary.Load(Path.GetFileNameWithoutExtension(((ShellItem)(sender as Fluent.MenuItem).Tag).ParsingName), false);
3244      if (_ShellListView.GetFirstSelectedItem().IsFolder)
3245        lib.Add(_ShellListView.GetFirstSelectedItem().ParsingName);
3246    }
3247
3248    #endregion
3249
3250    #region ShellListView
3251
3252    void ShellListView_EndItemLabelEdit(object sender, bool e) {
3253      //_ShellListView.FileNameChangeAttempt(this.txtEditor.Text, e);
3254      //this.Editor.Visibility = WIN.Visibility.Collapsed;
3255      //this.Editor.IsOpen = false;
3256    }
3257
3258    void ShellListView_BeginItemLabelEdit(object sender, RenameEventArgs e) {
3259      //if (this.Editor.IsOpen) return;
3260      //var isSmall = this._ShellListView.IconSize == 16;
3261      //if (isSmall) {
3262      //	this.txtEditor.TextWrapping = TextWrapping.WrapWithOverflow;
3263      //	this.txtEditor.TextAlignment = TextAlignment.Left;
3264      //} else {
3265      //	this.txtEditor.TextWrapping = TextWrapping.Wrap;
3266      //	this.txtEditor.TextAlignment = TextAlignment.Center;
3267      //}
3268
3269      //var itemRect = this._ShellListView.GetItemBounds(e.ItemIndex, 0);
3270      //var itemLabelRect = this._ShellListView.GetItemBounds(e.ItemIndex, 2);
3271      //this.txtEditor.Text = this._ShellListView.Items[e.ItemIndex].DisplayName;
3272      //var point = this.ShellViewHost.PointToScreen(new WIN.Point(isSmall ? itemLabelRect.Left : itemRect.Left, itemLabelRect.Top - (isSmall ? 1 : 0)));
3273      //this.Editor.HorizontalOffset = point.X;
3274      //this.Editor.VerticalOffset = point.Y;
3275
3276      //this.txtEditor.MaxWidth = isSmall ? Double.PositiveInfinity : itemRect.Width;
3277      //this.txtEditor.MaxHeight = isSmall ? itemLabelRect.Height + 2 : Double.PositiveInfinity;
3278
3279      //this.Editor.Width = isSmall ? this.txtEditor.Width : itemRect.Width;
3280      //this.Editor.Height = this.txtEditor.Height + 2;
3281      //this.Editor.Visibility = WIN.Visibility.Visible;
3282      //this.Editor.IsOpen = true;
3283      //this.txtEditor.Focus();
3284
3285      //var isCheckedExtensions = this.chkExtensions.IsChecked;
3286      //if (isCheckedExtensions != null && (isCheckedExtensions.Value & this.txtEditor.Text.Contains(".") && !this._ShellListView.GetFirstSelectedItem().IsFolder)) {
3287      //	var lastIndexOfDot = this.txtEditor.Text.LastIndexOf(".", StringComparison.Ordinal);
3288      //	this.txtEditor.SelectionStart = 0;
3289      //	this.txtEditor.SelectionLength = lastIndexOfDot;
3290      //} else {
3291      //	this.txtEditor.SelectAll();
3292      //}
3293
3294      //Keyboard.Focus(this.txtEditor);
3295    }
3296
3297    void ShellListView_Navigating(object sender, NavigatingEventArgs e) {
3298      if (this._ShellListView.CurrentFolder == null) return;
3299      Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
3300        this.btnCancelNavigation.Visibility = Visibility.Visible;
3301        this.btnGoNavigation.Visibility = Visibility.Collapsed;
3302        this._ProgressTimer.Start();
3303      }));
3304
3305      if (this.bcbc.RootItem.Items.OfType<ShellItem>().Last().IsSearchFolder) {
3306        this.bcbc.RootItem.Items.RemoveAt(this.bcbc.RootItem.Items.Count - 1);
3307      }
3308
3309      var pidl = e.Folder.PIDL.ToString();
3310      this.bcbc.SetPathWithoutNavigate(pidl);
3311
3312      Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
3313        var tab = tcMain.SelectedItem as Wpf.Controls.TabItem;
3314        if (tab != null && this._ShellListView.GetSelectedCount() > 0) {
3315          if (tab.SelectedItems != null)
3316            tab.SelectedItems.AddRange(this._ShellListView.SelectedItems.Select(s => s.ParsingName).ToList());
3317          else
3318            tab.SelectedItems = this._ShellListView.SelectedItems.Select(s => s.ParsingName).ToList();
3319        }
3320
3321        this.Title = "Better Explorer - " + e.Folder.DisplayName;
3322      }));
3323
3324      if (e.Folder.IsSearchFolder) {
3325        Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
3326          var selectedTabItem = tcMain.SelectedItem as Wpf.Controls.TabItem;
3327          if (selectedTabItem != null) {
3328            selectedTabItem.Header = e.Folder.DisplayName;
3329            selectedTabItem.Icon = e.Folder.ThumbnailSource(16, ShellThumbnailFormatOption.IconOnly, ShellThumbnailRetrievalOption.Default);
3330            selectedTabItem.ShellObject = e.Folder;
3331            selectedTabItem.ToolTip = e.Folder.ParsingName.Replace("%20", " ").Replace("%3A", ":").Replace("%5C", @"\");
3332          }
3333        }));
3334      } else {
3335        edtSearchBox.ClearSearchText();
3336      }
3337      this._ShellListView.Focus();
3338    }
3339
3340    void ShellTree_NodeClick(object sender, WIN.Forms.TreeNodeMouseClickEventArgs e) {
3341      if (e.Button == WIN.Forms.MouseButtons.Middle) {
3342        var item = e.Node?.Tag as IListItemEx;
3343        if ((item?.IsLink).Value) {
3344          var shellLink = new ShellLink(item.ParsingName);
3345          item = FileSystemListItem.ToFileSystemItem(this._ShellListView.LVHandle, shellLink.TargetPIDL);
3346          shellLink.Dispose();
3347        }
3348
3349        if (item != null) tcMain.NewTab(item, false);
3350      }
3351    }
3352
3353    WIN.Forms.Timer _keyjumpTimer = new WIN.Forms.Timer();
3354
3355    void ShellListView_KeyJumpTimerDone(object sender, EventArgs e) { _keyjumpTimer?.Stop(); _keyjumpTimer?.Start(); }
3356
3357    void _keyjumpTimer_Tick(object sender, EventArgs e) {
3358      //key jump done
3359      KeyJumpGrid.IsOpen = false;
3360      var timer = sender as WIN.Forms.Timer;
3361      timer?.Stop();
3362    }
3363
3364    void ShellListView_KeyJumpKeyDown(object sender, WIN.Forms.KeyEventArgs e) {
3365      //add key for key jump
3366      KeyJumpGrid.IsOpen = true;
3367      txtKeyJump.Text = _ShellListView.KeyJumpString;
3368    }
3369
3370    void ShellListView_ColumnHeaderRightClick(object sender, WIN.Forms.MouseEventArgs e) {
3371      //is where the more columns menu should be added
3372      chcm.IsOpen = true;
3373    }
3374
3375    void ShellListView_ItemUpdated(object sender, ItemUpdatedEventArgs e) {
3376      Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
3377        if (e.UpdateType == ItemUpdateType.RecycleBin) {
3378          this.UpdateRecycleBinInfos();
3379        }
3380        if (e.UpdateType != ItemUpdateType.Renamed && e.UpdateType != ItemUpdateType.Updated) {
3381          var itemsCount = _ShellListView.Items.Count;
3382          sbiItemsCount.Visibility = itemsCount == 0 ? Visibility.Collapsed : Visibility.Visible;
3383          sbiItemsCount.Content = itemsCount == 1 ? "1 item" : itemsCount + " items";
3384        }
3385        //if (e.UpdateType == ItemUpdateType.Created && this._ShellListView.IsRenameNeeded) {
3386        //	_ShellListView.SelectItemByIndex(e.NewItemIndex, true, true);
3387        //	_ShellListView.RenameSelectedItem();
3388        //	this._ShellListView.IsRenameNeeded = false;
3389        //}
3390        if (e.UpdateType == ItemUpdateType.DriveRemoved || (e.UpdateType == ItemUpdateType.Deleted && e.NewItem.IsFolder)) {
3391          foreach (var tab in this.tcMain.Items.OfType<Wpf.Controls.TabItem>().ToArray().Where(w => w.ShellObject.ParsingName.StartsWith(e.NewItem.ParsingName))) {
3392            this.tcMain.RemoveTabItem(tab, false);
3393          }
3394        }
3395
3396        this._ShellListView.Focus();
3397      }));
3398    }
3399
3400    void ShellListView_SelectionChanged(object sender, EventArgs e) {
3401      if (!this._ShellListView.IsNavigationInProgress && !this._ShellListView.IsSearchNavigating)
3402        SetupUIOnSelectOrNavigate();
3403      if (BESettings.IsInfoPaneEnabled) Task.Run(() => this.DetailsPanel.FillPreviewPane(this._ShellListView));
3404      SetUpStatusBarOnSelectOrNavigate(_ShellListView.GetSelectedCount());
3405    }
3406
3407    #endregion
3408
3409    #region On Navigated
3410
3411    void ShellListView_Navigated(object sender, NavigatedEventArgs e) {
3412      this._ProgressTimer.Stop();
3413      this.btnCancelNavigation.Visibility = Visibility.Collapsed;
3414      this.btnGoNavigation.Visibility = Visibility.Visible;
3415      SetupUIOnSelectOrNavigate();
3416
3417      Dispatcher.BeginInvoke(DispatcherPriority.Background, (ThreadStart)(() => {
3418        SetupColumnsButton();
3419        SetSortingAndGroupingButtons();
3420
3421        if (!tcMain.isGoingBackOrForward) {
3422          var Current = (tcMain.SelectedItem as Wpf.Controls.TabItem).log;
3423          Current.ClearForwardItems();
3424          if (Current.CurrentLocation != e.Folder) Current.CurrentLocation = e.Folder;
3425        }
3426
3427        tcMain.isGoingBackOrForward = false;
3428        SetupUIonNavComplete(e);
3429
3430        if (Settings.BESettings.IsConsoleShown)
3431          ctrlConsole.ChangeFolder(e.Folder.ParsingName, e.Folder.IsFileSystem);
3432      }));
3433
3434      Dispatcher.BeginInvoke(DispatcherPriority.Background, (ThreadStart)(() => {
3435        ConstructMoveToCopyToMenu();
3436        SetUpJumpListOnNavComplete();
3437        SetUpButtonVisibilityOnNavComplete(SetUpNewFolderButtons());
3438      }));
3439
3440      if (BESettings.IsInfoPaneEnabled) {
3441        Task.Run(() => {
3442          this.DetailsPanel.FillPreviewPane(this._ShellListView);
3443        });
3444      }
3445
3446      Dispatcher.Invoke(DispatcherPriority.Render, (Action)(() => {
3447        this._ShellListView.Focus(false, true);
3448        var selectedItem = this.tcMain.SelectedItem as Wpf.Controls.TabItem;
3449        if (selectedItem == null) {
3450          this.tcMain.SelectedItem = this.tcMain.Items.OfType<Wpf.Controls.TabItem>().Last();
3451          selectedItem = this.tcMain.SelectedItem as Wpf.Controls.TabItem;
3452        }
3453        var oldCurrentItem = selectedItem.ShellObject;
3454        var curentFolder = this._ShellListView.CurrentFolder.Clone();
3455        selectedItem.Header = this._ShellListView.CurrentFolder.DisplayName;
3456        selectedItem.Icon = curentFolder.ThumbnailSource(16, ShellThumbnailFormatOption.IconOnly, ShellThumbnailRetrievalOption.Default);
3457        selectedItem.ShellObject = this._ShellListView.CurrentFolder;
3458        if (selectedItem != null) {
3459          var selectedPaths = selectedItem.SelectedItems;
3460          if (selectedPaths?.Count > 0) {
3461            foreach (var path in selectedPaths.ToArray()) {
3462              var sho = this._ShellListView.Items.FirstOrDefault(w => w.ParsingName == path);
3463              if (sho != null) {
3464                var index = sho.ItemIndex;
3465                this._ShellListView.SelectItemByIndex(index, path.Equals(selectedPaths.Last(), StringComparison.InvariantCultureIgnoreCase) || this.IsNeedEnsureVisible);
3466                this.IsNeedEnsureVisible = false;
3467                selectedPaths.Remove(path);
3468              }
3469            }
3470          } else {
3471            var realItem = this._ShellListView.Items.ToArray().FirstOrDefault(w => w.GetUniqueID() == oldCurrentItem.GetUniqueID());
3472            if (realItem != null) {
3473              this._ShellListView.SelectItems(new[] { realItem });
3474            } else {
3475              if (!curentFolder.ParsingName.Contains(oldCurrentItem.ParsingName)) {
3476                var parents = new List<IListItemEx>();
3477                var parent = oldCurrentItem.Parent;
3478                while (parent != null) {
3479                  parents.Add(parent);
3480                  realItem = this._ShellListView.Items.ToArray().FirstOrDefault(w => w.GetUniqueID() == parent.GetUniqueID());
3481                  if (realItem != null) {
3482                    this._ShellListView.SelectItems(new[] { realItem });
3483                    break;
3484                  }
3485                  parent = parent.Parent;
3486                }
3487              }
3488            }
3489
3490            //this._ShellListView.ScrollToTop();
3491          }
3492        }
3493        oldCurrentItem.Dispose();
3494        curentFolder.Dispose();
3495      }));
3496
3497      ////This initially setup the statusbar after program opens
3498      Dispatcher.BeginInvoke(DispatcherPriority.Background, (ThreadStart)(() => {
3499        this.SetUpStatusBarOnSelectOrNavigate(_ShellListView.SelectedItems == null ? 0 : _ShellListView.GetSelectedCount());
3500      }));
3501
3502      //Dispatcher.BeginInvoke(DispatcherPriority.Background, (ThreadStart) (() => {
3503      //    Thread.Sleep(1500);
3504      if (this.bcbc.ProgressValue > 2)
3505        this.bcbc.SetProgressValue(this.bcbc.ProgressMaximum, TimeSpan.FromMilliseconds(750));
3506      else
3507        this.bcbc.SetProgressValue(0, TimeSpan.FromSeconds(0));
3508      this.bcbc.ProgressMaximum = 100;
3509      //this.bcbc.SetProgressValue(0, TimeSpan.FromSeconds(0));
3510      //}));
3511
3512
3513    }
3514
3515    /// <summary>
3516    /// Sets up the UI after the ShellListView has navigated
3517    /// </summary>
3518    /// <param name="e"></param>
3519    private void SetupUIonNavComplete(NavigatedEventArgs e) {
3520      btnSizeChart.IsEnabled = e.Folder.IsFileSystem;
3521      btnAutosizeColls.IsEnabled = _ShellListView.View == ShellViewStyle.Details;
3522
3523      if (e.Folder.ParsingName != KnownFolders.RecycleBin.ParsingName)
3524        miRestoreALLRB.Visibility = Visibility.Collapsed;
3525      else if (_ShellListView.Items.Any())
3526        miRestoreALLRB.Visibility = Visibility.Visible;
3527
3528      bool isFuncAvail;
3529      int selectedItemsCount = _ShellListView.GetSelectedCount();
3530      if (selectedItemsCount == 1) {
3531        isFuncAvail = _ShellListView.GetFirstSelectedItem().IsFileSystem || _ShellListView.CurrentFolder.ParsingName == KnownFolders.Libraries.ParsingName;
3532      } else {
3533        isFuncAvail = true;
3534        if (!(_ShellListView.CurrentFolder.IsFolder && !_ShellListView.CurrentFolder.IsDrive && !_ShellListView.CurrentFolder.IsSearchFolder))
3535          ctgFolderTools.Visibility = Visibility.Collapsed;
3536      }
3537
3538      bool IsChanged = selectedItemsCount > 0;
3539      btnCopy.IsEnabled = IsChanged;
3540      btnCut.IsEnabled = IsChanged;
3541      btnRename.IsEnabled = IsChanged;
3542      btnDelete.IsEnabled = IsChanged && isFuncAvail;
3543      btnCopyto.IsEnabled = IsChanged;
3544      btnMoveto.IsEnabled = IsChanged;
3545      btnSelNone.IsEnabled = IsChanged;
3546
3547      leftNavBut.IsEnabled = (tcMain.SelectedItem as Wpf.Controls.TabItem).log.CanNavigateBackwards;
3548      rightNavBut.IsEnabled = (tcMain.SelectedItem as Wpf.Controls.TabItem).log.CanNavigateForwards;
3549      btnUpLevel.IsEnabled = _ShellListView.CanNavigateParent;
3550    }
3551
3552    /// <summary>
3553    /// Adds the current folder to the recent category of the Better Exlorer's <see cref="JumpList">JumpList</see>
3554    /// </summary>
3555    private void SetUpJumpListOnNavComplete() {
3556      var pidl = IntPtr.Zero;
3557
3558      try {
3559        pidl = this._ShellListView.CurrentFolder.AbsolutePidl;
3560        var sfi = new SHFILEINFO();
3561
3562        if (pidl != IntPtr.Zero && !_ShellListView.CurrentFolder.IsFileSystem) {
3563          var res = BExplorer.Shell.Interop.Shell32.SHGetFileInfo(pidl, 0, out sfi, Marshal.SizeOf(sfi), SHGFI.IconLocation | SHGFI.SmallIcon | SHGFI.PIDL);
3564        }
3565
3566        if (_ShellListView.CurrentFolder.IsFileSystem) {
3567          BExplorer.Shell.Interop.Shell32.SHGetFileInfo(Marshal.StringToHGlobalAuto(_ShellListView.CurrentFolder.ParsingName), 0, out sfi, Marshal.SizeOf(sfi), SHGFI.IconLocation | SHGFI.SmallIcon);
3568        }
3569
3570        JumpList.AddToRecentCategory(new JumpTask() {
3571          ApplicationPath = Process.GetCurrentProcess().MainModule.FileName,
3572          Arguments = "\"" + _ShellListView.CurrentFolder.ParsingName + "\"",
3573          Title = _ShellListView.CurrentFolder.DisplayName,
3574          IconResourcePath = sfi.szDisplayName,
3575          IconResourceIndex = sfi.iIcon
3576        });
3577
3578        AppJL.Apply();
3579      } finally {
3580        if (pidl != IntPtr.Zero) Marshal.FreeCoTaskMem(pidl);
3581      }
3582    }
3583
3584    private bool SetUpNewFolderButtons() {
3585      var currentFolder = FileSystemListItem.ToFileSystemItem(_ShellListView.CurrentFolder.ParentHandle, _ShellListView.CurrentFolder.PIDL);
3586      if (currentFolder.Parent == null) {
3587        return false;
3588      } else if (currentFolder.ParsingName == KnownFolders.Libraries.ParsingName) {
3589        btnCreateFolder.Header = FindResource("btnNewLibraryCP");  //"New Library";
3590        stNewFolder.Title = FindResource("btnNewLibraryCP").ToString();//"New Library";
3591        stNewFolder.Text = "Creates a new library in the current folder.";
3592        stNewFolder.Image = new BitmapImage(new Uri(@"/BetterExplorer;component/Images/newlib32.png", UriKind.Relative));
3593        btnCreateFolder.LargeIcon = @"..\Images\newlib32.png";
3594        btnCreateFolder.Icon = @"..\Images\newlib16.png";
3595
3596        return true;
3597      } else if (currentFolder.IsFileSystem || currentFolder.Parent.ParsingName == KnownFolders.Libraries.ParsingName) {
3598        btnCreateFolder.Header = FindResource("btnNewFolderCP");//"New Folder";
3599        stNewFolder.Title = FindResource("btnNewFolderCP").ToString(); //"New Folder";
3600        stNewFolder.Text = "Creates a new folder in the current folder";
3601        stNewFolder.Image = new BitmapImage(new Uri(@"/BetterExplorer;component/Images/folder_new32.png", UriKind.Relative));
3602        btnCreateFolder.LargeIcon = @"..\Images\folder_new32.png";
3603        btnCreateFolder.Icon = @"..\Images\folder_new16.png";
3604
3605        return false;
3606      } else {
3607        return false;
3608      }
3609    }
3610
3611    private void SetUpButtonVisibilityOnNavComplete(bool isinLibraries) {
3612      if (_ShellListView.CurrentFolder.ParsingName.Contains(KnownFolders.Libraries.ParsingName) && _ShellListView.CurrentFolder.ParsingName != KnownFolders.Libraries.ParsingName) {
3613        if (this._ShellListView.GetSelectedCount() == 1) {
3614          ctgLibraries.Visibility = Visibility.Visible;
3615          SetupLibrariesTab(ShellLibrary.Load(Path.GetFileNameWithoutExtension(_ShellListView.CurrentFolder.ParsingName), false));
3616        }
3617        ctgFolderTools.Visibility = Visibility.Collapsed;
3618        ctgImage.Visibility = Visibility.Collapsed;
3619        ctgArchive.Visibility = Visibility.Collapsed;
3620        ctgVirtualDisk.Visibility = Visibility.Collapsed;
3621        ctgExe.Visibility = Visibility.Collapsed;
3622      } else if (!_ShellListView.CurrentFolder.ParsingName.ToLowerInvariant().EndsWith("library-ms")) {
3623        btnDefSave.Items.Clear();
3624        ctgLibraries.Visibility = Visibility.Collapsed;
3625      }
3626
3627      ctgDrive.Visibility = _ShellListView.CurrentFolder.IsDrive ? Visibility.Visible : Visibility.Collapsed;
3628
3629      if (isinLibraries) {
3630        ctgFolderTools.Visibility = Visibility.Collapsed;
3631      }
3632    }
3633
3634    /// <summary>
3635    /// Navigates to the <paramref name="Destination"/> When Destination != Current Folder
3636    /// </summary>
3637    /// <param name="Destination">The folder you want to navigate to</param>
3638    private void NavigationController(IListItemEx Destination) {
3639      if (!Destination.Equals(this._ShellListView.CurrentFolder)) this._ShellListView.Navigate_Full(Destination, true);
3640    }
3641
3642    private void OnBreadcrumbbarNavigate(IListItemEx Destination) {
3643      this.IsNeedEnsureVisible = true;
3644      this.NavigationController(Destination);
3645    }
3646
3647    /*
3648      private string RemoveLastEmptySeparator(string path) {
3649        path = path.Trim();
3650        if (path.EndsWith(@"\")) path = path.Remove(path.Length - 1, 1);
3651        return path;
3652      }
3653    */
3654
3655    #endregion
3656
3657    #region Misc
3658
3659    public MainWindow() {
3660      this.Badges = this.LoadBadgesData();
3661      this.DataContext = this;
3662
3663      this.LVItemsColorCol = new ObservableCollectionEx<LVItemColor>();
3664      this.CommandBindings.AddRange(new[]
3665      {
3666            new CommandBinding(AppCommands.RoutedNavigateBack, leftNavBut_Click),
3667            new CommandBinding(AppCommands.RoutedNavigateFF, rightNavBut_Click),
3668            new CommandBinding(AppCommands.RoutedNavigateUp, btnUpLevel_Click),
3669            new CommandBinding(AppCommands.RoutedGotoSearch, GoToSearchBox),
3670            new CommandBinding(AppCommands.RoutedNewTab, (sender, e) => tcMain.NewTab()),
3671            new CommandBinding(AppCommands.RoutedEnterInBreadCrumbCombo, (sender, e) => { this._ShellListView.IsFocusAllowed = false; this.bcbc.SetInputState(); }),
3672            new CommandBinding(AppCommands.RoutedChangeTab, (sender, e) => {
3673                int selIndex = tcMain.SelectedIndex == tcMain.Items.Count - 1 ? 0 : tcMain.SelectedIndex + 1;
3674                tcMain.SelectedItem = tcMain.Items[selIndex];
3675            }),
3676            new CommandBinding(AppCommands.RoutedCloseTab, (sender, e) => {
3677                if (tcMain.SelectedIndex == 0 && tcMain.Items.Count == 1) {
3678                    Close();
3679                    return;
3680                }
3681
3682                int CurSelIndex = tcMain.SelectedIndex;
3683                tcMain.SelectedItem = tcMain.SelectedIndex == 0 ? tcMain.Items[1] : tcMain.Items[CurSelIndex - 1];
3684                tcMain.Items.RemoveAt(CurSelIndex);
3685            })
3686        });
3687
3688      // loads current Ribbon color theme
3689      try {
3690        switch (Settings.BESettings.CurrentTheme) {
3691          case "Blue":
3692          case "Silver":
3693          case "Black":
3694          case "Green":
3695            ChangeRibbonTheme(Settings.BESettings.CurrentTheme);
3696            break;
3697          case "Metro":
3698            //ChangeRibbonTheme(Color, true);
3699            //Do nothing since Metro should be already loaded in App.Startup
3700            break;
3701          default:
3702            ChangeRibbonTheme("Blue");
3703            break;
3704        }
3705      } catch (Exception ex) {
3706        MessageBox.Show($"An error occurred while trying to load the theme data from the Registry. \n\r \n\r{ex.Message}\n\r \n\rPlease let us know of this issue at http://bugs.gainedge.org/public/betterexplorer", "RibbonTheme Error - " + ex.ToString());
3707      }
3708
3709      // loads current UI language (uses en-US if default)
3710      try {
3711        //load current UI language in case there is no specified registry value
3712        ((App)Application.Current).SelectCulture(BESettings.Locale, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\BExplorer\\translation.xaml");
3713      } catch (Exception ex) {
3714        MessageBox.Show($"An error occurred while trying to load the locale data from the Registry. \n\r \n\r{ex.Message}\n\r \n\rPlease let us know of this issue at http://bugs.gainedge.org/public/betterexplorer", "Locale Load Error - " + ex);
3715      }
3716
3717      // gets values from registry to be applied after initialization
3718      //bool rtlset = Convert.ToString(rks.GetValue("RTLMode", "notset")) != "notset";
3719
3720      RegistryKey rk = Registry.CurrentUser;
3721      RegistryKey rks = rk.OpenSubKey(@"Software\BExplorer", true);
3722
3723      string RTLMode = Convert.ToString(rks.GetValue("RTLMode", "notset")); //TODO: Find out how to remove this properly, I'm not exactly sure now it works!!
3724
3725      rks.Close();
3726      rk.Close();
3727
3728
3729      //Main Initialization routine
3730      InitializeComponent();
3731
3732      // sets up ComboBox to select the current UI language
3733      this.TranslationComboBox.SelectedItem = this.TranslationComboBox.Items.OfType<TranslationComboBoxItem>().FirstOrDefault(x => x.LocaleCode == BESettings.Locale);
3734
3735      if (RTLMode == "notset") {
3736        RTLMode = (this.TranslationComboBox.SelectedItem as TranslationComboBoxItem).UsesRTL.ToString();
3737      }
3738
3739      this.SearchBarColumn.Width = new GridLength(BESettings.SearchBarWidth);
3740
3741      // prepares RTL mode
3742      FlowDirection = RTLMode.ToLower() == "true" ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
3743
3744      // sets tab bar alignment
3745      if (BESettings.TabBarAlignment == "top")
3746        TabbaTop.IsChecked = true;
3747      else if (BESettings.TabBarAlignment == "bottom")
3748        TabbaBottom.IsChecked = true;
3749      else
3750        TabbaTop.IsChecked = true;
3751
3752      // allows user to change language
3753    }
3754
3755    private void beNotifyIcon_TrayMouseDoubleClick(object sender, RoutedEventArgs e) {
3756      this.Visibility = Visibility.Visible;
3757      if (this.WindowState == WindowState.Minimized) {
3758        User32.ShowWindow(Handle, User32.ShowWindowCommands.Restore);
3759      }
3760
3761      this.Activate();
3762      this.Topmost = true;  // important
3763      this.Topmost = false; // important
3764      this.Focus();         // important
3765    }
3766
3767    void ShellListView_ViewStyleChanged(object sender, BExplorer.Shell.ViewChangedEventArgs e) {
3768      Dispatcher.BeginInvoke(DispatcherPriority.Background,
3769          (ThreadStart)(() => {
3770            this._IsShouldRiseViewChanged = false;
3771            zoomSlider.Value = e.ThumbnailSize;
3772
3773            btnAutosizeColls.IsEnabled = e.CurrentView == ShellViewStyle.Details;
3774            btnSbTiles.IsChecked = e.CurrentView == ShellViewStyle.Tile;
3775
3776            this.ViewGallery.SelectedIndex = -1;
3777
3778            if (e.CurrentView == ShellViewStyle.ExtraLargeIcon && e.ThumbnailSize == 256) {
3779              ViewGallery.SelectedIndex = 0;
3780            } else if (e.CurrentView == ShellViewStyle.LargeIcon && e.ThumbnailSize == 96) {
3781              ViewGallery.SelectedIndex = 1;
3782            } else if (e.CurrentView == ShellViewStyle.Medium && e.ThumbnailSize == 48) {
3783              ViewGallery.SelectedIndex = 2;
3784              btnSbIcons.IsChecked = true;
3785            } else if (e.CurrentView == ShellViewStyle.SmallIcon) {
3786              ViewGallery.SelectedIndex = 3;
3787            } else {
3788              btnSbIcons.IsChecked = false;
3789            }
3790
3791            if (e.CurrentView == ShellViewStyle.List) {
3792              ViewGallery.SelectedIndex = 4;
3793            } else if (e.CurrentView == ShellViewStyle.Details) {
3794              ViewGallery.SelectedIndex = 5;
3795              btnSbDetails.IsChecked = true;
3796            } else {
3797              btnSbDetails.IsChecked = false;
3798            }
3799
3800            if (e.CurrentView == ShellViewStyle.Tile) {
3801              ViewGallery.SelectedIndex = 6;
3802            } else if (e.CurrentView == ShellViewStyle.Content) {
3803              ViewGallery.SelectedIndex = 7;
3804            } else if (e.CurrentView == ShellViewStyle.Thumbstrip) {
3805              ViewGallery.SelectedIndex = 8;
3806            }
3807            this._IsShouldRiseViewChanged = true;
3808          }));
3809    }
3810
3811    private void btnNewItem_DropDownOpened(object sender, EventArgs e) {
3812      var mnu = new ShellContextMenu(this._ShellListView, true);
3813
3814      var controlPos = btnNewItem.TransformToAncestor(Application.Current.MainWindow).Transform(new WIN.Point(0, 0));
3815      var tempPoint = PointToScreen(new WIN.Point(controlPos.X, controlPos.Y));
3816      mnu.ShowContextMenu(new System.Drawing.Point((int)tempPoint.X, (int)tempPoint.Y + (int)btnNewItem.ActualHeight));
3817      btnNewItem.IsDropDownOpen = false;
3818    }
3819
3820    private void mnuPinToStart_Click(object sender, RoutedEventArgs e) {
3821      if (_ShellListView.GetSelectedCount() == 1) {
3822        string loc = KnownFolders.StartMenu.ParsingName + @"\" + _ShellListView.GetFirstSelectedItem().DisplayName + ".lnk";
3823        var link = new ShellLink();
3824        link.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
3825        link.Target = _ShellListView.GetFirstSelectedItem().ParsingName;
3826        link.Save(loc);
3827        link.Dispose();
3828
3829        User32.PinUnpinToStartMenu(loc);
3830      }
3831
3832      if (_ShellListView.GetSelectedCount() == 0) {
3833        string loc = KnownFolders.StartMenu.ParsingName + @"\" + _ShellListView.CurrentFolder.DisplayName + ".lnk";
3834        ShellLink link = new ShellLink();
3835        link.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
3836        link.Target = _ShellListView.CurrentFolder.ParsingName;
3837        link.Save(loc);
3838        link.Dispose();
3839
3840        User32.PinUnpinToStartMenu(loc);
3841      }
3842    }
3843
3844    private void tmpButtonB_Click(object sender, RoutedEventArgs e) => MessageBox.Show("This button currently does nothing");
3845
3846    private void RibbonWindow_PreviewKeyDown(object sender, KeyEventArgs e) {
3847      if (!Keyboard.IsKeyDown(Key.LeftAlt) && (e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Down)) {
3848        e.Handled = true;
3849        var keyText = String.Empty;
3850        switch (e.Key) {
3851          case Key.Left:
3852            keyText = "{LEFT}";
3853            break;
3854          case Key.Right:
3855            keyText = "{RIGHT}";
3856            break;
3857          case Key.Up:
3858            keyText = "{UP}";
3859            break;
3860          case Key.Down:
3861            keyText = "{DOWN}";
3862            break;
3863        }
3864
3865        WIN.Forms.SendKeys.SendWait(keyText);
3866      }
3867    }
3868
3869    private void ToolBar_SizeChanged(object sender, SizeChangedEventArgs e) {
3870      var toolBar = sender as ToolBar;
3871      var overflowGrid = toolBar.Template.FindName("OverflowGrid", toolBar) as FrameworkElement;
3872      if (overflowGrid != null) overflowGrid.Visibility = toolBar.HasOverflowItems ? Visibility.Visible : Visibility.Collapsed;
3873
3874      var mainPanelBorder = toolBar.Template.FindName("MainPanelBorder", toolBar) as FrameworkElement;
3875      if (mainPanelBorder != null) mainPanelBorder.Margin = toolBar.HasOverflowItems ? new Thickness(0, 0, 11, 0) : new Thickness(0);
3876    }
3877
3878    private void btnPaypal_Click(object sender, RoutedEventArgs e) {
3879      string url = "";
3880      string business = "dimitarcenevjp@gmail.com";       // your PayPal email
3881      string description = "Donation%20for%20Better%20Explorer";  // '%20' represents a space. remember HTML!
3882      string country = "US";                    // AU, US, etc.
3883      string currency = "USD";                  // AUD, USD, etc.
3884
3885      url = $"https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business={business}&lc={country}&item_name={description}&currency_code={currency}&bn=PP%2dDonationsBF";
3886
3887      Process.Start(url);
3888    }
3889
3890    private void btnTest_Click(object sender, RoutedEventArgs e) {
3891      /*
3892    We could easily move this to another project and send that method			 
3893    */
3894
3895      //Following could be an example of what the most basic plugin could look like
3896      //We could also separate plugins so they could be enabled WHEN
3897      //Always OR Folder_Selected OR File_Selected 
3898      Action<string, string> pluginExampleActivateBasic = (string pluginPath, string currentFileOrFolder) => Process.Start(pluginPath, currentFileOrFolder);
3899
3900      var Tab = new Fluent.RibbonTabItem() { Header = "Plugins", ToolTip = "Plugins" };
3901      TheRibbon.Tabs.Add(Tab);
3902      var groupBox1 = new RibbonGroupBox() { Header = "Test" };
3903      Tab.Groups.Add(groupBox1);
3904      var XML =
3905                                      @"<Shortcuts>
3906            <Shortcut Name='Test' Path = 'C:\Aaron'/>
3907          </Shortcuts>";
3908
3909      var xDoc = XElement.Parse(XML);
3910      var shortcuts = xDoc.Elements("Shortcut");
3911
3912      var dropDown = new SplitButton();
3913      groupBox1.Items.Add(dropDown);
3914
3915      foreach (var Node in xDoc.Elements("Shortcut")) {
3916        var item = new MenuItem() { Header = Node.Attribute("Name").Value };
3917        item.Click += (x, y) => Process.Start(Node.Attribute("Path").Value);
3918        dropDown.Items.Add(item);
3919      }
3920    }
3921
3922    private void tcMain_Setup(object sender, RoutedEventArgs e) {
3923      tcMain.newt_DragEnter = newt_DragEnter;
3924      tcMain.newt_DragOver = newt_DragOver;
3925      tcMain.newt_Drop = newt_Drop;
3926      tcMain.newt_Leave = newt_Leave;
3927      tcMain.newt_GiveFeedback = newt_GiveFeedback;
3928      tcMain.newt_PreviewMouseMove = newt_PreviewMouseMove;
3929      tcMain.newt_PreviewMouseDown = newt_PreviewMouseDown;
3930      tcMain.ConstructMoveToCopyToMenu += ConstructMoveToCopyToMenu;
3931      tcMain.DefaultTabPath = tcMain.StartUpLocation.ToShellParsingName();
3932      tcMain.PreviewSelectionChanged += tcMain_PreviewSelectionChanged;
3933      //    tcMain.StartUpLocation = Utilities.GetRegistryValue("StartUpLoc", KnownFolders.Libraries.ParsingName).ToString();
3934      //    if (tcMain.StartUpLocation == "") {
3935      //BESettings.StartupLocation = KnownFolders.Libraries.ParsingName;
3936      //BESettings.SaveSettings();
3937      //      tcMain.StartUpLocation = KnownFolders.Libraries.ParsingName;
3938      //    }
3939
3940      tcMain.StartUpLocation = BESettings.StartupLocation;
3941    }
3942
3943    void tcMain_PreviewSelectionChanged(object sender, Wpf.Controls.PreviewSelectionChangedEventArgs e) {
3944      //if (tcMain.IsInTabDragDrop) {
3945      //	e.Cancel = true;
3946      //	return;
3947      //}
3948
3949      //if (e.RemovedItems.Count > 0) {
3950      //	var tab = e.RemovedItems[0] as Wpf.Controls.TabItem;
3951
3952      //	if (tab != null && this._ShellListView.GetSelectedCount() > 0) {
3953      //		tab.SelectedItems = this._ShellListView.SelectedItems.Select(s => s.ParsingName).ToList();
3954      //	}
3955      //}
3956
3957      //if (e.AddedItems.Count == 0 || tcMain.SelectNewTabOnCreate == false) return;
3958      //tcMain.IsInTabDragDrop = true;
3959      //var newTab = e.AddedItems[0] as Wpf.Controls.TabItem;
3960      //if (this._ShellListView.CurrentFolder == null || !this._ShellListView.CurrentFolder.Equals(newTab.ShellObject) && tcMain.CurrentTabItem == null) {
3961      //	SelectTab(newTab);
3962      //} else if (!tcMain.IsSelectionHandled) {
3963      //	SelectTab(newTab);
3964      //	//btnUndoClose
3965      //	btnUndoClose.Items.Clear();
3966      //	foreach (var item in tcMain.ReopenableTabs) {
3967      //		btnUndoClose.Items.Add(item.CurrentLocation);
3968      //	}
3969      //}
3970      ////else if (e.RemovedItems.Count == 0) {
3971      ////	e.Cancel = true;
3972      ////	SelectTab(newTab);
3973      ////	tcMain.SelectedItem = e.AddedItems[0];
3974      ////} else if (e.RemovedItems[0] == tcMain.CurrentTabItem) {
3975      ////	e.Cancel = true;
3976      ////	tcMain.IsSelectionHandled = false;
3977      ////	tcMain.SelectedItem = e.RemovedItems[0];
3978      ////	tcMain.CurrentTabItem = null;
3979      ////}
3980
3981      //tcMain.IsSelectionHandled = true;
3982      //this._ShellListView.Focus();
3983      //this._CurrentlySelectedItem = tcMain.SelectedItem as Wpf.Controls.TabItem;
3984    }
3985
3986    private void newt_GiveFeedback(object sender, GiveFeedbackEventArgs e) {
3987      e.Handled = true;
3988      e.UseDefaultCursors = true;
3989      if (this._TabDropData == null)
3990        return;
3991      var doo = new WIN.Forms.DataObject(this._TabDropData);
3992      if (doo.GetDataPresent("DragWindow")) {
3993        IntPtr hwnd = ShellView.GetIntPtrFromData(doo.GetData("DragWindow"));
3994        User32.PostMessage(hwnd, 0x403, IntPtr.Zero, IntPtr.Zero);
3995      } else {
3996        e.UseDefaultCursors = true;
3997      }
3998
3999      if (ShellView.IsDropDescriptionValid(this._TabDropData)) {
4000        e.UseDefaultCursors = false;
4001        Cursor = Cursors.Arrow;
4002      } else {
4003        e.UseDefaultCursors = true;
4004      }
4005
4006      if (ShellView.IsShowingLayered(doo)) {
4007        e.UseDefaultCursors = false;
4008        Cursor = Cursors.Arrow;
4009      } else {
4010        e.UseDefaultCursors = true;
4011      }
4012    }
4013
4014    private void btnResetLibrary_Click(object sender, RoutedEventArgs e) => WIN.Forms.MessageBox.Show("This does nothing"); //TODO: Add functionality or remove
4015
4016    private void RibbonWindow_Activated(object sender, EventArgs e) {
4017      //tcMain.CurrentTabItem = tcMain.SelectedItem as Wpf.Controls.TabItem;
4018      tcMain.IsSelectionHandled = true;
4019      focusTimer.Start();
4020    }
4021
4022    private void RibbonWindow_StateChanged(object sender, EventArgs e) {
4023      //tcMain.CurrentTabItem = tcMain.SelectedItem as Wpf.Controls.TabItem;
4024      tcMain.IsSelectionHandled = true;
4025      //if (this.WindowState != WindowState.Minimized && this.IsActive) focusTimer.Start();
4026    }
4027
4028    void focusTimer_Tick(object sender, EventArgs e) {
4029      this._ShellListView.Focus();
4030      focusTimer.Stop();
4031    }
4032
4033    private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) {
4034      var badgeIconPath = ((sender as Image)?.Tag as IListItemEx)?.ParsingName;
4035      var selectedItemPath = this._ShellListView.GetFirstSelectedItem().ParsingName;
4036      this.SaveBadgeForItem(selectedItemPath, badgeIconPath);
4037      this.Badges = this.LoadBadgesData();
4038      this._ShellListView.BadgesData = this.Badges;
4039      this._ShellListView.RefreshItem(this._ShellListView.GetFirstSelectedItemIndex(), true);
4040      this.btnBadges.IsDropDownOpen = false;
4041    }
4042
4043    private void SaveBadgeForItem(String itemPath, String badgePath, Boolean isClear = false) {
4044      var m_dbConnection = new System.Data.SQLite.SQLiteConnection("Data Source=" + this._DBPath + ";Version=3;");
4045      m_dbConnection.Open();
4046      if (isClear) {
4047        var command3 = new System.Data.SQLite.SQLiteCommand("DELETE FROM badges WHERE Path=@Path", m_dbConnection);
4048        command3.Parameters.AddWithValue("Path", itemPath);
4049        command3.ExecuteNonQuery();
4050      } else {
4051        var command1 = new System.Data.SQLite.SQLiteCommand("SELECT * FROM badges WHERE Path=@Path", m_dbConnection);
4052        command1.Parameters.AddWithValue("Path", itemPath);
4053        var Reader = command1.ExecuteReader();
4054        var sql = Reader.Read()
4055        ? @"UPDATE badges  SET Collection = @Collection, Badge = @Badge	 WHERE Path = @Path"
4056        : @"INSERT INTO badges (Path, Collection, Badge) VALUES (@Path, @Collection, @Badge)";
4057
4058        var command2 = new System.Data.SQLite.SQLiteCommand(sql, m_dbConnection);
4059        command2.Parameters.AddWithValue("Path", itemPath);
4060        command2.Parameters.AddWithValue("Collection", Path.GetFileName(Path.GetDirectoryName(badgePath)));
4061        command2.Parameters.AddWithValue("Badge", Path.GetFileName(badgePath));
4062        command2.ExecuteNonQuery();
4063        Reader.Close();
4064      }
4065
4066      m_dbConnection.Close();
4067    }
4068
4069    private void MenuItem_Click_2(object sender, RoutedEventArgs e) {
4070      this.SaveBadgeForItem(this._ShellListView.GetFirstSelectedItem().ParsingName, String.Empty, true);
4071      this.Badges = this.LoadBadgesData();
4072      this._ShellListView.BadgesData = this.Badges;
4073      this._ShellListView.RefreshItem(this._ShellListView.GetFirstSelectedItemIndex(), true);
4074    }
4075
4076    private void btnCancel_Click(object sender, RoutedEventArgs e) {
4077      this._ShellListView.CancelNavigation();
4078      this._ProgressTimer.Stop();
4079      this.bcbc.SetProgressValue(this.bcbc.ProgressMaximum, TimeSpan.FromMilliseconds(750));
4080      this.bcbc.ProgressMaximum = 100;
4081      this.btnCancelNavigation.Visibility = Visibility.Collapsed;
4082      this.btnGoNavigation.Visibility = Visibility.Visible;
4083    }
4084
4085    private void btnRefresh_Click(object sender, RoutedEventArgs e) {
4086      _ShellListView.RefreshContents();
4087      SetSortingAndGroupingButtons();
4088      SetupUIOnSelectOrNavigate();
4089    }
4090
4091    void bcbc_OnEditModeToggle(object sender, Odyssey.Controls.EditModeToggleEventArgs e) {
4092      this._ShellListView.IsFocusAllowed = e.IsExit;
4093      if (!e.IsExit) this.bcbc.Focus();
4094    }
4095
4096    private void bcbc_BreadcrumbItemDropDownOpened(object sender, Odyssey.Controls.BreadcrumbItemEventArgs e) {
4097      this._ShellListView.IsFocusAllowed = false;
4098      this.bcbc.Focus();
4099    }
4100
4101    private void bcbc_BreadcrumbItemDropDownClosed(object sender, Odyssey.Controls.BreadcrumbItemEventArgs e) => this._ShellListView.IsFocusAllowed = true;
4102
4103    private void btnOpenWith_DropDownOpened(object sender, EventArgs e) {
4104      var mnu = new ShellContextMenu(this._ShellListView, false);
4105
4106      var controlPos = btnOpenWith.TransformToAncestor(Application.Current.MainWindow).Transform(new WIN.Point(0, 0));
4107      var tempPoint = PointToScreen(new WIN.Point(controlPos.X, controlPos.Y));
4108      mnu.ShowContextMenu(new System.Drawing.Point((int)tempPoint.X, (int)tempPoint.Y + (int)btnOpenWith.ActualHeight), 1);
4109      btnOpenWith.IsDropDownOpen = false;
4110    }
4111
4112    private void btnSort_DropDownOpened(object sender, EventArgs e) {
4113      var button = sender as DropDownButton;
4114      foreach (MenuItem item in button.Items.OfType<MenuItem>()) {
4115        var column = item.Tag as Collumns;
4116        if (column == this._ShellListView.Collumns.FirstOrDefault(w => w.ID == this._ShellListView.LastSortedColumnId)) {
4117          item.IsChecked = true;
4118          break;
4119        }
4120      }
4121      button.Items.OfType<MenuItem>().Last().IsChecked = this._ShellListView.LastSortOrder == WIN.Forms.SortOrder.Descending;
4122      button.Items.OfType<MenuItem>().ToArray()[button.Items.OfType<MenuItem>().Count() - 2].IsChecked = this._ShellListView.LastSortOrder == WIN.Forms.SortOrder.Ascending;
4123    }
4124
4125    private void btnGroup_DropDownOpened(object sender, EventArgs e) {
4126      var button = sender as DropDownButton;
4127      foreach (MenuItem item in button.Items.OfType<MenuItem>()) {
4128        var column = item.Tag as Collumns;
4129        if (column == this._ShellListView.LastGroupCollumn) {
4130          item.IsChecked = true;
4131          break;
4132        }
4133      }
4134      button.Items.OfType<MenuItem>().Last().IsChecked = this._ShellListView.LastGroupOrder == WIN.Forms.SortOrder.Descending;
4135      button.Items.OfType<MenuItem>().ToArray()[button.Items.OfType<MenuItem>().Count() - 2].IsChecked = this._ShellListView.LastGroupOrder == WIN.Forms.SortOrder.Ascending;
4136    }
4137
4138    private void ShellTreeHost_SizeChanged(object sender, SizeChangedEventArgs e) {
4139      this.ShellTree.Refresh();
4140      this._ShellListView.Refresh();
4141    }
4142
4143    private void btnStartPowerShellClick(object sender, RoutedEventArgs e) {
4144      if (ctrlConsole.IsProcessRunning) ctrlConsole.StopProcess();
4145      ctrlConsole.StartPowerShell();
4146    }
4147
4148    private void chkTraditionalNameGrouping_CheckChanged(Object sender, RoutedEventArgs e) {
4149      BESettings.IsTraditionalNameGrouping = e.RoutedEvent.Name == "Checked";
4150      BESettings.SaveSettings();
4151    }
4152
4153    private void btnResetFolderSettings_OnClick(object sender, RoutedEventArgs e) => this._ShellListView.ResetFolderSettings();
4154
4155    #endregion
4156
4157  }
4158}