1 /**
2 * Copyright © Novelate 2020
3 * License: MIT (https://github.com/Novelate/NovelateEngine/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 * Website: https://novelate.com/
6 * ------
7 * Novelate is a free and open-source visual novel engine and framework written in the D programming language.
8 * It can be used freely for both personal and commercial projects.
9 * ------
10 * Module Description:
11 * This module handles media files. Currently only supports image files for relative sizes as of now.
12 */
13 module novelate.media;
14 
15 /// Wrapper around a media file.
16 final class NovelateMedia
17 {
18   private:
19   /// The name.
20   string _name;
21   /// The path.
22   string _path;
23 
24   public:
25   final:
26   /**
27   * Creates a new media file.
28   * Params:
29   *   name = The name of the media file.
30   *   path = The path of the media file.
31   */
32   this(string name, string path)
33   {
34     _name = name;
35     _path = path;
36   }
37 
38   @property
39   {
40     /// Gets the name.
41     string name() { return _name; }
42 
43     /// Gets the path.
44     string path() { return _path; }
45   }
46 
47   /**
48   * Gets a path relative to the given resolution. Ex. car.png is retrieved as ex. car_1280.png" if a relative file is found.
49   * Params:
50   *   width = The width to be relative to. Usually best kept within the available resolutions such as 800, 1024 and 1280.
51   * Returns:
52   *   The path of the media file relative to its resolution if a relative file is found, otherwise it returns the original media file path.
53   */
54   string relativePath(size_t width)
55   {
56     import std.array : replace;
57     import std.file : exists;
58     import std.conv : to;
59 
60     auto newPath = path
61     .replace(".png", "_" ~ to!string(width) ~ ".png")
62     .replace(".jpg", "_" ~ to!string(width) ~ ".jpg")
63     .replace(".jpeg", "_" ~ to!string(width) ~ ".jpeg")
64     .replace(".jfif", "_" ~ to!string(width) ~ ".jfif");
65 
66     if (!exists(newPath))
67     {
68       return path;
69     }
70 
71     return newPath;
72   }
73 }
74 
75 /// The collection of media files.
76 private NovelateMedia[string] _mediaFiles;
77 
78 /**
79 * Adds a media file.
80 * Params:
81 *   name = The name of the media file.
82 *   path = The path of the media file.
83 */
84 void addMediaFile(string name, string path)
85 {
86   _mediaFiles[name] = new NovelateMedia(name, path);
87 }
88 
89 /**
90 * Gets a media file.
91 * Params:
92 *   name = The name of the media file.
93 * Returns:
94 *   The media file from the media file collection.
95 */
96 NovelateMedia getMediaFile(string name)
97 {
98   return _mediaFiles.get(name, null);
99 }