file_desktop 0.1.0

Parse, inspect, and build XDG .desktop files in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
// {── Module ──────────────────────────────────────────────────────────────────
//! Strongly typed domain types for Desktop Entry key-value pairs.
//!
//! # Overview
//!
//! The central type is [`Entry`], a strongly typed enum where each variant carries
//! exactly the value type prescribed by the XDG Desktop Entry Specification for
//! that key.  This makes invalid key/value combinations impossible to construct.
//!
//! Entries are stored inside a group as [`AnnotatedEntry`] values, which pair an
//! [`Entry`] with an optional preceding comment string.
//!
//! # Semantic Value Types
//!
//! Several domain-specific wrapper types model values where the spec defines
//! distinct semantics beyond a plain string:
//!
//! - [`DesktopType`] — the `Type=` field discriminant (`Application`, `Link`, `Directory`)
//! - [`IconString`] — an icon theme name or absolute filesystem path
//! - [`LocaleString`] — a locale-appropriate string used in localized entries
//! - [`Numeric`](crate::key::Numeric) — a validated numeric value for extension fields
//!
//! # Non-Standard and Localized Keys
//!
//! Extension keys (e.g. `X-Extension=value`) are represented by
//! [`Entry::Extension`].  Localized standard keys (e.g. `Name[de]=Firefox`) are
//! represented by [`Entry::Localized`].
//!
//! # Comments
//!
//! Per-entry comment text is not embedded in `Entry` variants.  Instead,
//! [`AnnotatedEntry`] wraps an `Entry` with its associated comment string,
//! following the XDG Desktop Entry comment format: non-blank lines are prefixed
//! with `# ` and blank lines are preserved.
//!
//! # Examples
//!
//! ```rust
//! use file_desktop::entry::{AnnotatedEntry, Entry};
//! use file_desktop::key::DesktopType;
//!
//! let mut ae = AnnotatedEntry::new(Entry::Name("My Application".parse().unwrap()));
//! ae.append_comment("The display name");
//!
//! assert_eq!(ae.key_name(), "Name");
//! assert_eq!(ae.comment(), "# The display name");
//! assert_eq!(ae.to_string(), "# The display name\nName=My Application");
//! ```

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,
};

// }{── Entry ──────────────────────────────────────────────────────────────────

/// A strongly typed Desktop Entry key-value pair.
///
/// Each variant carries exactly the value type required by the
/// [XDG Desktop Entry Specification](https://specifications.freedesktop.org/desktop-entry-spec/latest/)
/// for that key, making invalid key/value combinations impossible to construct.
///
/// This enum is `#[non_exhaustive]` so that new standard keys can be added in
/// future crate versions without breaking downstream `match` expressions.
///
/// # Localized Keys
///
/// Localized standard keys such as `Name[de]=Firefox` are represented by
/// [`Entry::Localized`].  The `key` field is the [`EntryKeys`] variant for the
/// base standard key (e.g. `EntryKeys::Name`) and `locale` carries the locale
/// string.
///
/// # Extension Keys
///
/// Keys not recognized by the specification (including `X-` prefixed keys) are
/// represented by [`Entry::Extension`].
///
/// # Version Metadata
///
/// [`Entry::version_introduced`] returns the specification version in which a
/// standard key was first defined. Keys present since v1.0 and unversioned
/// extension keys return `None`.
///
/// # Examples
///
/// ```rust
/// use file_desktop::entry::Entry;
/// use file_desktop::key::{Bool, DesktopType, ExtensionEntry};
///
/// let name = Entry::Name("Firefox".parse().unwrap());
/// assert_eq!(name.key_name(), "Name");
/// assert_eq!(name.to_string(), "Name=Firefox");
///
/// let ty = Entry::Type(DesktopType::Application);
/// assert_eq!(ty.to_string(), "Type=Application");
///
/// let term = Entry::Terminal(Bool::new(true));
/// assert_eq!(term.to_string(), "Terminal=true");
///
/// let extension = Entry::Extension(
///     ExtensionEntry::try_from(("X-MyApp-Option", "enabled")).unwrap(),
/// );
/// assert_eq!(extension.to_string(), "X-MyApp-Option=enabled");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Entry {
    // ── Basic ─────────────────────────────────────────────────────────────────
    /// `Type=Application|Link|Directory` — required field.
    Type(DesktopType),
    /// `Version=<spec version>` (e.g. `1.5`).
    Version(Version),
    /// `Name=<display name>` — required field.
    Name(LocaleString),
    /// `GenericName=<generic description>` (e.g. `"Web Browser"`).
    GenericName(LocaleString),

    // ── Visibility ────────────────────────────────────────────────────────────
    /// `NoDisplay=true|false` — hide from application menus when `true`.
    NoDisplay(Bool),
    /// `Hidden=true|false` — treat as deleted when `true`.
    Hidden(Bool),
    /// `OnlyShowIn=<semicolon-separated desktop environments>`.
    OnlyShowIn(EscapedStrings),
    /// `NotShowIn=<semicolon-separated desktop environments>`.
    NotShowIn(EscapedStrings),

    // ── Descriptive ───────────────────────────────────────────────────────────
    /// `Comment=<tooltip or description>`.
    Comment(LocaleString),
    /// `Icon=<icon name or absolute path>`.
    Icon(IconString),
    /// `Keywords=<semicolon-separated search terms>` — since spec v1.1.
    Keywords(LocaleStrings),

    // ── Execution ─────────────────────────────────────────────────────────────
    /// `Exec=<command line>`.
    Exec(EscapedString),
    /// `TryExec=<executable path>` — used to determine if the program is installed.
    TryExec(EscapedString),
    /// `Path=<working directory>` for program execution.
    Path(EscapedString),
    /// `Terminal=true|false` — run in a terminal window when `true`.
    Terminal(Bool),

    // ── Activation ────────────────────────────────────────────────────────────
    /// `DBusActivatable=true|false` — since spec v1.1.
    DBusActivatable(Bool),
    /// `StartupNotify=true|false` — provide startup notification when `true`.
    StartupNotify(Bool),
    /// `StartupWMClass=<WM class>` — window manager class for startup notification.
    StartupWMClass(EscapedString),

    // ── Actions ───────────────────────────────────────────────────────────────
    /// `Actions=<semicolon-separated action names>` — since spec v1.1.
    Actions(EscapedStrings),

    // ── Classification ────────────────────────────────────────────────────────
    /// `Categories=<semicolon-separated menu categories>`.
    Categories(EscapedStrings),
    /// `MimeType=<semicolon-separated MIME types>`.
    MimeType(EscapedStrings),
    /// `Implements=<semicolon-separated interface names>` — since spec v1.2.
    Implements(EscapedStrings),

    // ── Presentation ──────────────────────────────────────────────────────────
    /// `URL=<URL>` — required for `Type=Link` entries.
    URL(EscapedString),
    /// `PrefersNonDefaultGPU=true|false` — since spec v1.4.
    PrefersNonDefaultGPU(Bool),
    /// `SingleMainWindow=true|false` — since spec v1.5.
    SingleMainWindow(Bool),

    // ── Special ───────────────────────────────────────────────────────────────
    /// A localized standard key, e.g. `Name[de]=Firefox`.
    ///
    /// The `key` field is the [`EntryKeys`] variant for the base standard key
    /// (one of `Name`, `GenericName`, `Comment`, `Icon`, or `Keywords` — the
    /// only localizable keys). The `locale` field carries the locale string
    /// (e.g. `"de"`, `"de_DE"`).
    Localized(LocalizedEntry),
    /// A non-standard or extension key, e.g. `X-Extension=value`.
    Extension(ExtensionEntry),
}

impl Entry {
    /// Returns the key name string for this entry.
    ///
    /// For standard variants this is always a statically borrowed `&'static str`
    /// wrapped in `Cow::Borrowed`.  For [`Entry::Localized`] (e.g. `Name[de]`)
    /// an owned `String` is returned.  For [`Entry::Extension`] the inner key is
    /// borrowed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::entry::Entry;
    /// use file_desktop::key::{Bool, DesktopType, LocalizedEntry};
    ///
    /// assert_eq!(Entry::Name("App".parse().unwrap()).key_name(), "Name");
    /// assert_eq!(Entry::Type(DesktopType::Application).key_name(), "Type");
    /// assert_eq!(Entry::Terminal(Bool::new(false)).key_name(), "Terminal");
    ///
    /// let loc = Entry::Localized(
    ///     LocalizedEntry::try_from(("Name[de]", "Firefox")).unwrap(),
    /// );
    /// assert_eq!(loc.key_name(), "Name[de]");
    /// ```
    #[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()),
        }
    }

    /// Returns whether this is an `Actions` entry.
    ///
    /// # Examples
    ///
    /// ```
    /// use file_desktop::entry::Entry;
    /// use file_desktop::key::EscapedStrings;
    ///
    /// let actions = "Open;".parse::<EscapedStrings>().unwrap();
    /// let entry = Entry::Actions(actions);
    ///
    /// assert!(entry.is_actions_entry());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_actions_entry(&self) -> bool {
        matches!(self, Self::Actions(_))
    }

    /// Returns the Desktop Entry Specification version in which this key was
    /// introduced.
    ///
    /// Returns `None` for standard keys present since version 1.0 and for
    /// unversioned extension keys.
    ///
    /// This method replaces the previous `VERSION_EXCLUDES`-based mechanism and
    /// allows callers to filter entries by the spec version they target.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::entry::Entry;
    /// use file_desktop::key::{Bool, EscapedStrings, Version};
    ///
    /// // Keys present since v1.0 return None.
    /// assert_eq!(Entry::Name("App".parse().unwrap()).version_introduced(), None);
    /// assert_eq!(Entry::Exec("".parse().unwrap()).version_introduced(), None);
    ///
    /// // Keys added in later versions.
    /// assert_eq!(Entry::DBusActivatable(Bool::new(false)).version_introduced(), Some(Version::Ver1_1));
    /// assert_eq!(Entry::Implements(EscapedStrings::default()).version_introduced(), Some(Version::Ver1_2));
    /// assert_eq!(Entry::PrefersNonDefaultGPU(Bool::new(false)).version_introduced(), Some(Version::Ver1_4));
    /// assert_eq!(Entry::SingleMainWindow(Bool::new(false)).version_introduced(), Some(Version::Ver1_5));
    /// ```
    #[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()
    }

    /// Returns a reference to the entry value as type `T`.
    ///
    /// # Errors
    ///
    /// Returns [`EntryError::Value`] if the entry value cannot be represented as
    /// `T`.
    ///
    /// # Examples
    ///
    /// ```
    /// use file_desktop::entry::Entry;
    /// use file_desktop::key::LocaleString;
    ///
    /// let entry = Entry::Name("Firefox".parse::<LocaleString>()?);
    ///
    /// let value = entry.value::<LocaleString>()?;
    ///
    /// assert_eq!(value.as_ref(), "Firefox");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[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)
    }

    /// Mutably borrows the inner value if it matches the target type `T`.
    ///
    /// # Errors
    ///
    /// Returns [`EntryError::MutationValue`] when this `Entry` does not hold
    /// a value of type `T`.
    #[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)
    }

    /// Builds an `Entry` for a recognized standard key from its raw value text.
    ///
    /// Internal helper shared by the `TryFrom<&str>` implementation; not part
    /// of the public API.
    #[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",
        }
    }
}

/// Parses a single already-split `key=value` line into an [`Entry`].
///
/// # Arguments
///
/// * `line` - A single `key=value` line, without a trailing newline.
///
/// # Errors
///
/// * `ParseEntryError::MissingSeparator` - `line` contains no `=` character.
/// * `ParseEntryError::ParseKey` - The key is not a recognized standard key,
///   localized standard key (`Key[locale]`), or `X-` prefixed extension key.
/// * `ParseEntryError::ParseValue` - The key was recognized, but its value
///   failed to parse into the required type.
///
/// # Examples
///
/// ```rust
/// use file_desktop::entry::Entry;
///
/// let entry = Entry::try_from("Name=Firefox").unwrap();
/// assert_eq!(entry.to_string(), "Name=Firefox");
///
/// assert!(Entry::try_from("NoEqualsSign").is_err());
/// ```
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)?);
        }

        // Preserve error intent for malformed extension keys.
        if key.starts_with("X-") {
            return Ok(Self::Extension(ExtensionEntry::try_from((key, value))?));
        }

        // Preserve error intent for malformed locale-suffixed keys.
        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())
    }
}

/// Parses a single already-split `key=value` line into an [`Entry`].
///
/// Delegates to the `TryFrom<&str>` implementation; see its documentation
/// for the exact argument and error semantics.
///
/// # Examples
///
/// ```rust
/// use file_desktop::entry::Entry;
///
/// let entry: Entry = "Name=Firefox".parse().unwrap();
/// assert_eq!(entry.to_string(), "Name=Firefox");
/// ```
impl FromStr for Entry {
    type Err = ParseEntryError;

    #[inline]
    fn from_str(line: &str) -> Result<Self, Self::Err> {
        Self::try_from(line)
    }
}

/// Formats an `Entry` back into its `key=value` (or `key[locale]=value`)
/// line form, as it would appear in a `.desktop` file.
///
/// # Examples
///
/// ```rust
/// use file_desktop::entry::Entry;
///
/// let entry = Entry::Name("Firefox".parse().unwrap());
/// assert_eq!(entry.to_string(), "Name=Firefox");
/// ```
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())
            }
        }
    }
}

// }{── AnnotatedEntry ─────────────────────────────────────────────────────────

/// An [`Entry`] paired with an optional preceding comment.
///
/// Desktop entry groups store entries as `AnnotatedEntry` values so that comment
/// text is preserved alongside each entry during parsing, mutation, and
/// serialization. Comments added through [`AnnotatedEntry::append_comment`]
/// are normalized with a `# ` prefix on non-blank lines; parsed comments retain
/// their original text after the `#` marker. Blank lines are preserved as-is.
///
/// # Examples
///
/// ```rust
/// use file_desktop::entry::{AnnotatedEntry, Entry};
///
/// let mut ae = AnnotatedEntry::new(Entry::Name("Firefox".parse().unwrap()));
/// ae.append_comment("The browser name");
///
/// assert_eq!(ae.comment(), "# The browser name");
/// assert_eq!(ae.key_name(), "Name");
/// assert_eq!(ae.to_string(), "# The browser name\nName=Firefox");
///
/// ae.clear_comment();
/// assert_eq!(ae.to_string(), "Name=Firefox");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnnotatedEntry {
    pub(crate) entry: Entry,
    pub(crate) comment: String,
}

impl AnnotatedEntry {
    /// Creates a new `AnnotatedEntry` with no comment.
    ///
    /// # Arguments
    ///
    /// * `entry` - The [`Entry`] to wrap.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::entry::{AnnotatedEntry, Entry};
    ///
    /// let ae = AnnotatedEntry::new(Entry::Name("Firefox".parse().unwrap()));
    /// assert_eq!(ae.comment(), "");
    /// assert_eq!(ae.key_name(), "Name");
    /// ```
    #[inline]
    #[must_use]
    pub fn new(entry: Entry) -> Self {
        Self {
            entry,
            comment: String::new(),
        }
    }

    /// Returns whether the contained entry is an `Actions` entry.
    #[inline]
    #[must_use]
    pub const fn is_actions_entry(&self) -> bool {
        self.entry.is_actions_entry()
    }

    /// Constructs an `AnnotatedEntry` from an already-formatted comment string.
    ///
    /// Used internally by the file parser to attach accumulated comment lines
    /// directly without re-normalizing them.  Not part of the public API.
    #[inline]
    pub(crate) fn from_parsed(entry: Entry, comment: String) -> Self {
        Self { entry, comment }
    }

    /// Returns a shared reference to the inner [`Entry`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::entry::{AnnotatedEntry, Entry};
    ///
    /// let ae = AnnotatedEntry::new(Entry::Name("Firefox".parse().unwrap()));
    /// assert_eq!(ae.entry(), &Entry::Name("Firefox".parse().unwrap()));
    /// ```
    #[inline]
    #[must_use]
    pub fn entry(&self) -> &Entry {
        &self.entry
    }

    /// Returns the key name for this entry.
    ///
    /// Delegates to [`Entry::key_name`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::entry::{AnnotatedEntry, Entry};
    ///
    /// let ae = AnnotatedEntry::new(Entry::Name("Firefox".parse().unwrap()));
    /// assert_eq!(ae.key_name(), "Name");
    /// ```
    #[inline]
    #[must_use]
    pub fn key_name(&self) -> Cow<'_, str> {
        self.entry.key_name()
    }

    /// Returns the specification version in which this entry's key was introduced.
    ///
    /// Delegates to [`Entry::version_introduced`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::entry::{AnnotatedEntry, Entry};
    /// use file_desktop::key::{Bool, Version};
    ///
    /// let ae = AnnotatedEntry::new(Entry::DBusActivatable(Bool::new(true)));
    /// assert_eq!(ae.version_introduced(), Some(Version::Ver1_1));
    /// ```
    #[inline]
    #[must_use]
    pub fn version_introduced(&self) -> Option<Version> {
        self.entry.version_introduced()
    }

    /// Returns the comment text associated with this entry.
    ///
    /// Comments attached by [`Self::append_comment`] are normalized so each
    /// non-blank line starts with `# `. Comments parsed from a file preserve
    /// their original text after the `#` marker.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::entry::{AnnotatedEntry, Entry};
    ///
    /// let mut ae = AnnotatedEntry::new(Entry::Name("Firefox".parse().unwrap()));
    /// ae.append_comment("Browser");
    /// assert_eq!(ae.comment(), "# Browser");
    /// ```
    #[inline]
    #[must_use]
    pub fn comment(&self) -> &str {
        &self.comment
    }

    /// Appends normalized comment text to this entry.
    ///
    /// Non-blank lines are prefixed with `# ` and blank lines are preserved.
    /// Multiple calls accumulate lines rather than replacing earlier text.  To
    /// replace an existing comment, call [`clear_comment`](Self::clear_comment)
    /// first.
    ///
    /// # Arguments
    ///
    /// * `text` - The comment text to append; may span multiple lines.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::entry::{AnnotatedEntry, Entry};
    ///
    /// let mut ae = AnnotatedEntry::new(Entry::Name("Firefox".parse().unwrap()));
    /// ae.append_comment("Browser");
    /// assert_eq!(ae.comment(), "# Browser");
    /// ```
    #[inline]
    pub fn append_comment(&mut self, text: &str) {
        format_comment(&mut self.comment, text);
    }

    /// Removes all comment text from this entry.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::entry::{AnnotatedEntry, Entry};
    ///
    /// let mut ae = AnnotatedEntry::new(Entry::Name("Firefox".parse().unwrap()));
    /// ae.append_comment("Browser");
    /// ae.clear_comment();
    /// assert_eq!(ae.comment(), "");
    /// ```
    #[inline]
    pub fn clear_comment(&mut self) {
        self.comment.clear();
    }

    /// Appends a value to this entry when its key accepts a list value.
    ///
    /// [`EscapedString`] values can be appended to `Actions`, `OnlyShowIn`,
    /// `NotShowIn`, `MimeType`, `Categories`, and `Implements` entries.
    /// [`LocaleString`] values can be appended to `Keywords` entries.
    ///
    /// # Arguments
    ///
    /// * `value` - The validated value to append.
    ///
    /// # Errors
    ///
    /// * `AppendKeyValueError::NotEscapedStringList` - `value` is an [`EscapedString`], but this entry does not hold an escaped-string list.
    /// * `AppendKeyValueError::NotLocaleStringList` - `value` is a [`LocaleString`], but this entry is not `Keywords`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::entry::{AnnotatedEntry, Entry};
    /// use file_desktop::key::EscapedString;
    ///
    /// let mut entry = AnnotatedEntry::new(Entry::Actions("Open;".try_into().unwrap()));
    /// entry
    ///     .try_append(EscapedString::try_from("NewWindow").unwrap())
    ///     .unwrap();
    ///
    /// assert_eq!(entry.to_string(), "Actions=Open;NewWindow;");
    /// ```
    #[inline]
    pub fn try_append<T>(&mut self, value: T) -> Result<(), AppendKeyValueError>
    where
        T: AppendValue,
    {
        value.append_to(&mut self.entry)?;
        Ok(())
    }

    /// Returns a reference to the contained entry value as type `T`.
    ///
    /// # Errors
    ///
    /// Returns [`EntryError::Value`] if the contained entry value cannot be
    /// represented as `T`.
    ///
    /// # Examples
    ///
    /// ```
    /// use file_desktop::entry::{Entry, AnnotatedEntry};
    /// use file_desktop::key::{EntryKeys, LocaleString};
    ///
    /// let ae = AnnotatedEntry::new("Name=Firefox".parse::<Entry>()?);
    ///
    /// let value = ae.value::<LocaleString>()?;
    ///
    /// assert_eq!(value.as_ref(), "Firefox");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub fn value<T>(&self) -> Result<&T, EntryError>
    where
        for<'a> &'a Entry: TryInto<&'a T, Error = ValueError>,
    {
        self.entry.value()
        //(&self.entry).try_into().map_err(EntryError::Value)
    }

    /// Returns a mutable reference to the inner value of type `T` if the entry holds that type.
    ///
    /// # Errors
    ///
    /// Returns [`EntryError::MutationValue`] when the wrapped [`Entry`] does
    /// not hold a value of type `T`.
    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)
    }
}

/// Converts a file-type selector into a `Type` entry.
///
/// The conversion ignores the embedded URL carried by [`DesktopFileType::Link`] because
/// it only produces the `Type` entry.
///
/// # Examples
///
/// ```rust
/// use file_desktop::desktop::DesktopFileType;
/// use file_desktop::entry::{AnnotatedEntry, Entry};
/// use file_desktop::key::DesktopType;
///
/// let ae = AnnotatedEntry::from(DesktopFileType::Application);
/// assert_eq!(ae.key_name(), "Type");
/// assert_eq!(ae.entry(), &Entry::Type(DesktopType::Application));
/// ```
///
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))
    }
}

// }{── Private trait ────────────────────────────────────────────────────────
//
mod private {
    pub trait Sealed {}
}

/// A value that can be appended to a compatible list-valued [`Entry`].
///
/// This sealed trait is implemented by [`EscapedString`] and [`LocaleString`]
/// only. Use [`AnnotatedEntry::try_append`] rather than calling this trait
/// method directly.
pub trait AppendValue: private::Sealed {
    /// Appends this value to `entry` when the entry accepts its value type.
    ///
    /// # Arguments
    ///
    /// * `entry` - The list-valued entry to update.
    ///
    /// # Errors
    ///
    /// Returns an [`AppendKeyValueError`] when `entry` does not accept this
    /// value type.
    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),
        }
    }
}

// }{── Tests ──────────────────────────────────────────────────────────────────

#[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)));
    }
}

// }────────────────────────────────────────────────────────────────────────────