private bool SaveChosenIcon() { ListView.SelectedIndexCollection lvsicS = m_lvIcons.SelectedIndices; int cS = lvsicS.Count; m_uChosenIcon = ((cS > 0) ? (uint)lvsicS[0] : m_uDefaultIcon); if (m_radioStandard.Checked && (cS != 1)) { return(false); } if (m_radioCustom.Checked) { ListView.SelectedListViewItemCollection lvsicC = m_lvCustomIcons.SelectedItems; if (lvsicC.Count != 1) { return(false); } PwCustomIcon ci = (lvsicC[0].Tag as PwCustomIcon); if (ci == null) { Debug.Assert(false); return(false); } m_puChosenCustomIcon = ci.Uuid; } else { m_puChosenCustomIcon = PwUuid.Zero; } return(true); }
private PwCustomIcon getOrAddCustomIcon(byte[] icon_data) { if (null == icon_data) { return(null); } try { System.Collections.Generic.List <PwCustomIcon> icon_entries = m_host.Database.CustomIcons; for (int i = 0; i < icon_entries.Count; i++) { string checksum1 = CalculateMD5Hash(icon_entries[i].ImageDataPng); string checksum2 = CalculateMD5Hash(icon_data); if (checksum1 == checksum2) { return(icon_entries[i]); } } PwUuid uuid = new PwUuid(true); PwCustomIcon custom_icon = new PwCustomIcon(uuid, icon_data); m_host.Database.CustomIcons.Add(custom_icon); return(custom_icon); } catch (Exception ex) { showError(ex); } return(null); }
private void OnBtnCustomRemove(object sender, EventArgs e) { ListView.SelectedListViewItemCollection lvsic = m_lvCustomIcons.SelectedItems; if (lvsic.Count == 0) { Debug.Assert(false); return; } List <PwUuid> lDel = new List <PwUuid>(); foreach (ListViewItem lvi in lvsic) { PwCustomIcon ci = (lvi.Tag as PwCustomIcon); if (ci != null) { lDel.Add(ci.Uuid); } else { Debug.Assert(false); } } m_pd.DeleteCustomIcons(lDel); m_pd.UINeedsIconUpdate = true; m_pd.Modified = true; RecreateCustomIconList(PwUuid.Zero); EnableControlsEx(); }
private void SelectCustomIcon(PwUuid pu) { if (pu.Equals(PwUuid.Zero)) { return; } foreach (ListViewItem lvi in m_lvCustomIcons.Items) { PwCustomIcon ci = (lvi.Tag as PwCustomIcon); if (ci == null) { Debug.Assert(false); continue; } if (ci.Uuid.Equals(pu)) { m_lvCustomIcons.BeginUpdate(); // Avoid animation from left lvi.EnsureVisible(); UIUtil.SetFocusedItem(m_lvCustomIcons, lvi, true); m_lvCustomIcons.EndUpdate(); return; } } Debug.Assert(false); }
private PwUuid GetKeeFoxIcon() { //return null; // {EB9FF2ED-0512-4747-B63E-AFA515A30422} PwUuid keeFoxIconUuid = new PwUuid(new byte[] { 0xeb, 0x9f, 0xf2, 0xed, 0x05, 0x12, 0x47, 0x47, 0xb6, 0x3e, 0xaf, 0xa5, 0x15, 0xa3, 0x04, 0x22 }); PwCustomIcon icon = null; foreach (PwCustomIcon testIcon in _host.Database.CustomIcons) { if (testIcon.Uuid == keeFoxIconUuid) { icon = testIcon; break; } } if (icon == null) { MemoryStream ms = new MemoryStream(); global::KeePassRPC.Properties.Resources.KeeFox16.Save(ms, System.Drawing.Imaging.ImageFormat.Png); // Create a new custom icon for use with this entry icon = new PwCustomIcon(keeFoxIconUuid, ms.ToArray()); _host.Database.CustomIcons.Add(icon); } return(keeFoxIconUuid); //string keeFoxIcon = @"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAFfKj/FAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAABpUExURf///wAAAAAAAFpaWl5eXm5ubnh4eICAgIeHh5GRkaCgoKOjo66urq+vr8jIyMnJycvLy9LS0uDg4Ovr6+zs7O3t7e7u7u/v7/X19fb29vf39/j4+Pn5+fr6+vv7+/z8/P39/f7+/v///5goWdMAAAADdFJOUwAxTTRG/kEAAACRSURBVBjTTY2JEoMgDESDaO0h9m5DUZT9/49sCDLtzpB5eQwLkSTkwb0cOBnJksYxiHqORHZG3gFc88WReTzvBFoOMbUCVkN/ATw3CnwHmwLjpYCfYoF5TQphAUztMfp5zsm5phY6MEsV+LapYRPAoC/ooOLxfL33RXQifJjjsnZFWPBniksCbBU+6F4FmV+IvtrgDOmaq+PeAAAAAElFTkSuQmCC"; //byte[] msByteArray = ms.ToArray(); //foreach (PwCustomIcon item in _host.Database.CustomIcons) //{ // *var* t = item.Image.[1][2]; // // re-use existing custom icon if it's already in the database // // (This will probably fail if database is used on // // both 32 bit and 64 bit machines - not sure why...) // if (KeePassLib.Utility.MemUtil.ArraysEqual(msByteArray, item.ImageDataPng)) // { // pwe.CustomIconUuid = item.Uuid; // m_host.Database.UINeedsIconUpdate = true; // return; // } //} // // Create a new custom icon for use with this entry // PwCustomIcon pwci = new PwCustomIcon(new PwUuid(true), // ms.ToArray()); // m_host.Database.CustomIcons.Add(pwci); // return pwci.Uuid; }
private void CheckAndAddIotaIcon() { if (!this.m_host.Database.CustomIcons.Any(i => i.Uuid.UuidBytes == this.iconUuId)) { var icon = new PwCustomIcon(new PwUuid(this.iconUuId), GetIotaIconAsPng()); this.m_host.Database.CustomIcons.Add(icon); } }
internal PwCustomIcon GetCustomIcon() { byte[] icon = this.ConvertIconToPng(); PwUuid uuid = this.GetUuid(icon); PwCustomIcon customIcon = new PwCustomIcon(uuid, icon); return(customIcon); }
/// <summary> /// converts a string to the relevant icon for this entry /// </summary> /// <param name="imageData">base64 representation of the image</param> /// <param name="customIconUUID">UUID of the generated custom icon; may be Zero</param> /// <param name="iconId">PwIcon of the matched standard icon; ignore if customIconUUID != Zero</param> /// <returns>true if the supplied imageData was converted into a customIcon /// or matched with a standard icon.</returns> public bool base64ToIcon(string imageData, ref PwUuid customIconUUID, ref PwIcon iconId) { iconId = PwIcon.Key; customIconUUID = PwUuid.Zero; for (int i = 0; i < _standardIconsBase64.Length; i++) { string item = _standardIconsBase64[i]; if (item == imageData) { iconId = (PwIcon)i; return(true); } } try { //MemoryStream id = new MemoryStream(); //icon.Save(ms, System.Drawing.Imaging.ImageFormat.Png); using (Image img = KeePass.UI.UIUtil.LoadImage(Convert.FromBase64String(imageData))) using (Image imgNew = new Bitmap(img, new Size(16, 16))) using (MemoryStream ms = new MemoryStream()) { // No need to lock here because we've created a new Bitmap // (KeePass.UI.UIUtil.LoadImage has no caching or fancy stuff) imgNew.Save(ms, System.Drawing.Imaging.ImageFormat.Png); byte[] msByteArray = ms.ToArray(); foreach (PwCustomIcon item in host.Database.CustomIcons) { // re-use existing custom icon if it's already in the database // (This will probably fail if database is used on // both 32 bit and 64 bit machines - not sure why...) if (KeePassLib.Utility.MemUtil.ArraysEqual(msByteArray, item.ImageDataPng)) { customIconUUID = item.Uuid; host.Database.UINeedsIconUpdate = true; return(true); } } PwCustomIcon pwci = new PwCustomIcon(new PwUuid(true), msByteArray); host.Database.CustomIcons.Add(pwci); customIconUUID = pwci.Uuid; host.Database.UINeedsIconUpdate = true; } return(true); } catch { return(false); } }
/// <summary> /// Event handler triggered when the set icon button is clicked. /// </summary> /// <param name="sender">The object which triggered the event.</param> /// <param name="e">The event arguments.</param> private void setIcon_Click(object sender, System.EventArgs e) { string application = this.application.Text; PwCustomIcon customIcon = this.passwordEntryManager.SetIconFromExecutable(application); if (this.EntryIconUpdated != null) { IconUpdatedEventArgs eventArgs = new IconUpdatedEventArgs(customIcon); this.EntryIconUpdated(this, eventArgs); } }
internal MultipleValuesEntryContext(PwEntry[] v, PwDatabase pd, out PwEntry peMulti) { if ((v == null) || (v.Length < 1)) { throw new ArgumentOutOfRangeException("v"); } if (Array.IndexOf(v, null) >= 0) { throw new ArgumentOutOfRangeException("v"); } if (pd == null) { throw new ArgumentNullException("pd"); } if (!pd.IsOpen) { throw new ArgumentOutOfRangeException("pd"); } PwEntry peM = new PwEntry(true, true); peM.ParentGroup = pd.RootGroup; m_v = new PwEntry[v.Length]; Array.Copy(v, m_v, v.Length); m_pd = pd; m_peM = peM; m_vModified = new bool[v.Length]; MultiInitStrings(); MultiInitIcon(); MultiInitProperties(); MultiInitCustomData(); if (peM.CustomIconUuid.Equals(m_puCueIcon)) { using (Image img = MultipleValuesEx.CreateMultiImage(null)) { using (MemoryStream ms = new MemoryStream()) { img.Save(ms, ImageFormat.Png); PwCustomIcon ico = new PwCustomIcon(m_puCueIcon, ms.ToArray()); ico.Name = MultipleValuesEx.CueString; pd.CustomIcons.Add(ico); pd.UINeedsIconUpdate = true; } } } peMulti = peM; }
public int GetNbUrlsInEntries(PwCustomIcon pci) { Debug.Assert(m_isInitialized); if (m_dicCustomIconsStats.ContainsKey(pci.Uuid)) { return(m_dicCustomIconsStats[pci.Uuid].listUris.Count); } else { return(0); } }
/// <summary> /// Get List of Uris /// </summary> /// <param name="pci"></param> /// <returns>List of groups</return> public ICollection <Uri> GetListUris(PwCustomIcon pci) { Debug.Assert(m_isInitialized); if (m_dicCustomIconsStats.ContainsKey(pci.Uuid)) { return(m_dicCustomIconsStats[pci.Uuid].listUris); } else { return(new List <Uri>()); } }
private void setIcon(PwEntry pwe, string icon_url) { PwCustomIcon custom_icon = getOrAddCustomIcon(getIconBytesFromUrl(icon_url)); if (custom_icon == null) { pwe.IconId = PwIcon.Star; } else { pwe.CustomIconUuid = custom_icon.Uuid; } }
public int GetNbUsageInGroups(PwCustomIcon pci) { Debug.Assert(m_isInitialized); if (m_dicCustomIconsStats.ContainsKey(pci.Uuid)) { return(m_dicCustomIconsStats[pci.Uuid].nbInGroups); } else { return(0); } }
/// <summary> /// Get List of groups for Custom Icon /// </summary> /// <param name="pci"></param> /// <returns>List of groups</returns> public ICollection <PwGroup> GetListGroupsForPci(PwCustomIcon pci) { Debug.Assert(m_isInitialized); if (m_dicCustomIconsStats.ContainsKey(pci.Uuid)) { return(m_dicCustomIconsStats[pci.Uuid].listGroups); } else { return(new List <PwGroup>()); } }
private void OnCustomIconsBeforeLabelEdit(object sender, LabelEditEventArgs e) { PwCustomIcon ci = (m_lvCustomIcons.Items[e.Item].Tag as PwCustomIcon); if (ci == null) { Debug.Assert(false); e.CancelEdit = true; return; } if (ci.Name == MultipleValuesEx.CueString) { e.CancelEdit = true; } }
private void ChangeEntriesIcon(PwEntry[] entries, PwGroup group, PwCustomIcon icon) { if (group != null) { group.CustomIconUuid = icon.Uuid; group.Touch(true, false); } foreach (var entry in entries) { // Set icon & update entry.CustomIconUuid = icon.Uuid; entry.Touch(true, false); } }
internal PwCustomIcon SetIconFromExecutable(string executable) { ExecutableIcon exeIcon = new ExecutableIcon(executable); PwCustomIcon icon = exeIcon.GetCustomIcon(); // Check for existing icons. if (!this.IconExists(icon)) { this.AddIconToDatabase(icon); } this.entry.CustomIconUuid = icon.Uuid; this.entry.Touch(true, false); return(icon); }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (requestCode == RequestCodePickImage && resultCode == Result.Ok) { try { var stream = ContentResolver.OpenInputStream(data.Data); var bitmap = BitmapFactory.DecodeStream(stream); stream.Close(); float maxSize = 128; using (MemoryStream ms = new MemoryStream()) { if ((bitmap.Width > maxSize) || (bitmap.Height > maxSize)) { float scale = Math.Min(maxSize / bitmap.Width, maxSize / bitmap.Height); var scaleWidth = (int)(bitmap.Width * scale); var scaleHeight = (int)(bitmap.Height * scale); var scaledBitmap = Bitmap.CreateScaledBitmap(bitmap, scaleWidth, scaleHeight, true); Bitmap newRectBitmap = Bitmap.CreateBitmap((int)maxSize, (int)maxSize, Bitmap.Config.Argb8888); Canvas c = new Canvas(newRectBitmap); c.DrawBitmap(scaledBitmap, (maxSize - scaledBitmap.Width) / 2.0f, (maxSize - scaledBitmap.Height) / 2.0f, null); bitmap = newRectBitmap; } ; bitmap.Compress(Bitmap.CompressFormat.Png, 90, ms); PwCustomIcon pwci = new PwCustomIcon(new PwUuid(true), ms.ToArray()); App.Kp2a.GetDb().KpDatabase.CustomIcons.Add(pwci); } var gridView = ((GridView)FindViewById(Resource.Id.IconGridView)); ((BaseAdapter)gridView.Adapter).NotifyDataSetInvalidated(); gridView.SmoothScrollToPosition(((BaseAdapter)gridView.Adapter).Count - 1); } catch (FileNotFoundException e) { e.PrintStackTrace(); } }
private void importRecord(TreeNode <Records.BaseRecord> currentNode, PwGroup pwGroupAddTo, PwDatabase pwDatabase, UserPrefs userPrefs) { Records.BaseRecord record = currentNode.AssociatedObject; if (record is Records.RegularFolderRecord) { PwGroup folder = (record as Records.RegularFolderRecord).CreatePwGroup(); if (folder != null) { pwGroupAddTo.AddGroup(folder, true); foreach (TreeNode <Records.BaseRecord> child in currentNode.Children) { importRecord(child, folder, pwDatabase, userPrefs); } } } else { Records.ItemRecord itemRecord = record as Records.ItemRecord; PwEntry entry = itemRecord.CreatePwEntry(pwDatabase, userPrefs); if (entry != null) { PwCustomIcon customIcon = itemRecord.GetPwCustomIcon(); if (customIcon != null) { if (!pwDatabase.CustomIcons.Exists(icon => icon.Uuid.Equals(customIcon.Uuid))) { pwDatabase.CustomIcons.Add(customIcon); } pwDatabase.UINeedsIconUpdate = true; } pwGroupAddTo.AddEntry(entry, true); } } }
public override void PopulateEntry(PwEntry pwEntry, PwDatabase pwDatabase, UserPrefs userPrefs) { base.PopulateEntry(pwEntry, pwDatabase, userPrefs); if (this.tags != null) { pwEntry.Tags.AddRange(this.tags); } if (this.faveIndex > 0 && !pwEntry.Tags.Contains(Properties.Strings.Tag_Favorite)) { pwEntry.Tags.Add(Properties.Strings.Tag_Favorite); } if (this.icon != null) { byte[] customIconData = null; try { using (MemoryStream originalIconStream = new MemoryStream(this.icon)) using (Bitmap originalIcon = new Bitmap(originalIconStream)) using (MemoryStream convertedIconStream = new MemoryStream()) { originalIcon.Save(convertedIconStream, ImageFormat.Png); customIconData = convertedIconStream.ToArray(); using (MD5 md5 = MD5.Create()) { PwUuid customIconUuid = new PwUuid(md5.ComputeHash(customIconData)); this.PwCustomIcon = new PwCustomIcon(customIconUuid, customIconData); pwEntry.CustomIconUuid = customIconUuid; } } } catch (ArgumentException) { // Image format is not supported or one of its dimensions is bigger than 65,535 } } }
/// <summary> /// Get original image (to get Original Width for example) /// </summary> public static Image GetOriginalImage(PwCustomIcon icon) { Image result = null; EnsureInitialize(); if (METHOD_GetImage_NoParameters != null) { result = METHOD_GetImage_NoParameters.Invoke( icon, new Object[] { }) as Image; } else { result = icon.GetType().GetProperty("Image").GetValue( icon, null) as Image; } return(result); }
private void OnCustomIconsAfterLabelEdit(object sender, LabelEditEventArgs e) { string strNew = e.Label; int iItem = e.Item; e.CancelEdit = true; if (strNew == null) { return; // Edit aborted (Esc) } if (strNew == MultipleValuesEx.CueString) { return; } if (Regex.IsMatch(strNew, "^\\d+$")) { strNew = string.Empty; } PwCustomIcon ci = (m_lvCustomIcons.Items[iItem].Tag as PwCustomIcon); if (ci == null) { Debug.Assert(false); return; } if (ci.Name != strNew) { ci.Name = strNew; ci.LastModificationTime = DateTime.UtcNow; m_pd.UINeedsIconUpdate = true; m_pd.Modified = true; } RecreateCustomIconList(ci.Uuid); EnableControlsEx(); }
/// <summary> /// Scale Image to fit dimensions (width x height). <br/> /// If version of keepass >= 2.28, use KeePass.UI.ScaleIntX/Y methods /// If version of keepass >= 2.29, use GetImage to get HighDPI definition /// </summary> public static Image GetScaledImage(PwCustomIcon icon, int width, int height) { Image result = null; EnsureInitialize(); if (METHOD_GetImage_TwoParameters != null) { result = METHOD_GetImage_TwoParameters.Invoke( icon, new Object[] { ScaleIntX(width), ScaleIntY(height) }) as Image; } else { result = ResizedImage( icon.GetType().GetProperty("Image").GetValue( icon, null) as Image, ScaleIntX(width), ScaleIntY(height)); } return(result); }
private static void SaveImageFile(PwCustomIcon ci, string strFile) { if ((ci == null) || string.IsNullOrEmpty(strFile)) { Debug.Assert(false); return; } try { Image img = ci.GetImage(); if (img == null) { Debug.Assert(false); return; } // string strExt = UrlUtil.GetExtension(strFile); ImageFormat fmt = ImageFormat.Png; // if(strExt.Equals("ico", StrUtil.CaseIgnoreCmp)) fmt = ImageFormat.Icon; img.Save(strFile, fmt); } catch (Exception ex) { MessageService.ShowWarning(strFile, ex); } }
/// <summary> /// Copies the custom icons required for this group to the target database. /// </summary> /// <param name="targetDatabase">The target database where to add the icons.</param> /// <param name="sourceDatabase">The source database where to get the icons from.</param> /// <param name="sourceGroup">The source group which icon should be copied (if it is custom).</param> private static void HandleCustomIcon(PwDatabase targetDatabase, PwDatabase sourceDatabase, PwGroup sourceGroup) { // Does the group not use a custom icon or is it already in the target database if (sourceGroup.CustomIconUuid.Equals(PwUuid.Zero) || targetDatabase.GetCustomIconIndex(sourceGroup.CustomIconUuid) != -1) { return; } // Check if the custom icon really is in the source database int iconIndex = sourceDatabase.GetCustomIconIndex(sourceGroup.CustomIconUuid); if (iconIndex < 0 || iconIndex > sourceDatabase.CustomIcons.Count - 1) { MessageService.ShowWarning("Can't locate custom icon (" + sourceGroup.CustomIconUuid.ToHexString() + ") for group " + sourceGroup.Name); } // Get the custom icon from the source database PwCustomIcon customIcon = sourceDatabase.CustomIcons[iconIndex]; // Copy the custom icon to the target database targetDatabase.CustomIcons.Add(customIcon); }
/// <summary> /// Copies the custom icons required for this group to the target database. /// </summary> /// <param name="targetDatabase">The target database where to add the icons.</param> /// <param name="sourceDb">The source database where to get the icons from.</param> /// <param name="entry">The entry which icon should be copied (if it is custom).</param> private static void HandleCustomIcon(PwDatabase targetDatabase, PwDatabase sourceDb, PwEntry entry) { // Does the entry not use a custom icon or is it already in the target database if (entry.CustomIconUuid.Equals(PwUuid.Zero) || targetDatabase.GetCustomIconIndex(entry.CustomIconUuid) != -1) { return; } // Check if the custom icon really is in the source database int iconIndex = sourceDb.GetCustomIconIndex(entry.CustomIconUuid); if (iconIndex < 0 || iconIndex > sourceDb.CustomIcons.Count - 1) { MessageService.ShowWarning("Can't locate custom icon (" + entry.CustomIconUuid.ToHexString() + ") for entry " + entry.Strings.ReadSafe("Title")); } // Get the custom icon from the source database PwCustomIcon customIcon = sourceDb.CustomIcons[iconIndex]; // Copy the custom icon to the target database targetDatabase.CustomIcons.Add(customIcon); }
public static bool WriteEntries(Stream msOutput, PwDatabase pdContext, PwEntry[] vEntries) { if (msOutput == null) { Debug.Assert(false); return(false); } // pdContext may be null if (vEntries == null) { Debug.Assert(false); return(false); } /* KdbxFile f = new KdbxFile(pwDatabase); * f.m_format = KdbxFormat.PlainXml; * * XmlTextWriter xtw = null; * try { xtw = new XmlTextWriter(msOutput, StrUtil.Utf8); } * catch(Exception) { Debug.Assert(false); return false; } * if(xtw == null) { Debug.Assert(false); return false; } * * f.m_xmlWriter = xtw; * * xtw.Formatting = Formatting.Indented; * xtw.IndentChar = '\t'; * xtw.Indentation = 1; * * xtw.WriteStartDocument(true); * xtw.WriteStartElement(ElemRoot); * * foreach(PwEntry pe in vEntries) * f.WriteEntry(pe, false); * * xtw.WriteEndElement(); * xtw.WriteEndDocument(); * * xtw.Flush(); * xtw.Close(); * return true; */ PwDatabase pd = new PwDatabase(); pd.New(new IOConnectionInfo(), new CompositeKey()); PwGroup pg = pd.RootGroup; if (pg == null) { Debug.Assert(false); return(false); } foreach (PwEntry pe in vEntries) { PwUuid pu = pe.CustomIconUuid; if (!pu.Equals(PwUuid.Zero) && (pd.GetCustomIconIndex(pu) < 0)) { int i = -1; if (pdContext != null) { i = pdContext.GetCustomIconIndex(pu); } if (i >= 0) { PwCustomIcon ci = pdContext.CustomIcons[i]; pd.CustomIcons.Add(ci); } else { Debug.Assert(pdContext == null); } } PwEntry peCopy = pe.CloneDeep(); pg.AddEntry(peCopy, true); } KdbxFile f = new KdbxFile(pd); f.Save(msOutput, null, KdbxFormat.PlainXml, null); return(true); }
/// <summary> /// A PwDatabase extension method that creates a website entry. /// </summary> /// <param name="pd">The database to act on</param> /// <param name="group">The group to insert new entries into</param> /// <param name="host">The host</param> /// <param name="username">The username</param> /// <param name="password">The password</param> /// <param name="extractTitle">true to extract the title of the host</param> /// <param name="extractIcon">true to extract icon of the host</param> /// <param name="logger">The logger</param> public static void CreateWebsiteEntry(this PwDatabase pd, PwGroup group, string host, string username, string password, bool extractTitle, bool extractIcon, IStatusLogger logger) { Contract.Requires(group != null); Contract.Requires(host != null); Contract.Requires(username != null); Contract.Requires(password != null); Contract.Requires(logger != null); logger.SetText(string.Format("{0} - {1}", username, host), LogStatusType.Info); var pe = new PwEntry(true, true); group.AddEntry(pe, true); pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle, host)); pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pd.MemoryProtection.ProtectUserName, username)); pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pd.MemoryProtection.ProtectPassword, password)); pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pd.MemoryProtection.ProtectUrl, host)); if (!string.IsNullOrEmpty(host) && (extractTitle || extractIcon)) { try { string content; using (var client = new WebClientEx()) { content = client.DownloadString(host); var document = new HtmlDocument(); document.LoadHtml(content); if (extractTitle) { var title = document.DocumentNode.SelectSingleNode("/html/head/title"); if (title != null) { pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle, HttpUtility.HtmlDecode(title.InnerText.Trim()))); } } if (extractIcon) { string iconUrl = null; foreach (var prio in new string[] { "shortcut icon", "apple-touch-icon", "icon" }) { //iconUrl = document.DocumentNode.SelectNodes("/html/head/link").Where(l => prio == l.Attributes["rel"]?.Value).LastOrDefault()?.Attributes["href"]?.Value; var node = document.DocumentNode.SelectNodes("/html/head/link").Where(l => l.GetAttributeValue("rel", string.Empty) == prio).LastOrDefault(); if (node != null) { iconUrl = node.GetAttributeValue("href", string.Empty); } if (!string.IsNullOrEmpty(iconUrl)) { break; } } if (!string.IsNullOrEmpty(iconUrl)) { if (!iconUrl.StartsWith("http://") && !iconUrl.StartsWith("https://")) { iconUrl = host.TrimEnd('/') + '/' + iconUrl.TrimStart('/'); } using (var s = client.OpenRead(iconUrl)) { var icon = Image.FromStream(s); if (icon.Width > 16 || icon.Height > 16) { icon = icon.GetThumbnailImage(16, 16, null, IntPtr.Zero); } using (var ms = new MemoryStream()) { icon.Save(ms, ImageFormat.Png); var data = ms.ToArray(); foreach (var item in pd.CustomIcons) { if (KeePassLib.Utility.MemUtil.ArraysEqual(data, item.ImageDataPng)) { pe.CustomIconUuid = item.Uuid; return; } } var pwci = new PwCustomIcon(new PwUuid(true), data); pd.CustomIcons.Add(pwci); pe.CustomIconUuid = pwci.Uuid; } } pd.UINeedsIconUpdate = true; } } } } catch { } } }
private void OnBtnCustomAdd(object sender, EventArgs e) { string strAllSupportedFilter = KPRes.AllSupportedFiles + @" (*.bmp; *.emf; *.gif; *.ico; *.jpg; *.jpe; *.jpeg; *.jfif; *.jfi; *.jif; *.png; *.tif; *.tiff; *.wmf)" + @"|*.bmp;*.emf;*.gif;*.ico;*.jpg;*.jpe;*.jpeg;*.jfif;*.jfi;*.jif;*.png;*.tif;*.tiff;*.wmf"; StringBuilder sbFilter = new StringBuilder(); sbFilter.Append(strAllSupportedFilter); AddFileType(sbFilter, "*.bmp", "Windows Bitmap (*.bmp)"); AddFileType(sbFilter, "*.emf", "Windows Enhanced Metafile (*.emf)"); AddFileType(sbFilter, "*.gif", "Graphics Interchange Format (*.gif)"); AddFileType(sbFilter, "*.ico", "Windows Icon (*.ico)"); AddFileType(sbFilter, "*.jpg;*.jpe;*.jpeg;*.jfif;*.jfi;*.jif", "JPEG (*.jpg; *.jpe; *.jpeg; *.jfif; *.jfi; *.jif)"); AddFileType(sbFilter, "*.png", "Portable Network Graphics (*.png)"); AddFileType(sbFilter, "*.tif;*.tiff", "Tagged Image File Format (*.tif; *.tiff)"); AddFileType(sbFilter, "*.wmf", "Windows Metafile (*.wmf)"); sbFilter.Append(@"|" + KPRes.AllFiles + @" (*.*)|*.*"); OpenFileDialogEx ofd = UIUtil.CreateOpenFileDialog(KPRes.ImportFileTitle, sbFilter.ToString(), 1, null, true, AppDefs.FileDialogContext.Import); if (ofd.ShowDialog() == DialogResult.OK) { bool bSelectLastIcon = false; foreach (string strFile in ofd.FileNames) { bool bUnsupportedFormat = false; try { if (!File.Exists(strFile)) { throw new FileNotFoundException(); } // Image img = Image.FromFile(strFile); // Image img = Image.FromFile(strFile, false); // Image img = Bitmap.FromFile(strFile); // Bitmap img = new Bitmap(strFile); // Image img = Image.FromFile(strFile); byte[] pb = File.ReadAllBytes(strFile); // MemoryStream msSource = new MemoryStream(pb, false); // Image img = Image.FromStream(msSource); // msSource.Close(); Image img = GfxUtil.LoadImage(pb); MemoryStream ms = new MemoryStream(); if ((img.Width == 16) && (img.Height == 16)) { img.Save(ms, ImageFormat.Png); } else { // Image imgNew = new Bitmap(img, new Size(16, 16)); Bitmap imgSc = UIUtil.CreateScaledImage(img, 16, 16); imgSc.Save(ms, ImageFormat.Png); imgSc.Dispose(); } img.Dispose(); PwCustomIcon pwci = new PwCustomIcon(new PwUuid(true), ms.ToArray()); m_pwDatabase.CustomIcons.Add(pwci); ms.Close(); m_pwDatabase.UINeedsIconUpdate = true; m_pwDatabase.Modified = true; bSelectLastIcon = true; } catch (ArgumentException) { bUnsupportedFormat = true; } catch (System.Runtime.InteropServices.ExternalException) { bUnsupportedFormat = true; } catch (Exception exImg) { MessageService.ShowWarning(strFile, exImg); } if (bUnsupportedFormat) { MessageService.ShowWarning(strFile, KPRes.ImageFormatFeatureUnsupported); } } RecreateCustomIconList(bSelectLastIcon); } EnableControlsEx(); }