Пример #1
0
        public RepoObjectsTree()
        {
            _currentToken = _reloadCancellation.Next();
            InitializeComponent();
            InitImageList();
            _txtBranchCriterion = CreateSearchBox();
            branchSearchPanel.Controls.Add(_txtBranchCriterion, 1, 0);

            treeMain.PreviewKeyDown  += OnPreviewKeyDown;
            btnSearch.PreviewKeyDown += OnPreviewKeyDown;
            PreviewKeyDown           += OnPreviewKeyDown;
            InitializeComplete();

            RegisterContextActions();

            InitializeAheadBehindProvider();

            treeMain.ShowNodeToolTips      = true;
            treeMain.HideSelection         = false;
            treeMain.NodeMouseClick       += OnNodeClick;
            treeMain.NodeMouseDoubleClick += OnNodeDoubleClick;

            _doubleClickDecorator = new NativeTreeViewDoubleClickDecorator(treeMain);
            _doubleClickDecorator.BeforeDoubleClickExpandCollapse += BeforeDoubleClickExpandCollapse;

            mnubtnFilterRemoteBranchInRevisionGrid.ToolTipText = _showBranchOnly.Text;
            mnubtnFilterLocalBranchInRevisionGrid.ToolTipText  = _showBranchOnly.Text;

            void InitImageList()
            {
                const int rowPadding = 1; // added to top and bottom, so doubled -- this value is scaled *after*, so consider 96dpi here

                treeMain.ImageList = new ImageList
                {
                    ImageSize = DpiUtil.Scale(new Size(16, 16 + rowPadding + rowPadding)), // Scale ImageSize and images scale automatically
                    Images    =
                    {
                        { nameof(Images.BranchDocument),           Pad(Images.BranchDocument)           },
                        { nameof(Images.Branch),                   Pad(Images.Branch)                   },
                        { nameof(Images.Remote),                   Pad(Images.Remote)                   },
                        { nameof(Images.BitBucket),                Pad(Images.BitBucket)                },
                        { nameof(Images.GitHub),                   Pad(Images.GitHub)                   },
                        { nameof(Images.VisualStudioTeamServices), Pad(Images.VisualStudioTeamServices) },
                        { nameof(Images.BranchLocalRoot),          Pad(Images.BranchLocalRoot)          },
                        { nameof(Images.BranchRemoteRoot),         Pad(Images.BranchRemoteRoot)         },
                        { nameof(Images.BranchRemote),             Pad(Images.BranchRemote)             },
                        { nameof(Images.BranchFolder),             Pad(Images.BranchFolder)             },
                        { nameof(Images.TagHorizontal),            Pad(Images.TagHorizontal)            },
                        { nameof(Images.FolderClosed),             Pad(Images.FolderClosed)             },
                        { nameof(Images.EyeOpened),                Pad(Images.EyeOpened)                },
                        { nameof(Images.EyeClosed),                Pad(Images.EyeClosed)                },
                        { nameof(Images.RemoteEnableAndFetch),     Pad(Images.RemoteEnableAndFetch)     },
                    }
                };
                treeMain.SelectedImageKey = treeMain.ImageKey;

                Image Pad(Image image)
                {
                    var padded = new Bitmap(image.Width, image.Height + rowPadding + rowPadding, PixelFormat.Format32bppArgb);

                    using (var g = Graphics.FromImage(padded))
                    {
                        g.DrawImageUnscaled(image, 0, rowPadding);
                        return(padded);
                    }
                }
            }

            SearchControl <string> CreateSearchBox()
            {
                var search = new SearchControl <string>(SearchForBranch, i => { })
                {
                    Anchor   = AnchorStyles.Left | AnchorStyles.Right,
                    Name     = "txtBranchCritierion",
                    TabIndex = 1
                };

                search.OnTextEntered += () =>
                {
                    OnBranchCriterionChanged(null, null);
                    OnBtnSearchClicked(null, null);
                };
                search.TextChanged    += OnBranchCriterionChanged;
                search.KeyDown        += TxtBranchCriterion_KeyDown;
                search.PreviewKeyDown += OnPreviewKeyDown;
                return(search);

                IEnumerable <string> SearchForBranch(string arg)
                {
                    return(CollectFilterCandidates()
                           .Where(r => r.IndexOf(arg, StringComparison.OrdinalIgnoreCase) != -1));
                }

                IEnumerable <string> CollectFilterCandidates()
                {
                    var list = new List <string>();

                    foreach (TreeNode rootNode in treeMain.Nodes)
                    {
                        CollectFromNodes(rootNode.Nodes);
                    }

                    return(list);

                    void CollectFromNodes(TreeNodeCollection nodes)
                    {
                        foreach (TreeNode node in nodes)
                        {
                            if (node.Tag is BaseBranchNode branch)
                            {
                                if (branch.Nodes.Count == 0)
                                {
                                    list.Add(branch.FullPath);
                                }
                            }
                            else
                            {
                                list.Add(node.Text);
                            }

                            CollectFromNodes(node.Nodes);
                        }
                    }
                }
            }
        }
Пример #2
0
        static void Main(string[] args)
        {
            DesignMode = false;             // The designer doesn't call Main()

            CommandLineArgs = new CommandLineArgs(args);

            try
            {
                DpiUtil.ConfigureProcess();
            }
            catch
            {
                // ignored
            }

            MonoSpaceFont = new FontEx
            {
                Font   = new Font("Courier New", DpiUtil.ScaleIntX(13), GraphicsUnit.Pixel),
                Width  = DpiUtil.ScaleIntX(8),
                Height = DpiUtil.ScaleIntY(16)
            };

            NativeMethods.EnableDebugPrivileges();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;

            Settings = SettingsSerializer.Load();
            Logger   = new GuiLogger();

            if (!NativeMethods.IsUnix() && Settings.RunAsAdmin && !WinUtil.IsAdministrator)
            {
                WinUtil.RunElevated(Process.GetCurrentProcess().MainModule?.FileName, args.Length > 0 ? string.Join(" ", args) : null);
                return;
            }

#if !DEBUG
            try
            {
#endif
            using (var coreFunctions = new CoreFunctionsManager())
            {
                RemoteProcess = new RemoteProcess(coreFunctions);

                MainForm = new MainForm();

                Application.Run(MainForm);

                RemoteProcess.Dispose();
            }
#if !DEBUG
        }

        catch (Exception ex)
        {
            ShowException(ex);
        }
#endif

            SettingsSerializer.Save(Settings);
        }
Пример #3
0
        public static void Main(string[] args)
        {
#if DEBUG
            // Program.DesignMode should not be queried before executing
            // Main (e.g. by a static Control) when running the program
            // normally
            Debug.Assert(!m_bDesignModeQueried);
#endif
            m_bDesignMode = false;             // Designer doesn't call Main method

            m_cmdLineArgs = new CommandLineArgs(args);

            // Before loading the configuration
            string strWaDisable = m_cmdLineArgs[
                AppDefs.CommandLineOptions.WorkaroundDisable];
            if (!string.IsNullOrEmpty(strWaDisable))
            {
                MonoWorkarounds.SetEnabled(strWaDisable, false);
            }

            DpiUtil.ConfigureProcess();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.DoEvents();             // Required

#if DEBUG
            string strInitialWorkDir = WinUtil.GetWorkingDirectory();
#endif

            if (!CommonInit())
            {
                CommonTerminate(); return;
            }

            if (m_appConfig.Application.Start.PluginCacheClearOnce)
            {
                PlgxCache.Clear();
                m_appConfig.Application.Start.PluginCacheClearOnce = false;
                AppConfigSerializer.Save(Program.Config);
            }

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtRegister] != null)
            {
                ShellUtil.RegisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId,
                                            KPRes.FileExtName, WinUtil.GetExecutable(), PwDefs.ShortProductName, false);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtUnregister] != null)
            {
                ShellUtil.UnregisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoad] != null)
            {
                // All important .NET assemblies are in memory now already
                try { SelfTest.Perform(); }
                catch (Exception) { Debug.Assert(false); }
                MainCleanUp();
                return;
            }

            /* if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadRegister] != null)
             * {
             *      string strPreLoadPath = WinUtil.GetExecutable().Trim();
             *      if(strPreLoadPath.StartsWith("\"") == false)
             *              strPreLoadPath = "\"" + strPreLoadPath + "\"";
             *      ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, strPreLoadPath,
             *              @"--" + AppDefs.CommandLineOptions.PreLoad, true);
             *      MainCleanUp();
             *      return;
             * }
             * if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadUnregister] != null)
             * {
             *      ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, string.Empty,
             *              string.Empty, false);
             *      MainCleanUp();
             *      return;
             * } */
            if ((m_cmdLineArgs[AppDefs.CommandLineOptions.Help] != null) ||
                (m_cmdLineArgs[AppDefs.CommandLineOptions.HelpLong] != null))
            {
                AppHelp.ShowHelp(AppDefs.HelpTopics.CommandLine, null);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetUrlOverride] != null)
            {
                Program.Config.Integration.UrlOverride = m_cmdLineArgs[
                    AppDefs.CommandLineOptions.ConfigSetUrlOverride];
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigClearUrlOverride] != null)
            {
                Program.Config.Integration.UrlOverride = string.Empty;
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigGetUrlOverride] != null)
            {
                try
                {
                    string strFileOut = UrlUtil.EnsureTerminatingSeparator(
                        UrlUtil.GetTempPath(), false) + "KeePass_UrlOverride.tmp";
                    string strContent = ("[KeePass]\r\nKeeURLOverride=" +
                                         Program.Config.Integration.UrlOverride + "\r\n");
                    File.WriteAllText(strFileOut, strContent);
                }
                catch (Exception) { Debug.Assert(false); }
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetLanguageFile] != null)
            {
                Program.Config.Application.LanguageFile = m_cmdLineArgs[
                    AppDefs.CommandLineOptions.ConfigSetLanguageFile];
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreate] != null)
            {
                PlgxPlugin.CreateFromCommandLine();
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreateInfo] != null)
            {
                PlgxPlugin.CreateInfoFile(m_cmdLineArgs.FileName);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ShowAssemblyInfo] != null)
            {
                MessageService.ShowInfo(Assembly.GetExecutingAssembly().ToString());
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakeXmlSerializerEx] != null)
            {
                XmlSerializerEx.GenerateSerializers(m_cmdLineArgs);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakeXspFile] != null)
            {
                XspArchive.CreateFile(m_cmdLineArgs.FileName, m_cmdLineArgs["d"]);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.Version] != null)
            {
                Console.WriteLine(PwDefs.ShortProductName + " " + PwDefs.VersionString);
                Console.WriteLine(PwDefs.Copyright);
                MainCleanUp();
                return;
            }
#if DEBUG
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.TestGfx] != null)
            {
                List <Image> lImg = new List <Image>();
                lImg.Add(Properties.Resources.B16x16_Browser);
                lImg.Add(Properties.Resources.B48x48_Keyboard_Layout);
                ImageArchive aHighRes = new ImageArchive();
                aHighRes.Load(Properties.Resources.Images_Client_HighRes);
                lImg.Add(aHighRes.GetForObject("C12_IRKickFlash"));
                if (File.Exists("Test.png"))
                {
                    lImg.Add(Image.FromFile("Test.png"));
                }
                Image img = GfxUtil.ScaleTest(lImg.ToArray());
                img.Save("GfxScaleTest.png", ImageFormat.Png);
                return;
            }
#endif
            // #if (DEBUG && !KeePassLibSD)
            // if(m_cmdLineArgs[AppDefs.CommandLineOptions.MakePopularPasswordTable] != null)
            // {
            //	PopularPasswords.MakeList();
            //	MainCleanUp();
            //	return;
            // }
            // #endif

            try { m_nAppMessage = NativeMethods.RegisterWindowMessage(m_strWndMsgID); }
            catch (Exception) { Debug.Assert(NativeLib.IsUnix()); }

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ExitAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Exit);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoType] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.AutoType);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoTypeSelected] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.AutoTypeSelected);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.OpenEntryUrl] != null)
            {
                string strEntryUuid = m_cmdLineArgs[AppDefs.CommandLineOptions.Uuid];
                if (!string.IsNullOrEmpty(strEntryUuid))
                {
                    IpcParamEx ipUrl = new IpcParamEx(IpcUtilEx.CmdOpenEntryUrl,
                                                      strEntryUuid, null, null, null, null);
                    IpcUtilEx.SendGlobalMessage(ipUrl);
                }

                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.LockAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Lock);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.UnlockAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Unlock);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.IpcEvent] != null)
            {
                string strName = m_cmdLineArgs[AppDefs.CommandLineOptions.IpcEvent];
                if (!string.IsNullOrEmpty(strName))
                {
                    string[] vFlt = KeyUtil.MakeCtxIndependent(args);

                    IpcParamEx ipEvent = new IpcParamEx(IpcUtilEx.CmdIpcEvent, strName,
                                                        CommandLineArgs.SafeSerialize(vFlt), null, null, null);
                    IpcUtilEx.SendGlobalMessage(ipEvent);
                }

                MainCleanUp();
                return;
            }

            // Mutex mSingleLock = TrySingleInstanceLock(AppDefs.MutexName, true);
            bool bSingleLock = GlobalMutexPool.CreateMutex(AppDefs.MutexName, true);
            // if((mSingleLock == null) && m_appConfig.Integration.LimitToSingleInstance)
            if (!bSingleLock && m_appConfig.Integration.LimitToSingleInstance)
            {
                ActivatePreviousInstance(args);
                MainCleanUp();
                return;
            }

            Mutex mGlobalNotify = TryGlobalInstanceNotify(AppDefs.MutexNameGlobal);

            AutoType.InitStatic();

            UserActivityNotifyFilter nfActivity = new UserActivityNotifyFilter();
            Application.AddMessageFilter(nfActivity);

#if DEBUG
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null)
            {
                throw new Exception(AppDefs.CommandLineOptions.DebugThrowException);
            }

            m_formMain = new MainForm();
            Application.Run(m_formMain);
#else
            try
            {
                if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null)
                {
                    throw new Exception(AppDefs.CommandLineOptions.DebugThrowException);
                }

                m_formMain = new MainForm();
                Application.Run(m_formMain);
            }
            catch (Exception exPrg)
            {
                // Catch message box exception;
                // https://sourceforge.net/p/keepass/patches/86/
                try { MessageService.ShowFatal(exPrg); }
                catch (Exception) { Console.Error.WriteLine(exPrg.ToString()); }
            }
#endif

            Application.RemoveMessageFilter(nfActivity);

            Debug.Assert(GlobalWindowManager.WindowCount == 0);
            Debug.Assert(MessageService.CurrentMessageCount == 0);

            MainCleanUp();

#if DEBUG
            string strEndWorkDir = WinUtil.GetWorkingDirectory();
            Debug.Assert(strEndWorkDir.Equals(strInitialWorkDir, StrUtil.CaseIgnoreCmp));
#endif

            if (mGlobalNotify != null)
            {
                GC.KeepAlive(mGlobalNotify);
            }
            // if(mSingleLock != null) { GC.KeepAlive(mSingleLock); }
        }
Пример #4
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            Debug.Assert(m_pgDataSource != null); if (m_pgDataSource == null)
            {
                throw new ArgumentException();
            }

            GlobalWindowManager.AddWindow(this);

            this.Icon = AppIcons.Default;
            CreateDialogBanner();

            List <Image> lTabImg = new List <Image>();

            lTabImg.Add(Properties.Resources.B16x16_XMag);
            lTabImg.Add(Properties.Resources.B16x16_Configure);

            m_ilTabIcons = UIUtil.BuildImageListUnscaled(lTabImg,
                                                         DpiUtil.ScaleIntX(16), DpiUtil.ScaleIntY(16));
            m_tabMain.ImageList = m_ilTabIcons;

            m_tabPreview.ImageIndex    = 0;
            m_tabDataLayout.ImageIndex = 1;

            UIUtil.SetButtonImage(m_btnConfigPrinter,
                                  Properties.Resources.B16x16_EditCopy, true);
            UIUtil.SetButtonImage(m_btnPrintPreview,
                                  Properties.Resources.B16x16_FileQuickPrint, true);

            FontUtil.AssignDefaultBold(m_rbTabular);
            FontUtil.AssignDefaultBold(m_rbDetails);

            Debug.Assert(!m_cmbSpr.Sorted);
            m_cmbSpr.Items.Add(KPRes.ReplaceNo);
            m_cmbSpr.Items.Add(KPRes.Replace + " (" + KPRes.Slow + ")");
            m_cmbSpr.Items.Add(KPRes.BothForms + " (" + KPRes.Slow + ")");
            m_cmbSpr.SelectedIndex = 0;

            if (!m_bPrintMode)
            {
                m_btnOK.Text = KPRes.Export;
            }

            m_bBlockPreviewRefresh = true;
            m_rbTabular.Checked    = true;

            m_cmbSortEntries.Items.Add("(" + KPRes.None + ")");
            m_cmbSortEntries.Items.Add(KPRes.Title);
            m_cmbSortEntries.Items.Add(KPRes.UserName);
            m_cmbSortEntries.Items.Add(KPRes.Password);
            m_cmbSortEntries.Items.Add(KPRes.Url);
            m_cmbSortEntries.Items.Add(KPRes.Notes);

            AceColumnType    colType = AceColumnType.Count;
            List <AceColumn> vCols   = Program.Config.MainWindow.EntryListColumns;

            if ((m_nDefaultSortColumn >= 0) && (m_nDefaultSortColumn < vCols.Count))
            {
                colType = vCols[m_nDefaultSortColumn].Type;
            }

            int nSortSel = 0;

            if (colType == AceColumnType.Title)
            {
                nSortSel = 1;
            }
            else if (colType == AceColumnType.UserName)
            {
                nSortSel = 2;
            }
            else if (colType == AceColumnType.Password)
            {
                nSortSel = 3;
            }
            else if (colType == AceColumnType.Url)
            {
                nSortSel = 4;
            }
            else if (colType == AceColumnType.Notes)
            {
                nSortSel = 5;
            }
            m_cmbSortEntries.SelectedIndex = nSortSel;
            m_bBlockPreviewRefresh         = false;

            if (!m_bPrintMode)            // Export to HTML
            {
                m_btnConfigPrinter.Visible = m_btnPrintPreview.Visible = false;
                m_lblPreviewHint.Visible   = false;
            }

            Program.TempFilesPool.AddWebBrowserPrintContent();

            UpdateHtmlDocument(true);
            UpdateUIState();
        }
Пример #5
0
        protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e)
        {
            ToolStripItem tsi = ((e != null) ? e.Item : null);

            if ((tsi != null) && ((tsi.Owner is ContextMenuStrip) ||
                                  (tsi.OwnerItem != null)) && tsi.Selected)
            {
                Rectangle rect = tsi.ContentRectangle;
                rect.Offset(0, -1);
                rect.Height += 1;

                Color clrStart  = KeePassTsrColorTable.StartGradient(this.ColorTable.MenuItemSelected);
                Color clrEnd    = KeePassTsrColorTable.EndGradient(this.ColorTable.MenuItemSelected);
                Color clrBorder = this.ColorTable.MenuItemBorder;

                if (!tsi.Enabled)
                {
                    Color clrBase = this.ColorTable.MenuStripGradientEnd;
                    clrStart  = UIUtil.ColorTowardsGrayscale(clrStart, clrBase, 0.5);
                    clrEnd    = UIUtil.ColorTowardsGrayscale(clrEnd, clrBase, 0.2);
                    clrBorder = UIUtil.ColorTowardsGrayscale(clrBorder, clrBase, 0.2);
                }

                Graphics g = e.Graphics;
                if (g != null)
                {
                    LinearGradientBrush br = new LinearGradientBrush(rect,
                                                                     clrStart, clrEnd, LinearGradientMode.Vertical);
                    Pen p = new Pen(clrBorder);

                    SmoothingMode smOrg = g.SmoothingMode;
                    g.SmoothingMode = SmoothingMode.HighQuality;

                    GraphicsPath gp = UIUtil.CreateRoundedRectangle(rect.X, rect.Y,
                                                                    rect.Width, rect.Height, DpiUtil.ScaleIntY(2));
                    if (gp != null)
                    {
                        g.FillPath(br, gp);
                        g.DrawPath(p, gp);

                        gp.Dispose();
                    }
                    else                     // Shouldn't ever happen...
                    {
                        Debug.Assert(false);
                        g.FillRectangle(br, rect);
                        g.DrawRectangle(p, rect);
                    }

                    g.SmoothingMode = smOrg;

                    p.Dispose();
                    br.Dispose();
                    return;
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            base.OnRenderMenuItemBackground(e);
        }
Пример #6
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            ++m_uUIAutoBlocked;

            // The password text box should not be focused by default
            // in order to avoid a Caps Lock warning tooltip bug;
            // https://sourceforge.net/p/keepass/bugs/1807/
            Debug.Assert((m_tbPassword.TabIndex >= 2) && !m_tbPassword.Focused);

            GlobalWindowManager.AddWindow(this);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_KGPG_Sign, KPRes.CreateMasterKey,
                                         m_ioInfo.GetDisplayName());
            this.Icon = AppIcons.Default;
            this.Text = KPRes.CreateMasterKey;

            FontUtil.SetDefaultFont(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbKeyFile);
            FontUtil.AssignDefaultBold(m_cbUserAccount);

            UIUtil.ConfigureToolTip(m_ttRect);
            UIUtil.SetToolTip(m_ttRect, m_tbRepeatPassword, KPRes.PasswordRepeatHint, false);
            UIUtil.SetToolTip(m_ttRect, m_btnSaveKeyFile, KPRes.KeyFileCreate, false);
            UIUtil.SetToolTip(m_ttRect, m_btnOpenKeyFile, KPRes.KeyFileUseExisting, false);

            UIUtil.AccSetName(m_tbPassword, m_cbPassword);
            UIUtil.AccSetName(m_cmbKeyFile, m_cbKeyFile);
            UIUtil.AccSetName(m_picKeyFileWarning, KPRes.Warning);
            UIUtil.AccSetName(m_picAccWarning, KPRes.Warning);

            Debug.Assert(!m_lblIntro.AutoSize);             // For RTL support
            if (!m_bCreatingNew)
            {
                m_lblIntro.Text = KPRes.ChangeMasterKeyIntroShort;
            }

            m_cbPassword.Checked = true;
            m_icgPassword.Attach(m_tbPassword, m_cbHidePassword, m_lblRepeatPassword,
                                 m_tbRepeatPassword, m_lblEstimatedQuality, m_pbPasswordQuality,
                                 m_lblQualityInfo, m_ttRect, this, true, m_bSecureDesktop);

            Debug.Assert(!m_cmbKeyFile.Sorted);
            m_cmbKeyFile.Items.Add(KPRes.NoKeyFileSpecifiedMeta);
            m_cmbKeyFile.SelectedIndex = 0;

            foreach (KeyProvider kp in Program.KeyProviderPool)
            {
                m_cmbKeyFile.Items.Add(kp.Name);
            }

            m_imgKeyFileWarning = UIUtil.IconToBitmap(SystemIcons.Warning,
                                                      DpiUtil.ScaleIntX(16), DpiUtil.ScaleIntY(16));
            m_imgAccWarning           = (Image)m_imgKeyFileWarning.Clone();
            m_picKeyFileWarning.Image = m_imgKeyFileWarning;
            m_picAccWarning.Image     = m_imgAccWarning;

            UIUtil.ApplyKeyUIFlags(Program.Config.UI.KeyCreationFlags,
                                   m_cbPassword, m_cbKeyFile, m_cbUserAccount, m_cbHidePassword);

            if (!m_cbKeyFile.Enabled && !m_cbKeyFile.Checked)
            {
                UIUtil.SetEnabledFast(false, m_lblKeyFileInfo, m_lblKeyFileWarning);
            }

            if (WinUtil.IsWindows9x || NativeLib.IsUnix() ||
                (!m_cbUserAccount.Enabled && !m_cbUserAccount.Checked))
            {
                UIUtil.SetChecked(m_cbUserAccount, false);
                UIUtil.SetEnabledFast(false, m_cbUserAccount, m_lblWindowsAccDesc,
                                      m_lblWindowsAccDesc2);
            }

            m_cbExpert.Checked = (m_cbKeyFile.Checked || m_cbUserAccount.Checked);

            --m_uUIAutoBlocked;
            UpdateUIState();
            // UIUtil.SetFocus(m_tbPassword, this); // See OnFormShown
        }
Пример #7
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            GlobalWindowManager.AddWindow(this, this);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_Keyboard_Layout,
                                         KPRes.SelectLanguage, KPRes.SelectLanguageDesc);
            this.Icon = AppIcons.Default;
            this.Text = KPRes.SelectLanguage;

            UIUtil.SetExplorerTheme(m_lvLanguages, true);

            List <Image> lImg = new List <Image>();

            lImg.Add(Properties.Resources.B16x16_Browser);

            m_ilIcons = UIUtil.BuildImageListUnscaled(lImg,
                                                      DpiUtil.ScaleIntX(16), DpiUtil.ScaleIntY(16));
            m_lvLanguages.SmallImageList = m_ilIcons;

            m_lvLanguages.Columns.Add(KPRes.InstalledLanguages);
            m_lvLanguages.Columns.Add(KPRes.Version);
            m_lvLanguages.Columns.Add(KPRes.Author);
            m_lvLanguages.Columns.Add(KPRes.Contact);
            m_lvLanguages.Columns.Add(KPRes.File);

            KPTranslation trlEng = new KPTranslation();

            trlEng.Properties.NameEnglish        = "English";
            trlEng.Properties.NameNative         = "English";
            trlEng.Properties.ApplicationVersion = PwDefs.VersionString;
            trlEng.Properties.AuthorName         = AppDefs.DefaultTrlAuthor;
            trlEng.Properties.AuthorContact      = AppDefs.DefaultTrlContact;

            string strDirA    = AceApplication.GetLanguagesDir(AceDir.App, false);
            string strDirASep = UrlUtil.EnsureTerminatingSeparator(strDirA, false);
            string strDirU    = AceApplication.GetLanguagesDir(AceDir.User, false);

            List <KeyValuePair <string, KPTranslation> > lTrls =
                new List <KeyValuePair <string, KPTranslation> >();

            lTrls.Add(new KeyValuePair <string, KPTranslation>(string.Empty, trlEng));
            AddTranslations(strDirA, lTrls);
            if (WinUtil.IsAppX)
            {
                AddTranslations(strDirU, lTrls);
            }
            lTrls.Sort(LanguageForm.CompareTrlItems);

            foreach (KeyValuePair <string, KPTranslation> kvp in lTrls)
            {
                KPTranslationProperties p = kvp.Value.Properties;
                string strName            = p.NameEnglish + " (" + p.NameNative + ")";
                bool   bBuiltIn           = ((kvp.Key.Length == 0) || (WinUtil.IsAppX &&
                                                                       kvp.Key.StartsWith(strDirASep, StrUtil.CaseIgnoreCmp)));

                ListViewItem lvi = m_lvLanguages.Items.Add(strName, 0);
                lvi.SubItems.Add(p.ApplicationVersion);
                lvi.SubItems.Add(p.AuthorName);
                lvi.SubItems.Add(p.AuthorContact);
                lvi.SubItems.Add(bBuiltIn ? KPRes.BuiltInU : kvp.Key);
                lvi.Tag = kvp.Key;

                // try
                // {
                //	string nl = MessageService.NewLine;
                //	lvi.ToolTipText = strName + " " + p.ApplicationVersion + nl +
                //		p.AuthorName + nl + p.AuthorContact + nl + nl + kvp.Key;
                // }
                // catch(Exception) { Debug.Assert(false); } // Too long?

                // if(kvp.Key.Equals(Program.Config.Application.GetLanguageFilePath(),
                //	StrUtil.CaseIgnoreCmp))
                //	UIUtil.SetFocusedItem(m_lvLanguages, lvi, true);
            }

            UIUtil.ResizeColumns(m_lvLanguages, new int[] { 5, 2, 5, 5, 3 }, true);
            UIUtil.SetFocus(m_lvLanguages, this);
        }
Пример #8
0
 public bool Equals(IntPtr dpiContext)
 {
     return(DpiUtil.AreDpiAwarenessContextsEqual(this.DangerousGetHandle(), dpiContext));
 }
Пример #9
0
        public RepoObjectsTree()
        {
            Disposed += (s, e) => _selectionCancellationTokenSequence.Dispose();

            InitializeComponent();
            InitImageList();
            _txtBranchCriterion = CreateSearchBox();
            branchSearchPanel.Controls.Add(_txtBranchCriterion, 1, 0);

            treeMain.PreviewKeyDown  += OnPreviewKeyDown;
            btnSearch.PreviewKeyDown += OnPreviewKeyDown;
            PreviewKeyDown           += OnPreviewKeyDown;

            mnubtnCollapseAll.AdaptImageLightness();
            tsbCollapseAll.AdaptImageLightness();
            tsbShowBranches.AdaptImageLightness();
            tsbShowRemotes.AdaptImageLightness();
            tsbShowTags.AdaptImageLightness();
            tsbShowSubmodules.AdaptImageLightness();
            mnubtnExpandAll.AdaptImageLightness();
            mnubtnFetchAllBranchesFromARemote.AdaptImageLightness();
            mnuBtnPruneAllBranchesFromARemote.AdaptImageLightness();
            mnuBtnFetchAllRemotes.AdaptImageLightness();
            mnuBtnPruneAllRemotes.AdaptImageLightness();
            mnubtnFetchCreateBranch.AdaptImageLightness();
            mnubtnPullFromRemoteBranch.AdaptImageLightness();
            InitializeComplete();

            RegisterContextActions();

            treeMain.ShowNodeToolTips = true;
            treeMain.HideSelection    = false;

            toolTip.SetToolTip(btnSearch, _searchTooltip.Text);
            tsbCollapseAll.ToolTipText = mnubtnCollapseAll.ToolTipText;

            tsbShowBranches.Checked   = AppSettings.RepoObjectsTreeShowBranches;
            tsbShowRemotes.Checked    = AppSettings.RepoObjectsTreeShowRemotes;
            tsbShowTags.Checked       = AppSettings.RepoObjectsTreeShowTags;
            tsbShowSubmodules.Checked = AppSettings.RepoObjectsTreeShowSubmodules;

            _doubleClickDecorator = new NativeTreeViewDoubleClickDecorator(treeMain);
            _doubleClickDecorator.BeforeDoubleClickExpandCollapse += BeforeDoubleClickExpandCollapse;

            _explorerNavigationDecorator              = new NativeTreeViewExplorerNavigationDecorator(treeMain);
            _explorerNavigationDecorator.AfterSelect += OnNodeSelected;

            treeMain.NodeMouseClick       += OnNodeClick;
            treeMain.NodeMouseDoubleClick += OnNodeDoubleClick;

            mnubtnFilterRemoteBranchInRevisionGrid.ToolTipText = _showBranchOnly.Text;
            mnubtnFilterLocalBranchInRevisionGrid.ToolTipText  = _showBranchOnly.Text;

            return;

            void InitImageList()
            {
                const int rowPadding = 1; // added to top and bottom, so doubled -- this value is scaled *after*, so consider 96dpi here

                treeMain.ImageList = new ImageList
                {
                    ColorDepth = ColorDepth.Depth32Bit,
                    ImageSize  = DpiUtil.Scale(new Size(16, 16 + rowPadding + rowPadding)), // Scale ImageSize and images scale automatically
                    Images     =
                    {
                        { nameof(Images.ArrowUp),                        Pad(Images.ArrowUp)                        },
                        { nameof(Images.ArrowDown),                      Pad(Images.ArrowDown)                      },
                        { nameof(Images.FolderClosed),                   Pad(Images.FolderClosed)                   },
                        { nameof(Images.BranchLocal),                    Pad(Images.BranchLocal)                    },
                        { nameof(Images.BranchLocalMerged),              Pad(Images.BranchLocalMerged)              },
                        { nameof(Images.Branch),                         Pad(Images.Branch.AdaptLightness())        },
                        { nameof(Images.Remote),                         Pad(Images.Remote)                         },
                        { nameof(Images.BitBucket),                      Pad(Images.BitBucket)                      },
                        { nameof(Images.GitHub),                         Pad(Images.GitHub)                         },
                        { nameof(Images.VisualStudioTeamServices),       Pad(Images.VisualStudioTeamServices)       },
                        { nameof(Images.BranchLocalRoot),                Pad(Images.BranchLocalRoot)                },
                        { nameof(Images.BranchRemoteRoot),               Pad(Images.BranchRemoteRoot)               },
                        { nameof(Images.BranchRemote),                   Pad(Images.BranchRemote)                   },
                        { nameof(Images.BranchRemoteMerged),             Pad(Images.BranchRemoteMerged)             },
                        { nameof(Images.BranchFolder),                   Pad(Images.BranchFolder)                   },
                        { nameof(Images.TagHorizontal),                  Pad(Images.TagHorizontal)                  },
                        { nameof(Images.EyeOpened),                      Pad(Images.EyeOpened)                      },
                        { nameof(Images.EyeClosed),                      Pad(Images.EyeClosed)                      },
                        { nameof(Images.RemoteEnableAndFetch),           Pad(Images.RemoteEnableAndFetch)           },
                        { nameof(Images.FileStatusModified),             Pad(Images.FileStatusModified)             },
                        { nameof(Images.FolderSubmodule),                Pad(Images.FolderSubmodule)                },
                        { nameof(Images.SubmoduleDirty),                 Pad(Images.SubmoduleDirty)                 },
                        { nameof(Images.SubmoduleRevisionUp),            Pad(Images.SubmoduleRevisionUp)            },
                        { nameof(Images.SubmoduleRevisionDown),          Pad(Images.SubmoduleRevisionDown)          },
                        { nameof(Images.SubmoduleRevisionSemiUp),        Pad(Images.SubmoduleRevisionSemiUp)        },
                        { nameof(Images.SubmoduleRevisionSemiDown),      Pad(Images.SubmoduleRevisionSemiDown)      },
                        { nameof(Images.SubmoduleRevisionUpDirty),       Pad(Images.SubmoduleRevisionUpDirty)       },
                        { nameof(Images.SubmoduleRevisionDownDirty),     Pad(Images.SubmoduleRevisionDownDirty)     },
                        { nameof(Images.SubmoduleRevisionSemiUpDirty),   Pad(Images.SubmoduleRevisionSemiUpDirty)   },
                        { nameof(Images.SubmoduleRevisionSemiDownDirty), Pad(Images.SubmoduleRevisionSemiDownDirty) },
                    }
                };
                treeMain.SelectedImageKey = treeMain.ImageKey;

                Image Pad(Image image)
                {
                    var padded = new Bitmap(image.Width, image.Height + rowPadding + rowPadding, PixelFormat.Format32bppArgb);

                    using (var g = Graphics.FromImage(padded))
                    {
                        g.DrawImageUnscaled(image, 0, rowPadding);
                        return(padded);
                    }
                }
            }

            SearchControl <string> CreateSearchBox()
            {
                var search = new SearchControl <string>(SearchForBranch, i => { })
                {
                    Anchor   = AnchorStyles.Left | AnchorStyles.Right,
                    Name     = "txtBranchCritierion",
                    TabIndex = 1
                };

                search.OnTextEntered += () =>
                {
                    OnBranchCriterionChanged(null, null);
                    OnBtnSearchClicked(null, null);
                };
                search.TextChanged    += OnBranchCriterionChanged;
                search.KeyDown        += TxtBranchCriterion_KeyDown;
                search.PreviewKeyDown += OnPreviewKeyDown;

                search.SearchBoxBorderStyle        = BorderStyle.FixedSingle;
                search.SearchBoxBorderDefaultColor = Color.LightGray.AdaptBackColor();
                search.SearchBoxBorderHoveredColor = SystemColors.Highlight.AdaptBackColor();
                search.SearchBoxBorderFocusedColor = SystemColors.HotTrack.AdaptBackColor();

                return(search);

                IEnumerable <string> SearchForBranch(string arg)
                {
                    return(CollectFilterCandidates()
                           .Where(r => r.IndexOf(arg, StringComparison.OrdinalIgnoreCase) != -1));
                }

                IEnumerable <string> CollectFilterCandidates()
                {
                    var list = new List <string>();

                    foreach (TreeNode rootNode in treeMain.Nodes)
                    {
                        CollectFromNodes(rootNode.Nodes);
                    }

                    return(list);

                    void CollectFromNodes(TreeNodeCollection nodes)
                    {
                        foreach (TreeNode node in nodes)
                        {
                            if (node.Tag is BaseBranchNode branch)
                            {
                                if (branch.Nodes.Count == 0)
                                {
                                    list.Add(branch.FullPath);
                                }
                            }
                            else
                            {
                                list.Add(node.Text);
                            }

                            CollectFromNodes(node.Nodes);
                        }
                    }
                }
            }
        }
Пример #10
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            GlobalWindowManager.AddWindow(this);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_KGPG_Sign, KPRes.CreateMasterKey,
                                         m_ioInfo.GetDisplayName());
            this.Icon = AppIcons.Default;
            this.Text = KPRes.CreateMasterKey;

            FontUtil.SetDefaultFont(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbKeyFile);
            FontUtil.AssignDefaultBold(m_cbUserAccount);

            using (Bitmap bmp = SystemIcons.Warning.ToBitmap())
            {
                m_imgAccWarning = GfxUtil.ScaleImage(bmp, DpiUtil.ScaleIntX(16),
                                                     DpiUtil.ScaleIntY(16), ScaleTransformFlags.UIIcon);
                m_imgKeyFileWarning = (Image)m_imgAccWarning.Clone();
            }
            m_picKeyFileWarning.Image = m_imgKeyFileWarning;
            m_picAccWarning.Image     = m_imgAccWarning;

            UIUtil.ConfigureToolTip(m_ttRect);
            // m_ttRect.SetToolTip(m_cbHidePassword, KPRes.TogglePasswordAsterisks);
            m_ttRect.SetToolTip(m_btnSaveKeyFile, KPRes.KeyFileCreate);
            m_ttRect.SetToolTip(m_btnOpenKeyFile, KPRes.KeyFileUseExisting);
            m_ttRect.SetToolTip(m_tbRepeatPassword, KPRes.PasswordRepeatHint);

            Debug.Assert(!m_lblIntro.AutoSize);             // For RTL support
            if (!m_bCreatingNew)
            {
                m_lblIntro.Text = KPRes.ChangeMasterKeyIntroShort;
            }

            m_icgPassword.Attach(m_tbPassword, m_cbHidePassword, m_lblRepeatPassword,
                                 m_tbRepeatPassword, m_lblEstimatedQuality, m_pbPasswordQuality,
                                 m_lblQualityInfo, m_ttRect, this, true, false);

            m_cmbKeyFile.Items.Add(KPRes.NoKeyFileSpecifiedMeta);
            foreach (KeyProvider prov in Program.KeyProviderPool)
            {
                m_cmbKeyFile.Items.Add(prov.Name);
            }

            m_cmbKeyFile.SelectedIndex = 0;

            m_cbPassword.Checked = true;
            UIUtil.ApplyKeyUIFlags(Program.Config.UI.KeyCreationFlags,
                                   m_cbPassword, m_cbKeyFile, m_cbUserAccount, m_cbHidePassword);

            if (WinUtil.IsWindows9x || NativeLib.IsUnix())
            {
                UIUtil.SetChecked(m_cbUserAccount, false);
                UIUtil.SetEnabled(m_cbUserAccount, false);
                UIUtil.SetEnabled(m_lblWindowsAccDesc, false);
                UIUtil.SetEnabled(m_lblWindowsAccDesc2, false);
            }

            CustomizeForScreenReader();
            EnableUserControls();
            // UIUtil.SetFocus(m_tbPassword, this); // See OnFormShown
        }
Пример #11
0
		private void OnFormLoad(object sender, EventArgs e)
		{
			Debug.Assert((m_pwDatabaseInfo != null) || (m_pgRootInfo != null));
			if((m_pwDatabaseInfo == null) && (m_pgRootInfo == null))
				throw new InvalidOperationException();

			GlobalWindowManager.AddWindow(this);

			string strWndTitle = (m_bExport ? KPRes.ExportFileTitle : KPRes.ImportFileTitle);
			string strWndDesc = (m_bExport ? KPRes.ExportFileDesc : KPRes.ImportFileDesc);
			Bitmap bmpBanner = (m_bExport ? Properties.Resources.B48x48_Folder_Txt :
				Properties.Resources.B48x48_Folder_Download);
			BannerFactory.CreateBannerEx(this, m_bannerImage,
				bmpBanner, strWndTitle, strWndDesc);
			this.Icon = Properties.Resources.KeePass;

			this.Text = strWndTitle;

			if(m_bExport)
			{
				m_lblFile.Text = KPRes.ExportToPrompt;
				UIUtil.SetButtonImage(m_btnSelFile,
					Properties.Resources.B16x16_FileSaveAs, false);

				m_lnkFileFormats.Enabled = false;
				m_lnkFileFormats.Visible = false;
			}
			else // Import mode
			{
				m_lblFile.Text = KPRes.ImportFilesPrompt;
				UIUtil.SetButtonImage(m_btnSelFile,
					Properties.Resources.B16x16_Folder_Yellow_Open, false);
			}

			m_lvFormats.ShowGroups = true;

			int w = m_lvFormats.ClientSize.Width - UIUtil.GetVScrollBarWidth();
			m_lvFormats.Columns.Add(string.Empty, w - 1);

			m_ilFormats = new ImageList();
			m_ilFormats.ColorDepth = ColorDepth.Depth32Bit;
			m_ilFormats.ImageSize = new Size(DpiUtil.ScaleIntX(16),
				DpiUtil.ScaleIntY(16));

			Dictionary<string, FormatGroupEx> dictGroups =
				new Dictionary<string, FormatGroupEx>();

			foreach(FileFormatProvider f in Program.FileFormatPool)
			{
				if(m_bExport && (f.SupportsExport == false)) continue;
				if((m_bExport == false) && (f.SupportsImport == false)) continue;

				string strDisplayName = f.DisplayName;
				if((strDisplayName == null) || (strDisplayName.Length == 0))
					continue;

				string strAppGroup = f.ApplicationGroup;
				if((strAppGroup == null) || (strAppGroup.Length == 0))
					strAppGroup = KPRes.General;

				FormatGroupEx grp;
				if(!dictGroups.TryGetValue(strAppGroup, out grp))
				{
					grp = new FormatGroupEx(strAppGroup);
					dictGroups.Add(strAppGroup, grp);
				}

				ListViewItem lvi = new ListViewItem(strDisplayName);
				lvi.Group = grp.Group;
				lvi.Tag = f;

				Image imgSmallIcon = f.SmallIcon;
				if(imgSmallIcon == null)
					imgSmallIcon = Properties.Resources.B16x16_Folder_Inbox;

				m_ilFormats.Images.Add(imgSmallIcon);
				lvi.ImageIndex = m_ilFormats.Images.Count - 1;

				grp.Items.Add(lvi);
			}

			foreach(FormatGroupEx formatGroup in dictGroups.Values)
			{
				m_lvFormats.Groups.Add(formatGroup.Group);
				foreach(ListViewItem lvi in formatGroup.Items)
					m_lvFormats.Items.Add(lvi);
			}

			m_lvFormats.SmallImageList = m_ilFormats;

			CustomizeForScreenReader();
			UpdateUIState();
		}
Пример #12
0
        private void OnClickFindEntry(object sender, EventArgs e)
        {
            string   f  = (sender as ToolStripItem).Name;
            FindInfo fi = SearchHelp.FindList.Find(x => x.Name == (sender as ToolStripItem).Name);

            if (CallStandardSearch(fi, (sender as ToolStripItem).Name))
            {
                if (fi != null)
                {
                    foreach (Delegate d in fi.StandardEventHandlers)
                    {
                        d.DynamicInvoke(new object[] { sender, e });
                    }
                }
                return;
            }

            PluginDebug.AddInfo("Call own find routine", 0, "Action: " + f);
            //Show status logger
            Form          fOptDialog = null;
            IStatusLogger sl         = StatusUtil.CreateStatusDialog(m_host.MainWindow, out fOptDialog, null,
                                                                     (KPRes.SearchingOp ?? "..."), true, false);

            m_host.MainWindow.UIBlockInteraction(true);

            m_aStandardLvInit = null;

            //Perform find for all open databases
            PwDatabase    dbAll = MergeDatabases();
            List <object> l     = null;

            try
            {
                object[] parameters;
                if (fi.SearchType != SearchType.BuiltIn)
                {
                    parameters = new object[] { dbAll, sl, null, fi }
                }
                ;
                else
                {
                    parameters = new object[] { dbAll, sl, null }
                };

                l = (List <object>)fi.StandardMethod.Invoke(m_host, parameters);
                m_aStandardLvInit = (Action <ListView>)parameters[2];
            }
            catch (Exception ex)
            {
                l = null;
                PluginDebug.AddError("Call standard find routine", 0, "Action: " + f, "Reason for standard call: " + ex.Message);
                foreach (Delegate d in fi.StandardEventHandlers)
                {
                    d.DynamicInvoke(new object[] { sender, e });
                }
            }
            finally { dbAll.Close(); }

            m_host.MainWindow.UIBlockInteraction(false);
            sl.EndLogging();

            if (l == null)
            {
                return;
            }

            //Fill db column
            ImageList il  = new ImageList();
            ImageList il2 = (ImageList)Tools.GetField("m_ilCurrentIcons", m_host.MainWindow);

            foreach (Image img in il2.Images)
            {
                il.Images.Add(img);
            }

            foreach (var o in l)
            {
                ListViewItem lvi = o as ListViewItem;
                if (lvi == null)
                {
                    continue;
                }
                ListViewItem.ListViewSubItem lvsi = new ListViewItem.ListViewSubItem();
                if (lvi.Tag is PwEntry)
                {
                    lvsi.Text = SearchHelp.GetDBName(lvi.Tag as PwEntry);
                    PwEntry    pe = lvi.Tag as PwEntry;
                    PwDatabase db = m_host.MainWindow.DocumentManager.FindContainerOf(pe);
                    if (!pe.CustomIconUuid.Equals(PwUuid.Zero))
                    {
                        il.Images.Add(db.GetCustomIcon(pe.CustomIconUuid, DpiUtil.ScaleIntX(16), DpiUtil.ScaleIntY(16)));
                        lvi.ImageIndex = il.Images.Count - 1;
                    }
                    else
                    {
                        lvi.ImageIndex = (int)pe.IconId;
                    }
                }
                else if (lvi.Tag is PwGroup)
                {
                    PwGroup pg = lvi.Tag as PwGroup;
                    lvsi.Text = SearchHelp.GetDBName(pg.Entries.GetAt(0));
                }
                lvi.SubItems.Insert(0, lvsi);
            }

            if ((l.Count == 0) && !string.IsNullOrEmpty(fi.NothingFound))
            {
                Tools.ShowInfo(fi.NothingFound);
                il.Dispose();
                return;
            }

            //Show results
            ListViewForm dlg = new ListViewForm();

            //Prepare ImageList (CustomIcons can be different per database)
            dlg.InitEx(fi.Title, fi.SubTitle, fi.Note, fi.img, l, il, InitListView);
            UIUtil.ShowDialogAndDestroy(dlg);
            if (dlg.DialogResult != DialogResult.OK)
            {
                return;
            }
            il.Dispose();
            NavigateToSelectedEntry(dlg, false);
        }
Пример #13
0
        private void OnSearchExecute(object sender, EventArgs e)
        {
            //Perform search in all open databases
            m_dDBGroups = new Dictionary <PwDatabase, PwGroup>();
            PwGroup           g       = null;
            List <PwDatabase> lOpenDB = m_host.MainWindow.DocumentManager.GetOpenDatabases();

            m_btnOK.Click -= OnSearchExecute;
            List <string> lMsg = new List <string>();

            foreach (PwDatabase db in lOpenDB)
            {
                lMsg.Clear();
                lMsg.Add("DB: " + db.IOConnectionInfo.Path);
                if ((m_sf != null) && (m_sf.SearchResultsGroup != null) && (m_sf.SearchResultsGroup.Entries != null))
                {
                    lMsg.Add("Previos search results cleared: " + true.ToString());
                    m_sf.SearchResultsGroup.Entries.Clear();
                }
                m_sf.InitEx(db, db.RootGroup);
                FindInfo fi = SearchHelp.FindList.Find(x => x.Name == SearchHelp.SearchForm);
                if (fi.StandardEventHandlers.Count > 0)
                {
                    using (MonoWorkaroundDialogResult mwaDR = new MonoWorkaroundDialogResult(sender))
                    {
                        foreach (Delegate onclick in fi.StandardEventHandlers)
                        {
                            lMsg.Add("Calling method: " + onclick.Method.Name + " - " + onclick.Method.ReflectedType.Name);
                            onclick.DynamicInvoke(new object[] { sender, e });
                        }
                    }
                }
                else
                {
                    lMsg.Add("Calling standard method");
                    m_btnOK.PerformClick();
                }
                if ((m_sf.SearchResultsGroup == null) || (m_sf.SearchResultsGroup.Entries == null))
                {
                    lMsg.Add("Found entries: 0");
                }
                else
                {
                    lMsg.Add("Found entries: " + m_sf.SearchResultsGroup.Entries.UCount.ToString());
                }

                //Do NOT use m_sf.SearchResultsGroup.CloneDeep
                //It makes the virtual SearchResultsGroup the
                //parent group of the found entries
                if (g == null)
                {
                    g = new PwGroup(true, true, m_sf.SearchResultsGroup.Name, m_sf.SearchResultsGroup.IconId);
                }
                foreach (PwEntry pe in m_sf.SearchResultsGroup.Entries)
                {
                    g.AddEntry(pe, false);
                }
                PluginDebug.AddInfo("Executing search", 0, lMsg.ToArray());
            }

            //Don't continue if not even a single entry was found
            if ((g == null) || (g.GetEntriesCount(true) == 0))
            {
                if (m_sf.DialogResult == DialogResult.None)
                {
                    m_sf.DialogResult = DialogResult.OK;
                }
                return;
            }
            //Prepare ImageList (CustomIcons can be different per database)
            ImageList il  = new ImageList();
            ImageList il2 = (ImageList)Tools.GetField("m_ilCurrentIcons", m_host.MainWindow);

            foreach (Image img in il2.Images)
            {
                il.Images.Add(img);
            }
            Dictionary <PwEntry, int> dEntryIconIndex = new Dictionary <PwEntry, int>();
            PwDatabase dbFirst     = null;
            bool       bMultipleDB = false;

            foreach (PwEntry pe in g.Entries)
            {
                PwDatabase db = m_host.MainWindow.DocumentManager.FindContainerOf(pe);
                if (db == null)
                {
                    PluginDebug.AddError("Could not get database for entry", 0, pe.Uuid.ToHexString());
                    continue;
                }
                if (!m_dDBGroups.ContainsKey(db))
                {
                    m_dDBGroups[db] = new PwGroup(true, false, SearchHelp.GetDBName(pe), PwIcon.Folder)
                    {
                        IsVirtual = true
                    }
                }
                ;
                m_dDBGroups[db].AddEntry(pe, false);
                if (dbFirst == null)
                {
                    dbFirst = db;
                }
                bMultipleDB |= db != dbFirst;
                if (!pe.CustomIconUuid.Equals(PwUuid.Zero))
                {
                    il.Images.Add(db.GetCustomIcon(pe.CustomIconUuid, DpiUtil.ScaleIntX(16), DpiUtil.ScaleIntY(16)));
                    dEntryIconIndex[pe] = dEntryIconIndex.Count - 1;
                }
                else
                {
                    dEntryIconIndex[pe] = (int)pe.IconId;
                }
            }

            //If all found entries are contained in the same database
            //simply activate this database (might not be active yet) and return
            if (!bMultipleDB)
            {
                PwGroup pgSF = (PwGroup)Tools.GetField("m_pgResultsGroup", m_sf);
                if (pgSF != null)
                {
                    //clear list of found entries
                    //otherwise duplicates might be shown if last searched db is the only one that is to be shown
                    pgSF.Entries.Clear();
                    pgSF.Entries.Add(g.Entries);
                }
                else                 //KeePass 2.47
                {
                    pgSF           = new PwGroup(true, true, g.Name, g.IconId);
                    pgSF.IsVirtual = true;
                    pgSF.Entries.Add(g.Entries);
                }
                PluginDebug.AddInfo("Found " + pgSF.Entries.UCount.ToString() + " entries in 1 database");
                m_host.MainWindow.UpdateUI(false, m_host.MainWindow.DocumentManager.FindDocument(dbFirst), true, pgSF, false, null, false);
                il.Dispose();
                m_sf.SearchResultsGroup.Entries.Clear();
                m_sf.SearchResultsGroup.Entries.Add(pgSF.Entries);
                m_sf.DialogResult = DialogResult.OK;
                return;
            }

            //We found entries from at least 2 databases
            //Show the results in ListViewForm and close SearchForm
            try
            {
                PluginDebug.AddInfo("Found " + g.Entries.UCount.ToString() + " entries in multiple database");
                m_sf.DialogResult = DialogResult.Abort;
                m_sf.Visible      = false;
                m_sf.Close();
            }
            catch (Exception ex)
            {
                PluginDebug.AddError("Error closing searchform", new string[] { ex.Message });
            }

            m_aStandardLvInit = InitListViewMain;
            List <object> l = GetFoundEntriesList(g, dEntryIconIndex);

            ListViewForm dlg       = new ListViewForm();
            int          iCount    = l.FindAll(x => (x as ListViewItem) != null).Count;
            string       sSubTitle = iCount == 1 ? KPRes.SearchEntriesFound1 : KPRes.SearchEntriesFound;

            sSubTitle = sSubTitle.Replace("{PARAM}", iCount.ToString());
            dlg.InitEx(KPRes.Search, sSubTitle, null, null, l, il, InitListView);
            ShowMultiDBInfo(true);
            PluginDebug.AddInfo("Multi-DB results: Show", 0);
            if (UIUtil.ShowDialogNotValue(dlg, DialogResult.OK))
            {
                PluginDebug.AddInfo("Multi-DB results: Shown", 0);
                return;
            }
            PluginDebug.AddInfo("Multi-DB results: Show and navigate", 0);
            il.Dispose();
            NavigateToSelectedEntry(dlg, true);
            PluginDebug.AddInfo("Multi-DB results: Dispose form", 0);
            UIUtil.DestroyForm(dlg);
            PluginDebug.AddInfo("Multi-DB results: Disposed form", 0);
        }
Пример #14
0
        private int RenderCheckBox(Context ctx, State.CheckBox stateid, Rectangle prect)
        {
            Brush backBrush;
            Color foreColor;
            Pen   borderPen;

            switch (stateid)
            {
            case State.CheckBox.CBS_UNCHECKEDNORMAL:
            case State.CheckBox.CBS_CHECKEDNORMAL:
            case State.CheckBox.CBS_MIXEDNORMAL:
                backBrush = SystemBrushes.Window;
                foreColor = SystemColors.WindowText;
                borderPen = SystemPens.ControlDarkDark;
                break;

            case State.CheckBox.CBS_UNCHECKEDHOT:
            case State.CheckBox.CBS_CHECKEDHOT:
            case State.CheckBox.CBS_MIXEDHOT:
                backBrush = SystemBrushes.Window;
                foreColor = SystemColors.HotTrack;
                borderPen = SystemPens.HotTrack;
                break;

            case State.CheckBox.CBS_UNCHECKEDPRESSED:
            case State.CheckBox.CBS_CHECKEDPRESSED:
            case State.CheckBox.CBS_MIXEDPRESSED:
                backBrush = SystemBrushes.ControlLightLight;
                foreColor = SystemColors.HotTrack;
                borderPen = SystemPens.HotTrack;
                break;

            case State.CheckBox.CBS_UNCHECKEDDISABLED:
            case State.CheckBox.CBS_CHECKEDDISABLED:
            case State.CheckBox.CBS_MIXEDDISABLED:
                backBrush = SystemBrushes.Control;
                foreColor = SystemColors.ControlDark;
                borderPen = SystemPens.ControlLight;
                break;

            // case State.CheckBox.CBS_IMPLICITNORMAL:
            // case State.CheckBox.CBS_IMPLICITHOT:
            // case State.CheckBox.CBS_IMPLICITPRESSED:
            // case State.CheckBox.CBS_IMPLICITDISABLED:
            // case State.CheckBox.CBS_EXCLUDEDNORMAL:
            // case State.CheckBox.CBS_EXCLUDEDHOT:
            // case State.CheckBox.CBS_EXCLUDEDPRESSED:
            // case State.CheckBox.CBS_EXCLUDEDDISABLED:
            default:
                return(Unhandled);
            }

            ctx.Graphics.FillRectangle(backBrush, prect);
            var border = prect.Inclusive();

            ctx.Graphics.DrawRectangle(borderPen, border);

            switch (stateid)
            {
            case State.CheckBox.CBS_MIXEDNORMAL:
            case State.CheckBox.CBS_MIXEDHOT:
            case State.CheckBox.CBS_MIXEDPRESSED:
            case State.CheckBox.CBS_MIXEDDISABLED:
                prect.Inflate(-prect.Width / 4, -prect.Height / 4);
                ctx.Graphics.FillRectangle(SystemBrushes.FromSystemColor(foreColor), prect);
                break;

            case State.CheckBox.CBS_CHECKEDNORMAL:
            case State.CheckBox.CBS_CHECKEDHOT:
            case State.CheckBox.CBS_CHECKEDPRESSED:
            case State.CheckBox.CBS_CHECKEDDISABLED:
                int padding = DpiUtil.Scale(2);
                int x1      = border.Left + padding;
                int x2      = border.Left + (border.Width / 2);
                int x3      = border.Right - padding;
                int y1      = border.Top + (border.Height / 4);
                int y2      = border.Top + (border.Height / 2);
                int y3      = border.Bottom - (border.Height / 4);
                var points  = new[]
                {
                    new Point(x1, y2),
                    new Point(x2, y3),
                    new Point(x3, y1),
                };
                using (var checkPen = new Pen(foreColor, DpiUtil.Scale(1.5f)))
                    using (ctx.HighQuality())
                    {
                        ctx.Graphics.DrawLines(checkPen, points);
                    }

                break;
            }

            return(Handled);
        }
Пример #15
0
        public void RefreshContent()
        {
            InitDashboardLayout();
            ApplyTheme();
            userRepositoriesList.ShowRecentRepositories();

            void ApplyTheme()
            {
                _selectedTheme = SystemColors.ControlText.IsLightColor() ? DashboardTheme.Dark : DashboardTheme.Light;

                BackColor                            = _selectedTheme.Primary;
                pnlLogo.BackColor                    = _selectedTheme.PrimaryVeryDark;
                flpnlStart.BackColor                 = _selectedTheme.PrimaryLight;
                flpnlContribute.BackColor            = _selectedTheme.PrimaryVeryLight;
                lblContribute.ForeColor              = _selectedTheme.SecondaryHeadingText;
                userRepositoriesList.BranchNameColor = AppSettings.BranchColor; // _selectedTheme.SecondaryText;
                userRepositoriesList.FavouriteColor  = _selectedTheme.AccentedText;
                userRepositoriesList.ForeColor       = _selectedTheme.PrimaryText;
                userRepositoriesList.HeaderColor     = _selectedTheme.SecondaryHeadingText;
                userRepositoriesList.HeaderBackColor = _selectedTheme.PrimaryDark;
                userRepositoriesList.HoverColor      = _selectedTheme.PrimaryLight;
                userRepositoriesList.MainBackColor   = _selectedTheme.Primary;
                BackgroundImage                      = _selectedTheme.BackgroundImage;

                foreach (var item in flpnlContribute.Controls.OfType <LinkLabel>().Union(flpnlStart.Controls.OfType <LinkLabel>()))
                {
                    item.LinkColor = _selectedTheme.PrimaryText;
                }
            }

            void InitDashboardLayout()
            {
                try
                {
                    pnlLeft.SuspendLayout();

                    AddLinks(flpnlContribute,
                             panel =>
                    {
                        panel.Controls.Add(lblContribute);
                        lblContribute.Font = new Font(AppSettings.Font.FontFamily, AppSettings.Font.SizeInPoints + 5.5f);

                        CreateLink(panel, _develop.Text, Images.Develop, GitHubItem_Click);
                        CreateLink(panel, _donate.Text, Images.DollarSign, DonateItem_Click);
                        CreateLink(panel, _translate.Text, Images.Translate, TranslateItem_Click);
                        var lastControl = CreateLink(panel, _issues.Text, Images.Bug, IssuesItem_Click);
                        return(lastControl);
                    },
                             (panel, lastControl) =>
                    {
                        var height        = lastControl.Location.Y + lastControl.Size.Height + panel.Padding.Bottom;
                        panel.Height      = height;
                        panel.MinimumSize = new Size(0, height);
                    });

                    AddLinks(flpnlStart,
                             panel =>
                    {
                        CreateLink(panel, _createRepository.Text, Images.RepoCreate, createItem_Click);
                        CreateLink(panel, _openRepository.Text, Images.RepoOpen, openItem_Click);
                        var lastControl = CreateLink(panel, _cloneRepository.Text, Images.CloneRepoGit, cloneItem_Click);

                        foreach (var gitHoster in PluginRegistry.GitHosters)
                        {
                            lastControl = CreateLink(panel, string.Format(_cloneFork.Text, gitHoster.Description), Images.CloneRepoGitHub,
                                                     (repoSender, eventArgs) => UICommands.StartCloneForkFromHoster(this, gitHoster, GitModuleChanged));
                        }

                        return(lastControl);
                    },
                             (panel, lastControl) =>
                    {
                        var height        = lastControl.Location.Y + lastControl.Size.Height + panel.Padding.Bottom;
                        panel.MinimumSize = new Size(0, height);
                    });
                }
                finally
                {
                    pnlLeft.ResumeLayout(false);
                    pnlLeft.PerformLayout();
                    AutoScrollMinSize = new Size(0, pnlLogo.Height + flpnlStart.MinimumSize.Height + flpnlContribute.MinimumSize.Height);
                }

                void AddLinks(Panel panel, Func <Panel, Control> addLinks, Action <Panel, Control> onLayout)
                {
                    panel.SuspendLayout();
                    panel.Controls.Clear();

                    var lastControl = addLinks(panel);

                    panel.ResumeLayout(false);
                    panel.PerformLayout();

                    onLayout(panel, lastControl);
                }

                Control CreateLink(Control container, string text, Image icon, EventHandler handler)
                {
                    var padding24 = DpiUtil.Scale(24);
                    var padding3  = DpiUtil.Scale(3);
                    var linkLabel = new LinkLabel
                    {
                        AutoSize     = true,
                        AutoEllipsis = true,
                        Font         = AppSettings.Font,
                        Image        = DpiUtil.Scale(icon),
                        ImageAlign   = ContentAlignment.MiddleLeft,
                        LinkBehavior = LinkBehavior.NeverUnderline,
                        Margin       = new Padding(padding3, 0, padding3, DpiUtil.Scale(8)),
                        Padding      = new Padding(padding24, padding3, padding3, padding3),
                        TabStop      = true,
                        Text         = text,
                        TextAlign    = ContentAlignment.MiddleLeft
                    };

                    linkLabel.MouseHover += (s, e) => linkLabel.LinkColor = _selectedTheme.AccentedText;
                    linkLabel.MouseLeave += (s, e) => linkLabel.LinkColor = _selectedTheme.PrimaryText;

                    if (handler != null)
                    {
                        linkLabel.Click += handler;
                    }

                    container.Controls.Add(linkLabel);

                    return(linkLabel);
                }
            }
        }
Пример #16
0
        protected override void OnRuntimeLoad(EventArgs e)
        {
            base.OnRuntimeLoad(e);

            // scale up for hi DPI
            MaximumSize = DpiUtil.Scale(new Size(950, 375));
            MinimumSize = DpiUtil.Scale(new Size(450, 375));

            ThreadHelper.JoinableTaskFactory.Run(async() =>
            {
                var repositoryHistory = await RepositoryHistoryManager.Remotes.LoadRecentHistoryAsync();

                await this.SwitchToMainThreadAsync();
                _NO_TRANSLATE_From.DataSource    = repositoryHistory;
                _NO_TRANSLATE_From.DisplayMember = nameof(Repository.Path);
            });

            _NO_TRANSLATE_To.Text = AppSettings.DefaultCloneDestinationPath;

            if (CanBeGitURL(_url) || GitModule.IsValidGitWorkingDir(_url))
            {
                _NO_TRANSLATE_From.Text = _url;
            }
            else
            {
                if (!string.IsNullOrEmpty(_url) && Directory.Exists(_url))
                {
                    _NO_TRANSLATE_To.Text = _url;
                }

                // Try to be more helpful to the user.
                // Use the clipboard text as a potential source URL.
                try
                {
                    if (Clipboard.ContainsText(TextDataFormat.Text))
                    {
                        string text = Clipboard.GetText(TextDataFormat.Text) ?? string.Empty;

                        // See if it's a valid URL.
                        if (CanBeGitURL(text))
                        {
                            _NO_TRANSLATE_From.Text = text;
                        }
                    }
                }
                catch
                {
                    // We tried.
                }

                // if the From field is empty, then fill it with the current repository remote URL in hope
                // that the cloned repository is hosted on the same server
                if (_NO_TRANSLATE_From.Text.IsNullOrWhiteSpace())
                {
                    var currentBranchRemote = Module.GetSetting(string.Format(SettingKeyString.BranchRemote, Module.GetSelectedBranch()));
                    if (currentBranchRemote.IsNullOrEmpty())
                    {
                        var remotes = Module.GetRemoteNames();

                        if (remotes.Any(s => s.Equals("origin", StringComparison.InvariantCultureIgnoreCase)))
                        {
                            currentBranchRemote = "origin";
                        }
                        else
                        {
                            currentBranchRemote = remotes.FirstOrDefault();
                        }
                    }

                    string pushUrl = Module.GetSetting(string.Format(SettingKeyString.RemotePushUrl, currentBranchRemote));
                    if (pushUrl.IsNullOrEmpty())
                    {
                        pushUrl = Module.GetSetting(string.Format(SettingKeyString.RemoteUrl, currentBranchRemote));
                    }

                    _NO_TRANSLATE_From.Text = pushUrl;

                    try
                    {
                        // If the from directory is filled with the pushUrl from current working directory, set the destination directory to the parent
                        if (pushUrl.IsNotNullOrWhitespace() && _NO_TRANSLATE_To.Text.IsNullOrWhiteSpace() && Module.WorkingDir.IsNotNullOrWhitespace())
                        {
                            _NO_TRANSLATE_To.Text = Path.GetDirectoryName(Module.WorkingDir.TrimEnd(Path.DirectorySeparatorChar));
                        }
                    }
                    catch
                    {
                        // Exceptions on setting the destination directory can be ignored
                    }
                }
            }

            // if there is no destination directory, then use the parent of the current working directory
            // this would clone the new repo at the same level as the current one by default
            if (_NO_TRANSLATE_To.Text.IsNullOrWhiteSpace() && Module.WorkingDir.IsNotNullOrWhitespace())
            {
                if (Module.IsValidGitWorkingDir())
                {
                    if (Path.GetPathRoot(Module.WorkingDir) != Module.WorkingDir)
                    {
                        _NO_TRANSLATE_To.Text = Path.GetDirectoryName(Module.WorkingDir.TrimEnd(Path.DirectorySeparatorChar));
                    }
                }
                else
                {
                    _NO_TRANSLATE_To.Text = Module.WorkingDir;
                }
            }

            FromTextUpdate(null, null);

            cbLfs.Visible = !GitVersion.Current.DepreciatedLfsClone;
            cbLfs.Enabled = Module.HasLfsSupport();
            if (!cbLfs.Enabled || !cbLfs.Visible)
            {
                cbLfs.Checked = false;
            }
        }
Пример #17
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            if (m_lInfo == null)
            {
                throw new InvalidOperationException();
            }

            GlobalWindowManager.AddWindow(this, this);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_WWW, KPRes.UpdateCheck,
                                         KPRes.UpdateCheckResults);
            this.Icon = AppIcons.Default;
            this.Text = KPRes.UpdateCheck + " - " + PwDefs.ShortProductName;

            UIUtil.SetExplorerTheme(m_lvInfo, true);

            m_lvInfo.Columns.Add(KPRes.Component);
            m_lvInfo.Columns.Add(KPRes.Status);
            m_lvInfo.Columns.Add(KPRes.Installed);
            m_lvInfo.Columns.Add(KPRes.Available);

            List <Image> lImages = new List <Image>();

            lImages.Add(Properties.Resources.B16x16_Help);
            lImages.Add(Properties.Resources.B16x16_Apply);
            lImages.Add(Properties.Resources.B16x16_Redo);
            lImages.Add(Properties.Resources.B16x16_History);
            lImages.Add(Properties.Resources.B16x16_Error);
            m_ilIcons = UIUtil.BuildImageListUnscaled(lImages,
                                                      DpiUtil.ScaleIntX(16), DpiUtil.ScaleIntY(16));

            m_lvInfo.SmallImageList = m_ilIcons;

            string        strCat   = string.Empty;
            ListViewGroup lvg      = null;
            const uint    uMinComp = 2;

            foreach (UpdateComponentInfo uc in m_lInfo)
            {
                if (uc.Category != strCat)
                {
                    lvg = new ListViewGroup(uc.Category);
                    m_lvInfo.Groups.Add(lvg);
                    strCat = uc.Category;
                }

                ListViewItem lvi = new ListViewItem(uc.Name);

                string strStatus = KPRes.Unknown + ".";
                if (uc.Status == UpdateComponentStatus.UpToDate)
                {
                    strStatus      = KPRes.UpToDate + ".";
                    lvi.ImageIndex = 1;
                }
                else if (uc.Status == UpdateComponentStatus.NewVerAvailable)
                {
                    strStatus      = KPRes.NewVersionAvailable + "!";
                    lvi.ImageIndex = 2;
                }
                else if (uc.Status == UpdateComponentStatus.PreRelease)
                {
                    strStatus      = KPRes.PreReleaseVersion + ".";
                    lvi.ImageIndex = 3;
                }
                else if (uc.Status == UpdateComponentStatus.DownloadFailed)
                {
                    strStatus      = KPRes.UpdateCheckFailedNoDl;
                    lvi.ImageIndex = 4;
                }
                else
                {
                    lvi.ImageIndex = 0;
                }

                lvi.SubItems.Add(strStatus);
                lvi.SubItems.Add(StrUtil.VersionToString(uc.VerInstalled, uMinComp));

                if ((uc.Status == UpdateComponentStatus.UpToDate) ||
                    (uc.Status == UpdateComponentStatus.NewVerAvailable) ||
                    (uc.Status == UpdateComponentStatus.PreRelease))
                {
                    lvi.SubItems.Add(StrUtil.VersionToString(uc.VerAvailable, uMinComp));
                }
                else
                {
                    lvi.SubItems.Add("?");
                }

                if (lvg != null)
                {
                    lvi.Group = lvg;
                }
                m_lvInfo.Items.Add(lvi);
            }

            UIUtil.ResizeColumns(m_lvInfo, new int[] { 2, 2, 1, 1 }, true);
        }
Пример #18
0
        public override object GetObject(string name, CultureInfo culture)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (this.GetObjectPre != null)
            {
                CrmEventArgs e = new CrmEventArgs(name, culture, null);
                this.GetObjectPre(this, e);
                if (e.Object != null)
                {
                    return(e.Object);
                }
            }

            object oOvr;

            if (m_dOverrides.TryGetValue(name, out oOvr))
            {
                return(oOvr);
            }

            object o = m_rm.GetObject(name, culture);

            if (o == null)
            {
                Debug.Assert(false); return(null);
            }

            try
            {
                Image img = (o as Image);
                if (img != null)
                {
                    Debug.Assert(!(o is Icon));

                    Image imgOvr = m_iaAppHighRes.GetForObject(name);
                    if (imgOvr != null)
                    {
                        int wOvr  = imgOvr.Width;
                        int hOvr  = imgOvr.Height;
                        int wBase = img.Width;
                        int hBase = img.Height;
                        int wReq  = DpiUtil.ScaleIntX(wBase);
                        int hReq  = DpiUtil.ScaleIntY(hBase);

                        if ((wBase > wOvr) || (hBase > hOvr))
                        {
                            Debug.Assert(false);                             // Base has higher resolution
                            imgOvr = img;
                            wOvr   = wBase;
                            hOvr   = hBase;
                        }

                        if ((wReq != wOvr) || (hReq != hOvr))
                        {
                            imgOvr = GfxUtil.ScaleImage(imgOvr, wReq, hReq,
                                                        ScaleTransformFlags.UIIcon);
                        }
                    }
                    else
                    {
                        imgOvr = DpiUtil.ScaleImage(img, false);
                    }

                    m_dOverrides[name] = imgOvr;
                    return(imgOvr);
                }
            }
            catch (Exception) { Debug.Assert(false); }

            return(o);
        }
Пример #19
0
        public FormPush([NotNull] GitUICommands commands)
            : base(commands)
        {
            InitializeComponent();

            NewColumn.Width    = DpiUtil.Scale(97);
            PushColumn.Width   = DpiUtil.Scale(36);
            ForceColumn.Width  = DpiUtil.Scale(101);
            DeleteColumn.Width = DpiUtil.Scale(108);

            InitializeComplete();

            if (!GitVersion.Current.SupportPushForceWithLease)
            {
                ckForceWithLease.Visible = false;
                ForcePushTags.DataBindings.Add("Checked", ForcePushBranches, "Checked",
                                               formattingEnabled: false, updateMode: DataSourceUpdateMode.OnPropertyChanged);
            }
            else
            {
                ForcePushTags.DataBindings.Add("Checked", ckForceWithLease, "Checked",
                                               formattingEnabled: false, updateMode: DataSourceUpdateMode.OnPropertyChanged);
                toolTip1.SetToolTip(ckForceWithLease, _forceWithLeaseTooltips.Text);
            }

            // can't be set in OnLoad, because after PushAndShowDialogWhenFailed()
            // they are reset to false
            _remotesManager = new ConfigFileRemoteSettingsManager(() => Module);
            Init();

            void Init()
            {
                _gitRefs = Module.GetRefs();
                if (GitVersion.Current.SupportPushWithRecursiveSubmodulesCheck)
                {
                    RecursiveSubmodules.Enabled       = true;
                    RecursiveSubmodules.SelectedIndex = AppSettings.RecursiveSubmodules;
                    if (!GitVersion.Current.SupportPushWithRecursiveSubmodulesOnDemand)
                    {
                        RecursiveSubmodules.Items.RemoveAt(2);
                    }
                }
                else
                {
                    RecursiveSubmodules.Enabled       = false;
                    RecursiveSubmodules.SelectedIndex = 0;
                }

                _currentBranchName = Module.GetSelectedBranch();

                // refresh registered git remotes
                UserGitRemotes = _remotesManager.LoadRemotes(false).ToList();
                BindRemotesDropDown(null);

                UpdateBranchDropDown();
                UpdateRemoteBranchDropDown();

                Push.Focus();

                if (AppSettings.AlwaysShowAdvOpt)
                {
                    ShowOptions_LinkClicked(null, null);
                }
            }
        }
Пример #20
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            Debug.Assert(m_pwGroup != null); if (m_pwGroup == null)
            {
                throw new InvalidOperationException();
            }
            Debug.Assert(m_pwDatabase != null); if (m_pwDatabase == null)
            {
                throw new InvalidOperationException();
            }

            GlobalWindowManager.AddWindow(this);

            string strTitle = (m_bCreatingNew ? KPRes.AddGroup : KPRes.EditGroup);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_Folder_Txt, strTitle,
                                         (m_bCreatingNew ? KPRes.AddGroupDesc : KPRes.EditGroupDesc));
            this.Icon = AppIcons.Default;
            this.Text = strTitle;

            UIUtil.SetButtonImage(m_btnAutoTypeEdit,
                                  Properties.Resources.B16x16_Wizard, true);

            m_pwIconIndex    = m_pwGroup.IconId;
            m_pwCustomIconID = m_pwGroup.CustomIconUuid;

            m_tbName.Text = m_pwGroup.Name;
            UIUtil.SetMultilineText(m_tbNotes, m_pwGroup.Notes);

            if (!m_pwCustomIconID.Equals(PwUuid.Zero))
            {
                UIUtil.SetButtonImage(m_btnIcon, DpiUtil.GetIcon(
                                          m_pwDatabase, m_pwCustomIconID), true);
            }
            else
            {
                UIUtil.SetButtonImage(m_btnIcon, m_ilClientIcons.Images[
                                          (int)m_pwIconIndex], true);
            }

            if (m_pwGroup.Expires)
            {
                m_dtExpires.Value   = TimeUtil.ToLocal(m_pwGroup.ExpiryTime, true);
                m_cbExpires.Checked = true;
            }
            else             // Does not expire
            {
                m_dtExpires.Value   = DateTime.Now.Date;
                m_cbExpires.Checked = false;
            }
            m_cgExpiry.Attach(m_cbExpires, m_dtExpires);

            PwGroup pgParent        = m_pwGroup.ParentGroup;
            bool    bParentAutoType = ((pgParent != null) ?
                                       pgParent.GetAutoTypeEnabledInherited() :
                                       PwGroup.DefaultAutoTypeEnabled);

            UIUtil.MakeInheritableBoolComboBox(m_cmbEnableAutoType,
                                               m_pwGroup.EnableAutoType, bParentAutoType);
            bool bParentSearching = ((pgParent != null) ?
                                     pgParent.GetSearchingEnabledInherited() :
                                     PwGroup.DefaultSearchingEnabled);

            UIUtil.MakeInheritableBoolComboBox(m_cmbEnableSearching,
                                               m_pwGroup.EnableSearching, bParentSearching);

            m_tbDefaultAutoTypeSeq.Text = m_pwGroup.GetAutoTypeSequenceInherited();

            if (m_pwGroup.DefaultAutoTypeSequence.Length == 0)
            {
                m_rbAutoTypeInherit.Checked = true;
            }
            else
            {
                m_rbAutoTypeOverride.Checked = true;
            }

            m_sdCustomData = m_pwGroup.CustomData.CloneDeep();
            UIUtil.StrDictListInit(m_lvCustomData);
            UIUtil.StrDictListUpdate(m_lvCustomData, m_sdCustomData);

            CustomizeForScreenReader();
            EnableControlsEx();

            ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                try
                {
                    string[] vSeq = m_pwDatabase.RootGroup.GetAutoTypeSequences(true);
                    // Do not append, because long suggestions hide the start
                    UIUtil.EnableAutoCompletion(m_tbDefaultAutoTypeSeq,
                                                false, vSeq); // Invokes
                }
                catch (Exception) { Debug.Assert(false); }
            });

            UIUtil.SetFocus(m_tbName, this);
        }
Пример #21
0
        private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
        {
            var spacing1 = DpiUtil.Scale(1f);
            var spacing2 = DpiUtil.Scale(2f);
            var spacing4 = DpiUtil.Scale(4f);
            var spacing6 = DpiUtil.Scale(6f);

            var textOffset = spacing2 + imageList1.ImageSize.Width + spacing2;
            int textWidth  = AppSettings.RecentReposComboMinWidth > 0 ? AppSettings.RecentReposComboMinWidth : e.Bounds.Width;

            if (e.Item == _prevHoveredItem)
            {
                e.Graphics.FillRectangle(_hoverColorBrush, e.Bounds);
            }
            else
            {
                e.DrawBackground();
            }

            var pointImage = new PointF(e.Bounds.Left + spacing4, e.Bounds.Top + (spacing2 * 4));

            // render anchor icon
            if (!string.IsNullOrWhiteSpace((e.Item.Tag as Repository)?.Category))
            {
                var pointImage1 = new PointF(pointImage.X + imageList1.ImageSize.Width - 12, e.Bounds.Top + spacing2);
                e.Graphics.DrawImage(Images.Star, pointImage1.X, pointImage1.Y, 16, 16);
            }

            // render icon
            e.Graphics.DrawImage(imageList1.Images[e.Item.ImageIndex], pointImage);

            // render path
            var textPadding = new PointF(e.Bounds.Left + spacing4, e.Bounds.Top + spacing6);
            var pointPath   = new PointF(textPadding.X + textOffset, textPadding.Y);
            var pathBounds  = DrawText(e.Graphics, e.Item.Text, AppSettings.Font, _foreColorBrush, textWidth, pointPath, spacing4 * 2);

            // render branch
            var pointBranch  = new PointF(pointPath.X, pointPath.Y + pathBounds.Height + spacing1);
            var branchBounds = DrawText(e.Graphics, e.Item.SubItems[1].Text, _secondaryFont, _branchNameColorBrush, textWidth, pointBranch, spacing4 * 2);

            // render category
            if (!string.IsNullOrWhiteSpace(e.Item.SubItems[2].Text))
            {
                var pointCategory = string.IsNullOrWhiteSpace(e.Item.SubItems[1].Text) ?
                                    pointBranch :
                                    new PointF(pointBranch.X, pointBranch.Y + branchBounds.Height + spacing1);
                DrawText(e.Graphics, e.Item.SubItems[2].Text, _secondaryFont, SystemBrushes.GrayText, textWidth, pointCategory, spacing4 * 2);
            }

            RectangleF DrawText(Graphics g, string text, Font font, Brush brush, int maxTextWidth, PointF location, float spacing)
            {
                var textBounds = TextRenderer.MeasureText(text, font);
                var minWidth   = Math.Min(textBounds.Width + spacing, maxTextWidth);
                var bounds     = new RectangleF(location, new SizeF(minWidth, textBounds.Height));
                var text1      = Math.Abs(maxTextWidth - minWidth) < float.Epsilon ? ShortenText(text, font, minWidth) : text;

                g.DrawString(text1, font, brush, bounds, StringFormat.GenericTypographic);

                return(bounds);
            }
        }