lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
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
//! What a media and its players say by themselves: the names of their controls, the words they draw, and what a
//! media that cannot play says. A part of the app's [`Locale`](super::Locale).

use std::{fmt, sync::Arc};

/// Why a media cannot play. It says what kind of failure it is, and the [`Locale`](super::Locale) says it in the
/// app's language ([`MediaWords::error`]); what the system or the connection said in its own words is kept beside
/// it, for a log.
///
/// ```
/// use lurq::core::{Locale, MediaError};
///
/// assert_eq!(&*Locale::english().media.error(&MediaError::Unsupported), "Unsupported format");
/// assert_eq!(&*Locale::for_tag("uk").media.error(&MediaError::Server(503)), "Помилка сервера 503");
/// assert_eq!(MediaError::NotFound.to_string(), "Not found");
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MediaError {
  /// What it is, is nothing the system plays: bytes that are no video and no sound, a kind it has no decoder for.
  Unsupported,
  /// There is no such file, or the server has none at the address.
  NotFound,
  /// The app's loader does not allow the address.
  Denied,
  /// Loading it took longer than the app's loader waits.
  TimedOut,
  /// It is larger than the app's loader reads whole, and nothing else could read it.
  TooLarge,
  /// The server answered with this status.
  Server(u16),
  /// The connection failed, in the words of what failed.
  Network(Arc<str>),
  /// This build or this system has nothing to play it with, and why.
  Unavailable(Arc<str>),
  /// Anything else, in the system's own words.
  Other(Arc<str>),
}

impl MediaError {
  /// What the system or the connection said in its own words, where it said something: for a log, not for a
  /// person.
  pub fn detail(&self) -> Option<&str> {
    match self {
      Self::Network(said) | Self::Unavailable(said) | Self::Other(said) => Some(said),
      _ => None,
    }
  }
}

/// In English, as [`Locale::english`](super::Locale::english) says it.
impl fmt::Display for MediaError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(&MediaWords::english().error(self))
  }
}

impl std::error::Error for MediaError {}

/// What a media is, once it opened and is ready to play: what [`Media::on_load`](crate::media::Media::on_load) and
/// a player's `on_load` are told.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct MediaInfo {
  /// How long it is, in seconds. `None` for what has no end.
  pub duration: Option<f64>,
  /// How large its picture is, in pixels. `None` for what has no picture, and for what is only heard.
  pub size: Option<(u32, u32)>,
  /// Whether it has sound.
  pub sound: bool,
}

/// Why a picture did not come: what `ui::Picture::on_error` is told. It says what kind of failure it is, and the
/// [`Locale`](super::Locale) says it in the app's language ([`MediaWords::picture_error`]); what the system, the
/// connection or the decoder said in its own words is kept beside it, for a log.
///
/// ```
/// use lurq::core::{Locale, PictureError};
///
/// assert_eq!(&*Locale::english().media.picture_error(&PictureError::NotAPicture(None)), "Not an image");
/// assert_eq!(&*Locale::for_tag("uk").media.picture_error(&PictureError::NotFound), "Не знайдено");
/// assert_eq!(PictureError::Server(404).to_string(), "Server error 404");
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PictureError {
  /// There is no such file, or the server has none at the address.
  NotFound,
  /// The app's loader does not allow the address.
  Denied,
  /// Loading it took longer than the app's loader waits.
  TimedOut,
  /// It is larger than the app's loader reads whole, or than the decoder takes.
  TooLarge,
  /// The server answered with this status.
  Server(u16),
  /// The connection failed, in the words of what failed.
  Network(Arc<str>),
  /// What came is no picture the decoder reads: bytes of another kind, a format it has no decoder for, a broken
  /// file, a picture with no pixels. With what the decoder said, where it said something.
  NotAPicture(Option<Arc<str>>),
  /// This build or this system has nothing to load or decode it with, and why: a build without the `image`
  /// feature, an address in one without `http`, a picture in no app.
  Unavailable(Arc<str>),
  /// Anything else, in the system's own words: a file that could not be read.
  Other(Arc<str>),
}

impl PictureError {
  /// What the system, the connection or the decoder said in its own words, where it said something: for a log,
  /// not for a person.
  pub fn detail(&self) -> Option<&str> {
    match self {
      Self::Network(said) | Self::Unavailable(said) | Self::Other(said) | Self::NotAPicture(Some(said)) => Some(said),
      _ => None,
    }
  }
}

/// In English, as [`Locale::english`](super::Locale::english) says it.
impl fmt::Display for PictureError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(&MediaWords::english().picture_error(self))
  }
}

impl std::error::Error for PictureError {}

/// What a media and its players say by themselves, in a locale's words. Every field is the app's to replace.
///
/// ```
/// use std::sync::Arc;
///
/// use lurq::core::Locale;
///
/// let mut locale = Locale::for_tag("uk");
/// assert_eq!(&*locale.media.play, "Відтворити");
/// // A word of the app's own in place of one of lurq's.
/// locale.media.try_again = Arc::from("Ще раз");
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MediaWords {
  /// What an audio player and a video player are called to what reads the tree.
  pub audio_player: Arc<str>,
  pub video_player: Arc<str>,
  pub play: Arc<str>,
  pub pause: Arc<str>,
  pub replay: Arc<str>,
  pub previous: Arc<str>,
  pub next: Arc<str>,
  pub shuffle: Arc<str>,
  pub repeat: Arc<str>,
  pub more: Arc<str>,
  /// The name of a video's speed button, and the heading of the menu of speeds.
  pub speed: Arc<str>,
  pub playback_speed: Arc<str>,
  /// The speed things were made at, in a menu of speeds: "Normal".
  pub normal_speed: Arc<str>,
  pub queue: Arc<str>,
  /// What the mark of the track that plays is called in a queue.
  pub now_playing: Arc<str>,
  pub expand: Arc<str>,
  /// What a seek bar and a waveform are called.
  pub seek: Arc<str>,
  pub mute: Arc<str>,
  pub unmute: Arc<str>,
  pub volume: Arc<str>,
  pub captions: Arc<str>,
  pub settings: Arc<str>,
  pub quality: Arc<str>,
  pub picture_in_picture: Arc<str>,
  /// What a video says where it stood while it plays in its small window, and the button that brings it back.
  pub in_picture: Arc<str>,
  pub back_to_window: Arc<str>,
  pub fullscreen: Arc<str>,
  pub exit_fullscreen: Arc<str>,
  pub try_again: Arc<str>,
  /// The touch form's buttons that go ten seconds back and on, and the word after a number of them.
  pub rewind: Arc<str>,
  pub forward: Arc<str>,
  pub seconds: Arc<str>,
  pub minimize: Arc<str>,
  pub back: Arc<str>,
  /// The quality a player picks itself, captions on and off, and the badge of what is live.
  pub auto: Arc<str>,
  pub on: Arc<str>,
  pub off: Arc<str>,
  pub live: Arc<str>,
  /// The title of a video's error; the reason is under it.
  pub unplayable_video: Arc<str>,
  /// What each kind of [`MediaError`] is called.
  pub unsupported: Arc<str>,
  pub not_found: Arc<str>,
  pub denied: Arc<str>,
  pub timed_out: Arc<str>,
  pub too_large: Arc<str>,
  /// The server's answer, with `{status}` where its number goes.
  pub server_error: Arc<str>,
  pub network_error: Arc<str>,
  pub unavailable: Arc<str>,
  pub failed: Arc<str>,
  /// What a [`PictureError`] is called where a media's word does not fit it: bytes that are no picture, a picture
  /// this build or system cannot show, and anything else.
  pub not_a_picture: Arc<str>,
  pub picture_unavailable: Arc<str>,
  pub picture_failed: Arc<str>,
}

impl MediaWords {
  /// The words in the order of the fields.
  fn of(words: [&str; 51]) -> Self {
    let [
      audio_player,
      video_player,
      play,
      pause,
      replay,
      previous,
      next,
      shuffle,
      repeat,
      more,
      speed,
      playback_speed,
      normal_speed,
      queue,
      now_playing,
      expand,
      seek,
      mute,
      unmute,
      volume,
      captions,
      settings,
      quality,
      picture_in_picture,
      in_picture,
      back_to_window,
      fullscreen,
      exit_fullscreen,
      try_again,
      rewind,
      forward,
      seconds,
      minimize,
      back,
      auto,
      on,
      off,
      live,
      unplayable_video,
      unsupported,
      not_found,
      denied,
      timed_out,
      too_large,
      server_error,
      network_error,
      unavailable,
      failed,
      not_a_picture,
      picture_unavailable,
      picture_failed,
    ] = words.map(Arc::from);
    Self {
      audio_player,
      video_player,
      play,
      pause,
      replay,
      previous,
      next,
      shuffle,
      repeat,
      more,
      speed,
      playback_speed,
      normal_speed,
      queue,
      now_playing,
      expand,
      seek,
      mute,
      unmute,
      volume,
      captions,
      settings,
      quality,
      picture_in_picture,
      in_picture,
      back_to_window,
      fullscreen,
      exit_fullscreen,
      try_again,
      rewind,
      forward,
      seconds,
      minimize,
      back,
      auto,
      on,
      off,
      live,
      unplayable_video,
      unsupported,
      not_found,
      denied,
      timed_out,
      too_large,
      server_error,
      network_error,
      unavailable,
      failed,
      not_a_picture,
      picture_unavailable,
      picture_failed,
    }
  }

  pub fn english() -> Self {
    Self::of([
      "Audio player",
      "Video player",
      "Play",
      "Pause",
      "Replay",
      "Previous",
      "Next",
      "Shuffle",
      "Repeat",
      "More",
      "Speed",
      "Playback speed",
      "Normal",
      "Queue",
      "Now playing",
      "Expand",
      "Seek",
      "Mute",
      "Unmute",
      "Volume",
      "Captions",
      "Settings",
      "Quality",
      "Picture in picture",
      "Playing in picture in picture",
      "Back to the window",
      "Fullscreen",
      "Exit fullscreen",
      "Try again",
      "Back 10 seconds",
      "Forward 10 seconds",
      "seconds",
      "Minimize",
      "Back",
      "Auto",
      "On",
      "Off",
      "LIVE",
      "This video can't be played",
      "Unsupported format",
      "Not found",
      "Not allowed",
      "Timed out",
      "Too large",
      "Server error {status}",
      "Network error",
      "Can't play on this device",
      "Can't be played",
      "Not an image",
      "Can't be shown",
      "Can't be shown on this device",
    ])
  }

  /// The words of a language (`en`, `uk`, `de`, `fr`, `es`, `pl`); of any other, English.
  pub fn for_language(language: &str) -> Self {
    match language {
      "uk" => Self::of([
        "Аудіоплеєр",
        "Відеоплеєр",
        "Відтворити",
        "Пауза",
        "Відтворити знову",
        "Попередній",
        "Наступний",
        "Перемішати",
        "Повтор",
        "Ще",
        "Швидкість",
        "Швидкість відтворення",
        "Звичайна",
        "Черга",
        "Зараз грає",
        "Розгорнути",
        "Перемотування",
        "Вимкнути звук",
        "Увімкнути звук",
        "Гучність",
        "Субтитри",
        "Налаштування",
        "Якість",
        "Картинка в картинці",
        "Відтворюється в режимі «картинка в картинці»",
        "Повернути у вікно",
        "На весь екран",
        "Вийти з повноекранного режиму",
        "Спробувати ще раз",
        "Назад на 10 секунд",
        "Вперед на 10 секунд",
        "секунд",
        "Згорнути",
        "Назад",
        "Авто",
        "Увімк.",
        "Вимк.",
        "НАЖИВО",
        "Це відео не вдається відтворити",
        "Непідтримуваний формат",
        "Не знайдено",
        "Не дозволено",
        "Час очікування вичерпано",
        "Завеликий файл",
        "Помилка сервера {status}",
        "Помилка мережі",
        "Не відтворюється на цьому пристрої",
        "Не вдається відтворити",
        "Це не зображення",
        "Не вдається показати",
        "Не показується на цьому пристрої",
      ]),
      "de" => Self::of([
        "Audioplayer",
        "Videoplayer",
        "Wiedergabe",
        "Pause",
        "Erneut abspielen",
        "Vorheriger Titel",
        "Nächster Titel",
        "Zufallswiedergabe",
        "Wiederholen",
        "Mehr",
        "Geschwindigkeit",
        "Wiedergabegeschwindigkeit",
        "Normal",
        "Warteschlange",
        "Läuft gerade",
        "Erweitern",
        "Position",
        "Stummschalten",
        "Stummschaltung aufheben",
        "Lautstärke",
        "Untertitel",
        "Einstellungen",
        "Qualität",
        "Bild im Bild",
        "Wiedergabe im Bild-im-Bild-Modus",
        "Zurück zum Fenster",
        "Vollbild",
        "Vollbild beenden",
        "Erneut versuchen",
        "10 Sekunden zurück",
        "10 Sekunden vor",
        "Sekunden",
        "Minimieren",
        "Zurück",
        "Auto",
        "Ein",
        "Aus",
        "LIVE",
        "Dieses Video kann nicht abgespielt werden",
        "Nicht unterstütztes Format",
        "Nicht gefunden",
        "Nicht erlaubt",
        "Zeitüberschreitung",
        "Zu groß",
        "Serverfehler {status}",
        "Netzwerkfehler",
        "Auf diesem Gerät nicht abspielbar",
        "Wiedergabe nicht möglich",
        "Kein Bild",
        "Kann nicht angezeigt werden",
        "Auf diesem Gerät nicht anzeigbar",
      ]),
      "fr" => Self::of([
        "Lecteur audio",
        "Lecteur vidéo",
        "Lire",
        "Pause",
        "Relire",
        "Précédent",
        "Suivant",
        "Lecture aléatoire",
        "Répéter",
        "Plus",
        "Vitesse",
        "Vitesse de lecture",
        "Normale",
        "File d’attente",
        "Lecture en cours",
        "Agrandir",
        "Position de lecture",
        "Couper le son",
        "Rétablir le son",
        "Volume",
        "Sous-titres",
        "Paramètres",
        "Qualité",
        "Image dans l’image",
        "Lecture en mode image dans l’image",
        "Revenir à la fenêtre",
        "Plein écran",
        "Quitter le plein écran",
        "Réessayer",
        "Reculer de 10 secondes",
        "Avancer de 10 secondes",
        "secondes",
        "Réduire",
        "Retour",
        "Auto",
        "Activé",
        "Désactivé",
        "EN DIRECT",
        "Impossible de lire cette vidéo",
        "Format non pris en charge",
        "Introuvable",
        "Non autorisé",
        "Délai dépassé",
        "Trop volumineux",
        "Erreur du serveur {status}",
        "Erreur réseau",
        "Lecture impossible sur cet appareil",
        "Lecture impossible",
        "Ce n'est pas une image",
        "Affichage impossible",
        "Affichage impossible sur cet appareil",
      ]),
      "es" => Self::of([
        "Reproductor de audio",
        "Reproductor de vídeo",
        "Reproducir",
        "Pausar",
        "Volver a reproducir",
        "Anterior",
        "Siguiente",
        "Aleatorio",
        "Repetir",
        "Más",
        "Velocidad",
        "Velocidad de reproducción",
        "Normal",
        "Cola",
        "Reproduciendo",
        "Ampliar",
        "Posición",
        "Silenciar",
        "Activar sonido",
        "Volumen",
        "Subtítulos",
        "Ajustes",
        "Calidad",
        "Imagen en imagen",
        "Reproduciendo en imagen en imagen",
        "Volver a la ventana",
        "Pantalla completa",
        "Salir de pantalla completa",
        "Reintentar",
        "Retroceder 10 segundos",
        "Avanzar 10 segundos",
        "segundos",
        "Minimizar",
        "Atrás",
        "Auto",
        "Activado",
        "Desactivado",
        "EN DIRECTO",
        "No se puede reproducir este vídeo",
        "Formato no compatible",
        "No encontrado",
        "No permitido",
        "Tiempo de espera agotado",
        "Demasiado grande",
        "Error del servidor {status}",
        "Error de red",
        "No se puede reproducir en este dispositivo",
        "No se puede reproducir",
        "No es una imagen",
        "No se puede mostrar",
        "No se puede mostrar en este dispositivo",
      ]),
      "pl" => Self::of([
        "Odtwarzacz audio",
        "Odtwarzacz wideo",
        "Odtwórz",
        "Wstrzymaj",
        "Odtwórz ponownie",
        "Poprzedni",
        "Następny",
        "Losowo",
        "Powtarzaj",
        "Więcej",
        "Szybkość",
        "Szybkość odtwarzania",
        "Normalna",
        "Kolejka",
        "Teraz odtwarzane",
        "Rozwiń",
        "Przewijanie",
        "Wycisz",
        "Wyłącz wyciszenie",
        "Głośność",
        "Napisy",
        "Ustawienia",
        "Jakość",
        "Obraz w obrazie",
        "Odtwarzanie w trybie obraz w obrazie",
        "Wróć do okna",
        "Pełny ekran",
        "Zamknij pełny ekran",
        "Spróbuj ponownie",
        "Cofnij o 10 sekund",
        "Do przodu o 10 sekund",
        "sekund",
        "Minimalizuj",
        "Wstecz",
        "Auto",
        "Wł.",
        "Wył.",
        "NA ŻYWO",
        "Nie można odtworzyć tego filmu",
        "Nieobsługiwany format",
        "Nie znaleziono",
        "Niedozwolone",
        "Przekroczono limit czasu",
        "Za duży plik",
        "Błąd serwera {status}",
        "Błąd sieci",
        "Nie można odtworzyć na tym urządzeniu",
        "Nie można odtworzyć",
        "To nie jest obraz",
        "Nie można wyświetlić",
        "Nie można wyświetlić na tym urządzeniu",
      ]),
      _ => Self::english(),
    }
  }

  /// What `error` is called: the short line a player shows a person.
  pub fn error(&self, error: &MediaError) -> Arc<str> {
    match error {
      MediaError::Unsupported => self.unsupported.clone(),
      MediaError::NotFound => self.not_found.clone(),
      MediaError::Denied => self.denied.clone(),
      MediaError::TimedOut => self.timed_out.clone(),
      MediaError::TooLarge => self.too_large.clone(),
      MediaError::Server(status) => Arc::from(self.server_error.replace("{status}", &status.to_string())),
      MediaError::Network(_) => self.network_error.clone(),
      MediaError::Unavailable(_) => self.unavailable.clone(),
      MediaError::Other(_) => self.failed.clone(),
    }
  }

  /// What a picture's `error` is called: the short line for a person, in the media's words where they fit it.
  pub fn picture_error(&self, error: &PictureError) -> Arc<str> {
    match error {
      PictureError::NotFound => self.not_found.clone(),
      PictureError::Denied => self.denied.clone(),
      PictureError::TimedOut => self.timed_out.clone(),
      PictureError::TooLarge => self.too_large.clone(),
      PictureError::Server(status) => Arc::from(self.server_error.replace("{status}", &status.to_string())),
      PictureError::Network(_) => self.network_error.clone(),
      PictureError::NotAPicture(_) => self.not_a_picture.clone(),
      PictureError::Unavailable(_) => self.picture_unavailable.clone(),
      PictureError::Other(_) => self.picture_failed.clone(),
    }
  }
}

impl Default for MediaWords {
  fn default() -> Self {
    Self::english()
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn every_language_has_every_word_and_the_server_error_has_its_place_for_the_status() {
    for language in ["en", "uk", "de", "fr", "es", "pl"] {
      let words = MediaWords::for_language(language);
      assert!(words.server_error.contains("{status}"), "{language}");
      assert!(words.error(&MediaError::Server(404)).contains("404"), "{language}");
      assert!(!words.play.is_empty() && !words.failed.is_empty(), "{language}");
      assert!(
        words.picture_error(&PictureError::Server(404)).contains("404"),
        "{language}"
      );
      assert!(
        !words.not_a_picture.is_empty() && !words.picture_failed.is_empty(),
        "{language}"
      );
    }
    assert_eq!(MediaWords::for_language("xx"), MediaWords::english());
  }

  #[test]
  fn an_error_keeps_what_the_system_said_and_shows_what_the_locale_says() {
    let error = MediaError::Network(Arc::from("No such host is known. (os error 11001)"));
    assert_eq!(error.detail(), Some("No such host is known. (os error 11001)"));
    assert_eq!(error.to_string(), "Network error");
    assert_eq!(MediaError::Unsupported.detail(), None);
  }
}