use std::fmt;
use std::fs;
use std::path::Path;
use std::str::FromStr;
use crate::entry::{AnnotatedEntry, Entry};
use crate::entry_group::{EntryGroup, GroupName};
use crate::error::{Error, GroupError, ParseFileDesktopError};
use crate::format_comment;
use crate::key::{DesktopType, EntryKeys, EscapedString, EscapedStrings, LocaleString};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DesktopFileType {
Application,
Link(EscapedString),
Directory,
}
impl DesktopFileType {
const APPLICATION: &str = "Application";
const LINK: &str = "Link";
const DIRECTORY: &str = "Directory";
}
impl fmt::Display for DesktopFileType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
Self::Application => Self::APPLICATION,
Self::Link(_) => Self::LINK,
Self::Directory => Self::DIRECTORY,
}
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DesktopFile {
entry_groups: Vec<EntryGroup>,
comment: String,
}
impl DesktopFile {
#[inline]
#[must_use]
pub fn new(name: LocaleString, file_type: DesktopFileType) -> Self {
Self {
entry_groups: vec![EntryGroup::required_group(name, file_type)],
comment: String::new(),
}
}
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
let content = fs::read_to_string(path)?;
Ok(Self::from_str(&content)?)
}
#[must_use]
#[inline]
pub fn comment(&self) -> &str {
&self.comment
}
pub fn contains(&self, group: impl AsRef<str>) -> bool {
let group = group.as_ref();
self.entry_groups
.iter()
.any(|g| g.group_name.as_str() == group)
}
#[must_use]
#[inline]
pub fn contains_extending_key(&self) -> bool {
self.entry_groups()
.iter()
.flatten()
.any(|ae| ae.key_name().starts_with("X-"))
}
#[inline]
#[must_use]
pub fn has_actions_entry(&self) -> bool {
self.group(GroupName::DESKTOP_ENTRY)
.is_ok_and(|group| group.entry(EntryKeys::Actions).is_ok())
}
#[must_use]
#[inline]
pub fn has_required_keys(&self) -> bool {
if let Ok(group) = self.group(GroupName::DESKTOP_ENTRY)
&& group.has_type_and_name()
{
if let Some(entry_type) = group.entry_type() {
return match entry_type {
DesktopType::Application | DesktopType::Directory => true,
DesktopType::Link => group.contains(EntryKeys::URL),
};
}
}
false
}
#[inline]
#[must_use]
pub fn has_associated_action_groups(&self) -> bool {
let Ok(group) = self.group(GroupName::DESKTOP_ENTRY) else {
return false;
};
let Ok(actions) = group.value::<EscapedStrings>(EntryKeys::Actions) else {
return false;
};
actions
.iter()
.all(|action| self.contains(GroupName::action_group_name(action)))
}
#[inline]
#[must_use]
pub fn is_actions_consistent(&self) -> bool {
let action_groups = self
.entry_groups
.iter()
.filter_map(|group| group.group_name().action_identifier())
.collect::<Vec<_>>();
let Ok(group) = self.group(GroupName::default()) else {
return action_groups.is_empty();
};
let Ok(actions) = group.value::<EscapedStrings>(EntryKeys::Actions) else {
return action_groups.is_empty();
};
actions
.iter()
.all(|action| self.contains(GroupName::action_group_name(action).as_str()))
&& action_groups
.iter()
.all(|identifier| actions.iter().any(|action| action.as_ref() == *identifier))
}
#[inline]
pub fn group(&self, name: impl AsRef<str>) -> Result<&EntryGroup, Error> {
let name = name.as_ref();
self.entry_groups
.iter()
.find(|group| group.group_name().as_str() == name)
.ok_or(Error::EntryGroupNotFound)
}
#[must_use]
#[inline]
pub fn entry_groups(&self) -> &[EntryGroup] {
&self.entry_groups
}
#[inline]
#[must_use]
pub fn group_index(&self, group_name: impl AsRef<str>) -> Option<usize> {
let group_name = group_name.as_ref();
self.entry_groups
.iter()
.position(|group| group.group_name.as_str() == group_name)
}
#[inline]
pub fn group_comment(&self, name: &str) -> Result<&str, Error> {
Ok(self.group(name)?.comment())
}
fn group_mut(&mut self, name: impl AsRef<str>) -> Result<&mut EntryGroup, Error> {
let name = name.as_ref();
self.entry_groups
.iter_mut()
.find(|group| group.group_name.as_str() == name)
.ok_or(Error::EntryGroupNotFound)
}
#[inline]
pub fn try_add_group(&mut self, group: EntryGroup) -> Result<&mut Self, Error> {
if self.contains(group.group_name()) {
return Err(Error::EntryGroupExists);
}
if group.group_name().is_action() {
return Err(Error::AddActionGroup);
}
self.entry_groups.push(group);
Ok(self)
}
#[inline]
fn try_add_any_group(&mut self, group: EntryGroup) -> Result<&mut Self, Error> {
if self.contains(group.group_name()) {
return Err(Error::EntryGroupExists);
}
self.entry_groups.push(group);
Ok(self)
}
#[inline]
pub fn try_add_entry(
&mut self,
group: impl AsRef<str>,
entry: AnnotatedEntry,
) -> Result<&mut Self, Error> {
self.group_mut(group.as_ref())?.try_add(entry)?;
Ok(self)
}
#[inline]
fn try_add_any_entry(
&mut self,
group: impl AsRef<str>,
entry: AnnotatedEntry,
) -> Result<&mut Self, Error> {
self.group_mut(group.as_ref())?.try_add_any(entry)?;
Ok(self)
}
#[inline]
pub fn try_add_entry_to_main_group(
&mut self,
entry: AnnotatedEntry,
) -> Result<&mut Self, Error> {
if entry.is_actions_entry() {
return Err(Error::AddActionsEntry);
}
self.try_add_entry(GroupName::DESKTOP_ENTRY, entry)
}
#[inline]
pub fn try_add_action(&mut self, name: impl Into<String>) -> Result<&mut Self, Error> {
let index = self
.group_index(GroupName::DESKTOP_ENTRY)
.ok_or(Error::EntryGroupNotFound)?;
let name = name.into();
let action_group_name = GroupName::try_from(GroupName::action_group_name(&name))?;
let action_display_name = LocaleString::try_from(name.as_str())?;
let action = EscapedString::try_from(name)?;
if !self.contains(&action_group_name) {
let action_group = EntryGroup::with_entry(
action_group_name,
AnnotatedEntry::new(Entry::Name(action_display_name)),
);
self.entry_groups.push(action_group);
}
if let Some(entry_index) = self.entry_groups[index].key_index(EntryKeys::Actions) {
let Entry::Actions(actions) = &mut self.entry_groups[index].entries[entry_index].entry
else {
unreachable!("\"Actions\" entry exists but is not Entry::Actions");
};
actions.push(action);
} else {
self.entry_groups[index].try_add_any(AnnotatedEntry::new(Entry::Actions(
EscapedStrings::from(vec![action]),
)))?;
}
Ok(self)
}
#[inline]
pub fn append_group_comment(&mut self, name: &str, comment: &str) -> Result<&mut Self, Error> {
format_comment(&mut self.group_mut(name)?.comment, comment);
Ok(self)
}
#[inline]
pub fn append_comment(&mut self, comment: &str) -> &mut Self {
format_comment(&mut self.comment, comment);
self
}
#[inline]
pub fn insert_entry(
&mut self,
group_name: &str,
key: impl AsRef<str>,
entry: AnnotatedEntry,
) -> Result<&mut Self, Error> {
if entry.is_actions_entry() {
return Err(Error::InsertActionsEntry);
}
self.group_mut(group_name)?.try_insert(key, entry)?;
Ok(self)
}
pub fn try_remove_entry(
&mut self,
group_name: impl AsRef<str>,
key: impl AsRef<str>,
) -> Result<AnnotatedEntry, Error> {
let key = key.as_ref();
let group_name = GroupName::try_from(group_name.as_ref())?;
let group = self.group_mut(&group_name)?;
let entry_key_index = group.key_index(key).ok_or(Error::RemoveEntry)?;
if let Ok(key) = key.parse::<EntryKeys>() {
let is_required = if group_name.is_desktop_entry() {
group
.entry_type()
.is_some_and(|desktop_type| key.is_required_for(desktop_type))
} else if group_name.is_action() {
key == EntryKeys::Name
} else {
false
};
if is_required {
return Err(Error::RemoveRequiredEntry);
}
}
let ae = group.remove(entry_key_index);
if group_name.is_desktop_entry() && ae.is_actions_entry() {
self.remove_all_action_groups();
}
Ok(ae)
}
fn remove_all_action_groups(&mut self) {
self.entry_groups
.retain(|group| !group.group_name().is_action());
}
#[inline]
pub fn try_swap_entry(
&mut self,
group_name: &str,
key_a: &str,
key_b: &str,
) -> Result<&mut Self, Error> {
let group = self.group_mut(group_name)?;
let index_a = group.key_index(key_a).ok_or(Error::SwapEntry)?;
let index_b = group.key_index(key_b).ok_or(Error::SwapEntry)?;
group.entries.swap(index_a, index_b);
Ok(self)
}
}
impl fmt::Display for DesktopFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let last_index = self.entry_groups.len();
self.entry_groups
.iter()
.enumerate()
.try_for_each(|(i, group)| {
let new_line = if (i + 1) == last_index { "" } else { "\n" };
write!(f, "{group}{new_line}")
})?;
write!(f, "{}{}", comment_separator(&self.comment), self.comment)?;
Ok(())
}
}
impl FromStr for DesktopFile {
type Err = ParseFileDesktopError;
fn from_str(content: &str) -> Result<Self, Self::Err> {
if content.is_empty() {
return Err(ParseFileDesktopError::EmptyFile);
}
let mut current_group_name = None;
let mut pending_comment = String::new();
let mut desktop_file = Self {
entry_groups: Vec::new(),
comment: String::new(),
};
for (line_index, line) in content.lines().enumerate() {
let line_number = line_index + 1;
if line.starts_with(' ') {
return Err(ParseFileDesktopError::InvalidComment { line: line_number });
}
if line.starts_with('#') {
if !pending_comment.is_empty() && !pending_comment.ends_with('\n') {
pending_comment.push('\n');
}
pending_comment.push_str(line);
continue;
}
if line.is_empty() {
if !pending_comment.is_empty() && !pending_comment.ends_with('\n') {
pending_comment.push('\n');
}
pending_comment.push('\n');
continue;
}
if line.starts_with('[') {
let group_name = GroupName::from_str(line).map_err(|source| match source {
GroupError::EmptyGroupName => {
ParseFileDesktopError::EmptyGroupName { line: line_number }
}
source => ParseFileDesktopError::InvalidGroupHeader {
line: line_number,
source,
},
})?;
desktop_file
.try_add_any_group(EntryGroup {
group_name: group_name.clone(),
comment: std::mem::take(&mut pending_comment),
entries: Vec::new(),
})
.map_err(|_| ParseFileDesktopError::DuplicateGroup { line: line_number })?;
current_group_name = Some(group_name);
continue;
}
let entry =
Entry::try_from(line).map_err(|source| ParseFileDesktopError::ParseEntry {
line: line_number,
source,
})?;
desktop_file
.try_add_any_entry(
current_group_name
.as_ref()
.ok_or(ParseFileDesktopError::EntryOutsideGroup { line: line_number })?,
AnnotatedEntry::from_parsed(entry, std::mem::take(&mut pending_comment)),
)
.map_err(|_| ParseFileDesktopError::DuplicateEntry { line: line_number })?;
}
if !desktop_file.contains(GroupName::DESKTOP_ENTRY) {
return Err(ParseFileDesktopError::MissingRequiredGroup);
}
if !desktop_file.has_required_keys() {
return Err(ParseFileDesktopError::MissingRequiredKeys);
}
if !desktop_file.is_actions_consistent() {
return Err(ParseFileDesktopError::InconsistentActions);
}
if content.ends_with('\n') && !pending_comment.ends_with('\n') {
pending_comment.push('\n');
}
desktop_file.comment = pending_comment;
Ok(desktop_file)
}
}
fn comment_separator(comment: &str) -> &'static str {
if !comment.is_empty() && !comment.ends_with('\n') {
"\n"
} else {
""
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_comment_separator() {
assert_eq!(comment_separator(""), "");
assert_eq!(comment_separator("test"), "\n");
}
}