use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;
use crate::desktop::DesktopFileType;
use crate::error::{
AppendKeyValueError, EntryError, MutationValueError, ParseEntryError, ParseEntryValueError,
ParseKeyError, ValueError,
};
use crate::format_comment;
use crate::key::{
Bool, DesktopType, EntryKeys, EscapedString, EscapedStrings, ExtensionEntry, IconString,
LocaleString, LocaleStrings, LocalizedEntry, Version,
};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Entry {
Type(DesktopType),
Version(Version),
Name(LocaleString),
GenericName(LocaleString),
NoDisplay(Bool),
Hidden(Bool),
OnlyShowIn(EscapedStrings),
NotShowIn(EscapedStrings),
Comment(LocaleString),
Icon(IconString),
Keywords(LocaleStrings),
Exec(EscapedString),
TryExec(EscapedString),
Path(EscapedString),
Terminal(Bool),
DBusActivatable(Bool),
StartupNotify(Bool),
StartupWMClass(EscapedString),
Actions(EscapedStrings),
Categories(EscapedStrings),
MimeType(EscapedStrings),
Implements(EscapedStrings),
URL(EscapedString),
PrefersNonDefaultGPU(Bool),
SingleMainWindow(Bool),
Localized(LocalizedEntry),
Extension(ExtensionEntry),
}
impl Entry {
#[inline]
#[must_use]
pub fn key_name(&self) -> Cow<'_, str> {
match self {
Self::Type(_) => Cow::Borrowed("Type"),
Self::Version(_) => Cow::Borrowed("Version"),
Self::Name(_) => Cow::Borrowed("Name"),
Self::GenericName(_) => Cow::Borrowed("GenericName"),
Self::NoDisplay(_) => Cow::Borrowed("NoDisplay"),
Self::Hidden(_) => Cow::Borrowed("Hidden"),
Self::OnlyShowIn(_) => Cow::Borrowed("OnlyShowIn"),
Self::NotShowIn(_) => Cow::Borrowed("NotShowIn"),
Self::Comment(_) => Cow::Borrowed("Comment"),
Self::Icon(_) => Cow::Borrowed("Icon"),
Self::Keywords(_) => Cow::Borrowed("Keywords"),
Self::Exec(_) => Cow::Borrowed("Exec"),
Self::TryExec(_) => Cow::Borrowed("TryExec"),
Self::Path(_) => Cow::Borrowed("Path"),
Self::Terminal(_) => Cow::Borrowed("Terminal"),
Self::DBusActivatable(_) => Cow::Borrowed("DBusActivatable"),
Self::StartupNotify(_) => Cow::Borrowed("StartupNotify"),
Self::StartupWMClass(_) => Cow::Borrowed("StartupWMClass"),
Self::Actions(_) => Cow::Borrowed("Actions"),
Self::Categories(_) => Cow::Borrowed("Categories"),
Self::MimeType(_) => Cow::Borrowed("MimeType"),
Self::Implements(_) => Cow::Borrowed("Implements"),
Self::URL(_) => Cow::Borrowed("URL"),
Self::PrefersNonDefaultGPU(_) => Cow::Borrowed("PrefersNonDefaultGPU"),
Self::SingleMainWindow(_) => Cow::Borrowed("SingleMainWindow"),
Self::Localized(localized_entry) => Cow::Owned(format!(
"{}[{}]",
localized_entry.key(),
localized_entry.locale(),
)),
Self::Extension(extension_entry) => Cow::Borrowed(extension_entry.key()),
}
}
#[inline]
#[must_use]
pub const fn is_actions_entry(&self) -> bool {
matches!(self, Self::Actions(_))
}
#[inline]
#[must_use]
pub fn version_introduced(&self) -> Option<Version> {
let key = match self {
Self::Type(_) => EntryKeys::Type,
Self::Version(_) => EntryKeys::Version,
Self::Name(_) => EntryKeys::Name,
Self::GenericName(_) => EntryKeys::GenericName,
Self::NoDisplay(_) => EntryKeys::NoDisplay,
Self::Hidden(_) => EntryKeys::Hidden,
Self::OnlyShowIn(_) => EntryKeys::OnlyShowIn,
Self::NotShowIn(_) => EntryKeys::NotShowIn,
Self::Comment(_) => EntryKeys::Comment,
Self::Icon(_) => EntryKeys::Icon,
Self::Keywords(_) => EntryKeys::Keywords,
Self::Exec(_) => EntryKeys::Exec,
Self::TryExec(_) => EntryKeys::TryExec,
Self::Path(_) => EntryKeys::Path,
Self::Terminal(_) => EntryKeys::Terminal,
Self::DBusActivatable(_) => EntryKeys::DBusActivatable,
Self::StartupNotify(_) => EntryKeys::StartupNotify,
Self::StartupWMClass(_) => EntryKeys::StartupWMClass,
Self::Actions(_) => EntryKeys::Actions,
Self::Categories(_) => EntryKeys::Categories,
Self::MimeType(_) => EntryKeys::MimeType,
Self::Implements(_) => EntryKeys::Implements,
Self::URL(_) => EntryKeys::URL,
Self::PrefersNonDefaultGPU(_) => EntryKeys::PrefersNonDefaultGPU,
Self::SingleMainWindow(_) => EntryKeys::SingleMainWindow,
Self::Localized(localized) => localized.key(),
Self::Extension(_) => return None,
};
key.version_introduced()
}
#[inline]
pub fn value<T>(&self) -> Result<&T, EntryError>
where
for<'a> &'a Entry: TryInto<&'a T, Error = ValueError>,
{
self.try_into().map_err(EntryError::Value)
}
#[inline]
pub fn value_mut<T>(&mut self) -> Result<&mut T, EntryError>
where
for<'a> &'a mut Entry: TryInto<&'a mut T, Error = MutationValueError>,
{
self.try_into().map_err(EntryError::MutationValue)
}
#[inline]
fn try_with_standard_key(key: EntryKeys, value: &str) -> Result<Self, ParseEntryValueError> {
Ok(match key {
EntryKeys::Type => Self::Type(value.parse()?),
EntryKeys::Version => Self::Version(value.parse()?),
EntryKeys::Name => Self::Name(value.parse()?),
EntryKeys::GenericName => Self::GenericName(value.parse()?),
EntryKeys::NoDisplay => Self::NoDisplay(value.parse()?),
EntryKeys::Comment => Self::Comment(value.parse()?),
EntryKeys::Icon => Self::Icon(value.parse()?),
EntryKeys::Hidden => Self::Hidden(value.parse()?),
EntryKeys::OnlyShowIn => Self::OnlyShowIn(value.parse()?),
EntryKeys::NotShowIn => Self::NotShowIn(value.parse()?),
EntryKeys::DBusActivatable => Self::DBusActivatable(value.parse()?),
EntryKeys::TryExec => Self::TryExec(value.parse()?),
EntryKeys::Exec => Self::Exec(value.parse()?),
EntryKeys::Path => Self::Path(value.parse()?),
EntryKeys::Terminal => Self::Terminal(value.parse()?),
EntryKeys::Actions => Self::Actions(value.parse()?),
EntryKeys::MimeType => Self::MimeType(value.parse()?),
EntryKeys::Categories => Self::Categories(value.parse()?),
EntryKeys::Implements => Self::Implements(value.parse()?),
EntryKeys::Keywords => Self::Keywords(value.parse()?),
EntryKeys::StartupNotify => Self::StartupNotify(value.parse()?),
EntryKeys::StartupWMClass => Self::StartupWMClass(value.parse()?),
EntryKeys::URL => Self::URL(value.parse()?),
EntryKeys::PrefersNonDefaultGPU => Self::PrefersNonDefaultGPU(value.parse()?),
EntryKeys::SingleMainWindow => Self::SingleMainWindow(value.parse()?),
})
}
#[inline]
pub(crate) fn value_type(&self) -> &str {
match self {
Self::Type(_) => "DesktopType",
Self::Version(_) => "Version",
Self::Name(_) | Self::GenericName(_) | Self::Comment(_) => "LocaleString",
Self::NoDisplay(_)
| Self::Hidden(_)
| Self::Terminal(_)
| Self::DBusActivatable(_)
| Self::StartupNotify(_)
| Self::PrefersNonDefaultGPU(_)
| Self::SingleMainWindow(_) => "Bool",
Self::Keywords(_) => "LocaleStrings",
Self::Icon(_) => "IconString",
Self::Exec(_)
| Self::TryExec(_)
| Self::Path(_)
| Self::StartupWMClass(_)
| Self::URL(_) => "EscapedString",
Self::OnlyShowIn(_)
| Self::NotShowIn(_)
| Self::Actions(_)
| Self::Categories(_)
| Self::MimeType(_)
| Self::Implements(_) => "EscapedStrings",
Self::Localized(_) => "LocalizedEntry",
Self::Extension(_) => "ExtensionEntry",
}
}
}
impl TryFrom<&str> for Entry {
type Error = ParseEntryError;
fn try_from(line: &str) -> Result<Self, Self::Error> {
let (key, value) = line
.split_once('=')
.ok_or(ParseEntryError::MissingSeparator(line.to_owned()))?;
let key = key.trim_end();
let value = value.trim_start();
if key.is_empty() {
return Err(ParseEntryError::ParseKey(ParseKeyError::InvalidFormat));
}
if let Ok(key) = EntryKeys::from_str(key) {
return Ok(Self::try_with_standard_key(key, value)?);
}
if key.starts_with("X-") {
return Ok(Self::Extension(ExtensionEntry::try_from((key, value))?));
}
if key.contains(['[', ']']) {
return Ok(Self::Localized(LocalizedEntry::try_from((key, value))?));
}
Err(ParseEntryError::ParseKey(ParseKeyError::UnknownKey(
key.to_owned(),
)))
}
}
impl TryFrom<String> for Entry {
type Error = ParseEntryError;
fn try_from(line: String) -> Result<Self, Self::Error> {
Entry::try_from(line.as_str())
}
}
impl FromStr for Entry {
type Err = ParseEntryError;
#[inline]
fn from_str(line: &str) -> Result<Self, Self::Err> {
Self::try_from(line)
}
}
impl fmt::Display for Entry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Type(dt) => write!(f, "Type={dt}"),
Self::Version(v) => write!(f, "Version={v}"),
Self::Name(s) => write!(f, "Name={s}"),
Self::GenericName(s) => write!(f, "GenericName={s}"),
Self::NoDisplay(b) => write!(f, "NoDisplay={b}"),
Self::Hidden(b) => write!(f, "Hidden={b}"),
Self::OnlyShowIn(v) => write!(f, "OnlyShowIn={v}"),
Self::NotShowIn(v) => write!(f, "NotShowIn={v}"),
Self::Comment(s) => write!(f, "Comment={s}"),
Self::Icon(i) => write!(f, "Icon={i}"),
Self::Keywords(v) => write!(f, "Keywords={v}"),
Self::Exec(s) => write!(f, "Exec={s}"),
Self::TryExec(s) => write!(f, "TryExec={s}"),
Self::Path(s) => write!(f, "Path={s}"),
Self::Terminal(b) => write!(f, "Terminal={b}"),
Self::DBusActivatable(b) => write!(f, "DBusActivatable={b}"),
Self::StartupNotify(b) => write!(f, "StartupNotify={b}"),
Self::StartupWMClass(s) => write!(f, "StartupWMClass={s}"),
Self::Actions(v) => write!(f, "Actions={v}"),
Self::Categories(v) => write!(f, "Categories={v}"),
Self::MimeType(v) => write!(f, "MimeType={v}"),
Self::Implements(v) => write!(f, "Implements={v}"),
Self::URL(s) => write!(f, "URL={s}"),
Self::PrefersNonDefaultGPU(b) => write!(f, "PrefersNonDefaultGPU={b}"),
Self::SingleMainWindow(b) => write!(f, "SingleMainWindow={b}"),
Self::Localized(localized_entry) => write!(
f,
"{}[{}]={}",
localized_entry.key(),
localized_entry.locale(),
localized_entry.value(),
),
Self::Extension(extension_entry) => {
write!(f, "{}={}", extension_entry.key(), extension_entry.value())
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnnotatedEntry {
pub(crate) entry: Entry,
pub(crate) comment: String,
}
impl AnnotatedEntry {
#[inline]
#[must_use]
pub fn new(entry: Entry) -> Self {
Self {
entry,
comment: String::new(),
}
}
#[inline]
#[must_use]
pub const fn is_actions_entry(&self) -> bool {
self.entry.is_actions_entry()
}
#[inline]
pub(crate) fn from_parsed(entry: Entry, comment: String) -> Self {
Self { entry, comment }
}
#[inline]
#[must_use]
pub fn entry(&self) -> &Entry {
&self.entry
}
#[inline]
#[must_use]
pub fn key_name(&self) -> Cow<'_, str> {
self.entry.key_name()
}
#[inline]
#[must_use]
pub fn version_introduced(&self) -> Option<Version> {
self.entry.version_introduced()
}
#[inline]
#[must_use]
pub fn comment(&self) -> &str {
&self.comment
}
#[inline]
pub fn append_comment(&mut self, text: &str) {
format_comment(&mut self.comment, text);
}
#[inline]
pub fn clear_comment(&mut self) {
self.comment.clear();
}
#[inline]
pub fn try_append<T>(&mut self, value: T) -> Result<(), AppendKeyValueError>
where
T: AppendValue,
{
value.append_to(&mut self.entry)?;
Ok(())
}
#[inline]
pub fn value<T>(&self) -> Result<&T, EntryError>
where
for<'a> &'a Entry: TryInto<&'a T, Error = ValueError>,
{
self.entry.value()
}
pub fn value_mut<T>(&mut self) -> Result<&mut T, EntryError>
where
for<'a> &'a mut Entry: TryInto<&'a mut T, Error = MutationValueError>,
{
(&mut self.entry)
.try_into()
.map_err(EntryError::MutationValue)
}
}
impl From<Entry> for AnnotatedEntry {
fn from(entry: Entry) -> Self {
Self {
entry,
comment: String::new(),
}
}
}
impl fmt::Display for AnnotatedEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if !self.comment.is_empty() {
write!(f, "{}", self.comment)?;
if !self.comment.ends_with('\n') {
writeln!(f)?;
}
}
write!(f, "{}", self.entry)
}
}
impl From<DesktopFileType> for AnnotatedEntry {
fn from(file_type: DesktopFileType) -> Self {
let dt = match file_type {
DesktopFileType::Application => DesktopType::Application,
DesktopFileType::Link(_) => DesktopType::Link,
DesktopFileType::Directory => DesktopType::Directory,
};
AnnotatedEntry::new(Entry::Type(dt))
}
}
mod private {
pub trait Sealed {}
}
pub trait AppendValue: private::Sealed {
fn append_to(self, entry: &mut Entry) -> Result<(), AppendKeyValueError>;
}
impl private::Sealed for EscapedString {}
impl AppendValue for EscapedString {
fn append_to(self, entry: &mut Entry) -> Result<(), AppendKeyValueError> {
match entry {
Entry::Actions(v)
| Entry::OnlyShowIn(v)
| Entry::NotShowIn(v)
| Entry::MimeType(v)
| Entry::Categories(v)
| Entry::Implements(v) => {
v.push(self);
Ok(())
}
_ => Err(AppendKeyValueError::NotEscapedStringList),
}
}
}
impl private::Sealed for LocaleString {}
impl AppendValue for LocaleString {
fn append_to(self, entry: &mut Entry) -> Result<(), AppendKeyValueError> {
match entry {
Entry::Keywords(v) => {
v.push(self);
Ok(())
}
_ => Err(AppendKeyValueError::NotLocaleStringList),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_annotated_entry_value_mut() {
let mut annotated = AnnotatedEntry::new(Entry::Terminal(Bool::from(false)));
if let Ok(b) = annotated.value_mut() {
*b = Bool::from(true);
}
assert_eq!(annotated.entry, Entry::Terminal(Bool::from(true)));
}
}