use std::borrow::Borrow;
use std::fmt;
use std::str::FromStr;
use crate::desktop::DesktopFileType;
use crate::entry::{AnnotatedEntry, Entry};
use crate::error::{GroupError, MutationValueError, ValueError};
use crate::format_comment;
use crate::key::{DesktopType, LocaleString};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyUniqueness {
Unique,
Duplicate,
Missing,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GroupName(String);
impl GroupName {
pub const DESKTOP_ENTRY: &'static str = "Desktop Entry";
pub fn try_new(name: impl Into<String>) -> Result<Self, GroupError> {
Self::try_from(name.into())
}
#[inline]
#[must_use]
pub fn action_identifier(&self) -> Option<&str> {
self.as_str()
.strip_prefix("Desktop Action ")
.filter(|action| !action.is_empty())
}
#[inline]
#[must_use]
pub fn action_group_name(identifier: impl AsRef<str>) -> String {
format!("Desktop Action {}", identifier.as_ref())
}
#[inline]
#[must_use]
pub fn is_action(&self) -> bool {
self.action_identifier().is_some()
}
#[inline]
#[must_use]
pub fn into_inner(self) -> String {
self.0
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[inline]
#[must_use]
pub fn is_desktop_entry(&self) -> bool {
self.as_str() == Self::DESKTOP_ENTRY
}
}
impl AsRef<str> for GroupName {
fn as_ref(&self) -> &str {
&self.0
}
}
impl From<GroupName> for String {
fn from(value: GroupName) -> Self {
value.0
}
}
impl<'a> From<&'a GroupName> for &'a str {
fn from(value: &'a GroupName) -> Self {
value.0.as_str()
}
}
impl Default for GroupName {
fn default() -> Self {
Self(String::from("Desktop Entry"))
}
}
impl fmt::Display for GroupName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[{}]", self.0)
}
}
impl TryFrom<&str> for GroupName {
type Error = GroupError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
GroupName::try_from(value.to_owned())
}
}
impl TryFrom<String> for GroupName {
type Error = GroupError;
fn try_from(name: String) -> Result<Self, Self::Error> {
if name.is_empty() {
return Err(GroupError::EmptyGroupName);
}
if !is_valid_group_name(&name) {
return Err(GroupError::InvalidGroupName);
}
Ok(Self(name))
}
}
impl FromStr for GroupName {
type Err = GroupError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let inner = value
.strip_prefix('[')
.and_then(|s| s.strip_suffix(']'))
.ok_or(GroupError::InvalidGroupHeader)?;
GroupName::try_from(inner.to_owned())
}
}
impl Borrow<str> for GroupName {
fn borrow(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntryGroup {
pub(crate) group_name: GroupName,
pub(crate) entries: Vec<AnnotatedEntry>,
pub(crate) comment: String,
}
impl EntryGroup {
#[inline]
#[must_use]
pub fn new(group_name: GroupName) -> Self {
Self {
group_name,
entries: Vec::new(),
comment: String::new(),
}
}
#[inline]
#[must_use]
pub fn with_entry(group_name: GroupName, entry: AnnotatedEntry) -> Self {
let mut group = Self::new(group_name);
group.entries.push(entry);
group
}
#[inline]
#[must_use]
pub fn required_group(name: LocaleString, file_type: DesktopFileType) -> Self {
let desktop_type = match file_type {
DesktopFileType::Application => DesktopType::Application,
DesktopFileType::Link(_) => DesktopType::Link,
DesktopFileType::Directory => DesktopType::Directory,
};
let mut entries = vec![AnnotatedEntry::new(Entry::Type(desktop_type))];
if let DesktopFileType::Link(url) = file_type {
entries.push(AnnotatedEntry::new(Entry::URL(url)));
}
entries.push(AnnotatedEntry::new(Entry::Name(name)));
Self {
group_name: GroupName::default(),
comment: String::new(),
entries,
}
}
#[inline]
#[must_use]
pub fn comment(&self) -> &str {
&self.comment
}
#[inline]
pub fn append_comment(&mut self, string: &str) -> &mut Self {
format_comment(&mut self.comment, string);
self
}
#[must_use]
pub fn has_name(&self, name: &str) -> bool {
self.group_name.as_str() == name
}
#[inline]
#[must_use]
pub fn contains(&self, key: impl AsRef<str>) -> bool {
let key = key.as_ref();
self.entries.iter().any(|ae| ae.key_name() == key)
}
#[inline]
#[must_use]
pub fn has_type_and_name(&self) -> bool {
let mut has_type = false;
let mut has_name = false;
for ae in &self.entries {
match &ae.entry {
Entry::Type(_) => has_type = true,
Entry::Name(_) => has_name = true,
_ => {}
}
if has_type && has_name {
return true;
}
}
has_type && has_name
}
#[must_use]
#[inline]
pub fn entry_type(&self) -> Option<DesktopType> {
self.entries.iter().find_map(|ae| {
if let Entry::Type(dt) = &ae.entry {
Some(*dt)
} else {
None
}
})
}
#[inline]
#[must_use]
pub fn key_index(&self, key: impl AsRef<str>) -> Option<usize> {
let key = key.as_ref();
self.entries.iter().position(|ae| ae.key_name() == key)
}
#[inline]
pub fn entry(&self, key: impl AsRef<str>) -> Result<&AnnotatedEntry, GroupError> {
let key = key.as_ref();
self.entries
.iter()
.find(|ae| ae.key_name() == key)
.ok_or(GroupError::EntryNotFound)
}
#[inline]
#[must_use]
pub fn group_name(&self) -> &GroupName {
&self.group_name
}
#[inline]
#[must_use]
pub fn entries(&self) -> &[AnnotatedEntry] {
&self.entries
}
#[inline]
#[must_use]
pub fn key_status(&self, key: impl AsRef<str>) -> KeyUniqueness {
let key = key.as_ref();
match self
.entries
.iter()
.filter(|ae| ae.key_name() == key)
.take(2)
.count()
{
0 => KeyUniqueness::Missing,
1 => KeyUniqueness::Unique,
_ => KeyUniqueness::Duplicate,
}
}
#[inline]
#[must_use = "Adding an annotated entry can fail; you must handle the Err case."]
pub fn try_add(&mut self, ad_entry: AnnotatedEntry) -> Result<(), GroupError> {
let key = ad_entry.key_name();
if ad_entry.is_actions_entry() {
return Err(GroupError::AddActionsEntry);
}
if self.entries.iter().any(|ae| ae.key_name() == key) {
return Err(GroupError::EntryExists);
}
self.entries.push(ad_entry);
Ok(())
}
#[inline]
#[must_use = "Adding an annotated entry can fail; you must handle the Err case."]
pub(crate) fn try_add_any(&mut self, ad_entry: AnnotatedEntry) -> Result<(), GroupError> {
let key = ad_entry.key_name();
if self.entries.iter().any(|ae| ae.key_name() == key) {
return Err(GroupError::EntryExists);
}
self.entries.push(ad_entry);
Ok(())
}
#[inline]
#[must_use = "Adding an entry can fail; you must handle the Err case."]
pub fn try_add_entry(&mut self, entry: Entry) -> Result<(), GroupError> {
let key = entry.key_name();
if self.entries.iter().any(|ae| ae.key_name() == key) {
return Err(GroupError::EntryExists);
}
let ad_entry = AnnotatedEntry::new(entry);
self.entries.push(ad_entry);
Ok(())
}
#[inline]
pub fn try_insert(
&mut self,
key: impl AsRef<str>,
entry: AnnotatedEntry,
) -> Result<(), GroupError> {
let key = key.as_ref();
let entry_key = entry.key_name();
let mut insert_index = None;
for (i, ae) in self.entries.iter().enumerate() {
if ae.key_name() == entry_key {
return Err(GroupError::EntryExists);
}
if ae.key_name() == key {
if insert_index.is_some() {
return Err(GroupError::DuplicatePosition);
}
insert_index = Some(i);
}
}
let Some(index) = insert_index else {
return Err(GroupError::PositionNotFound);
};
self.entries.insert(index, entry);
Ok(())
}
#[inline]
pub(crate) fn remove(&mut self, index: usize) -> AnnotatedEntry {
self.entries.remove(index)
}
pub fn value<T>(&self, key: impl AsRef<str>) -> Result<&T, GroupError>
where
for<'a> &'a Entry: TryInto<&'a T, Error = ValueError>,
{
let index = self.key_index(key).ok_or(GroupError::EntryNotFound)?;
self.entries[index].value().map_err(GroupError::Entry)
}
pub fn value_mut<T>(&mut self, key: impl AsRef<str>) -> Result<&mut T, GroupError>
where
for<'a> &'a mut Entry: TryInto<&'a mut T, Error = MutationValueError>,
{
let index = self.key_index(key).ok_or(GroupError::EntryNotFound)?;
self.entries[index].value_mut().map_err(GroupError::Entry)
}
#[inline]
pub fn iter(&self) -> std::slice::Iter<'_, AnnotatedEntry> {
<&Self as IntoIterator>::into_iter(self)
}
}
impl Default for EntryGroup {
fn default() -> Self {
Self::new(GroupName::default())
}
}
impl AsRef<[AnnotatedEntry]> for EntryGroup {
fn as_ref(&self) -> &[AnnotatedEntry] {
&self.entries
}
}
impl AsRef<GroupName> for EntryGroup {
fn as_ref(&self) -> &GroupName {
&self.group_name
}
}
impl fmt::Display for EntryGroup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}{}{}",
self.comment,
if self.comment.is_empty() || self.comment.ends_with('\n') {
""
} else {
"\n"
},
self.group_name,
)?;
for ae in &self.entries {
write!(f, "\n{ae}")?;
}
Ok(())
}
}
impl<'a> IntoIterator for &'a EntryGroup {
type Item = &'a AnnotatedEntry;
type IntoIter = std::slice::Iter<'a, AnnotatedEntry>;
fn into_iter(self) -> Self::IntoIter {
self.entries.iter()
}
}
impl Borrow<GroupName> for EntryGroup {
fn borrow(&self) -> &GroupName {
&self.group_name
}
}
#[inline]
fn is_valid_group_name(group_name: &str) -> bool {
!group_name.is_empty()
&& group_name
.bytes()
.all(|b| !b.is_ascii_control() && b != b'[' && b != b']')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn group_lookup_and_removal_use_key_names() {
let mut group = EntryGroup::with_entry(
GroupName::try_from("Desktop Action Open").unwrap(),
AnnotatedEntry::new(Entry::Name("Open".try_into().unwrap())),
);
assert_eq!(
group.entry("Name").unwrap().entry().to_string(),
"Name=Open"
);
assert_eq!(group.remove(0).key_name(), "Name");
assert_eq!(group.entry("Name"), Err(GroupError::EntryNotFound));
}
}