FPLBase
An open source project by FPL.
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Groups Pages
utilities.h
Go to the documentation of this file.
1 // Copyright 2014 Google Inc. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef FPLBASE_UTILITIES_H
16 #define FPLBASE_UTILITIES_H
17 
18 #include <functional>
19 #include <string>
20 #include "fplbase/config.h" // Must come first.
21 
22 #include "mathfu/utilities.h"
23 
24 #if defined(__ANDROID__)
25 #include <jni.h>
26 #if defined(FPLBASE_BACKEND_STDLIB)
27 #include <android/asset_manager.h>
28 #include <android/asset_manager_jni.h>
29 #endif // defined(FPLBASE_BACKEND_STDLIB)
30 #endif
31 
32 namespace fplbase {
33 
34 /// @file
35 /// @brief General utility functions, used by FPLBase, and that might be of use
36 /// to people using the library:
37 /// @addtogroup fplbase_utilities
38 /// @{
39 
40 /// @brief Constants for use with LogInfo, LogError, etc.
41 #ifdef FPLBASE_BACKEND_SDL
43  kApplication = 0, // SDL_LOG_CATEGORY_APPLICATION
44  kError = 1, // SDL_LOG_CATEGORY_ERROR
45  kSystem = 3, // SDL_LOG_CATEGORY_SYSTEM
46  kAudio = 4, // SDL_LOG_CATEGORY_AUDIO
47  kVideo = 5, // SDL_LOG_CATEGORY_VIDEO
48  kRender = 6, // SDL_LOG_CATEGORY_RENDER
49  kInput = 7, // SDL_LOG_CATEGORY_INPUT
50  kCustom = 19, // SDL_LOG_CATEGORY_CUSTOM
51 };
52 #else
53 enum LogCategory {
54  kApplication = 0,
55  kError,
56  kSystem,
57  kAudio,
58  kVideo,
59  kRender,
60  kInput,
61  kCustom
62 };
63 #endif
64 
65 /// @brief Called by `LoadFile()`.
66 typedef std::function<bool(const char *filename, std::string *dest)>
68 
69 /// @brief Enum for use with the `Set/GetPerformanceMode()` functions.
71  // Normal mode. No special actions taken.
72  kNormalPerformance = 0,
73 
74  // High performance mode. Attempt to keep the CPU frequency up.
75  kHighPerformance
76 };
77 
78 #ifdef __ANDROID__
79 /// @brief Used for Android to represent a Vsync callback function.
80 typedef void (*VsyncCallback)(void);
81 
82 /// @brief Used for Android to simulate a keypress. Corresponds to `F24`, which
83 /// is unavailable on most keyboards.
84 const int kDefaultAndroidKeycode = 115;
85 
86 /// @brief Used for Android. Corresponds to the time, in seconds, between
87 /// simulated keypresses.
88 const double kDefaultTimeBetweenPresses = 1.0;
89 
90 /// @brief HighPerformanceParams are used on Android to configure simulated key
91 /// presses, in order to stop the CPU governor (see
92 /// https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt) from
93 /// reducing the CPU frequency when a user is not providing tactile input.
94 ///
95 /// For example, if a user is providing data to the device via a gyroscope, it
96 /// is possible for the CPU governor to reduce the CPU (and potentially the
97 /// GPU) frequency, reducing application performance.
101  time_between_presses(kDefaultTimeBetweenPresses) {}
102  HighPerformanceParams(int keycode, int presses)
103  : android_key_code(keycode), time_between_presses(presses) {}
104 
105  /// @brief The key to press repeatedly, to keep the CPU active.
107  // @brief The time (in seconds) between keypress events.
108  double time_between_presses;
109 };
110 #endif
111 
112 /// @brief Loads a file and returns its contents via string pointer.
113 /// @param[in] filename A UTF-8 C-string representing the file to load.
114 /// @param[out] dest A pointer to a `std::string` to capture the output of
115 /// the file.
116 /// @return Returns `false` if the file couldn't be loaded (usually means it's
117 /// not present, but can also mean there was a read error).
118 bool LoadFileRaw(const char *filename, std::string *dest);
119 
120 /// @brief Loads a file and returns its contents via string pointer.
121 /// @details In contrast to `LoadFileRaw()`, this method simply calls the
122 /// function set by `SetLoadFileFunction()` to read the specified file.
123 /// @param[in] filename A UTF-8 C-string representing the file to load.
124 /// @param[out] dest A pointer to a `std::string` to capture the output of
125 /// the file.
126 /// @return Returns `false` if the file couldn't be loaded (usually means it's
127 /// not present, but can also mean there was a read error).
128 bool LoadFile(const char *filename, std::string *dest);
129 
130 /// @brief Set the function called by `LoadFile()`.
131 /// @param[in] load_file_function The function to be used by `LoadFile()` to
132 /// read files.
133 /// @note If the specified function is nullptr, `LoadFileRaw()` is set as the
134 /// default function.
135 /// @return Returns the function previously set by `LoadFileFunction()`.
137 
138 /// @brief Save a string to a file, overwriting the existing contents.
139 /// @param[in] filename A UTF-8 C-string representing the file to save to.
140 /// @param[in] data A const reference to a `std::string` containing the data
141 /// that should be written to the file specified by `filename`.
142 /// @return Returns `false` if the file could not be written.
143 bool SaveFile(const char *filename, const std::string &data);
144 
145 /// @brief Save a string to a file, overwriting the existing contents.
146 /// @param[in] filename A UTF-8 C-string representing the file to save to.
147 /// @param[in] data A const void pointer to the data that should be written to
148 /// the file specified by `filename`.
149 /// @param[in] size The size of the `data` array to write to the file specified
150 /// by `filename`.
151 /// @return Returns `false` if the file could not be written.
152 bool SaveFile(const char *filename, const void *data, size_t size);
153 
154 /// @brief Load preference settings.
155 ///
156 /// The API uses a dedicated API when an optimal API is available instead of
157 /// regular file IO APIs.
158 /// @param[in] filename A UTF-8 C-string representing the file to load
159 /// preferences from.
160 /// @param[out] dest A pointer to a `std::string` to capture the preferences
161 /// output.
162 /// @return Returns `false` if the file couldn't be loaded (usually means it's
163 /// not present, but can also mean there was a read error).
164 bool LoadPreferences(const char *filename, std::string *dest);
165 
166 /// @brief Save preference settings.
167 ///
168 /// The API uses a dedicated API when an optimal API is available instead of
169 /// regular file IO APIs.
170 /// @param[in] filename A UTF-8 C-string representing the file to save
171 /// preferences to.
172 /// @param[in] data A const void pointer to the data that should be written to
173 /// the file specified by `filename`.
174 /// @param[in] size The size of the `data` array to write to the file specified
175 /// by `filename`.
176 /// @return Returns `false` if the file couldn't be loaded (usually means it's
177 /// not present, but can also mean there was a read error).
178 bool SavePreferences(const char *filename, const void *data, size_t size);
179 
180 /// @brief Load a single integer value to a preference.
181 /// @param[in] key The UTF-8 key for the preference.
182 /// @param[in] initial_value The default value to use if the preference is not
183 /// found.
184 /// @return Returns the preference value.
185 int32_t LoadPreference(const char *key, int32_t initial_value);
186 
187 /// @brief Save a single integer value to a preference.
188 /// @param[in] key The UTF-8 key for the preference.
189 /// @param[in] value The value to save for the preference.
190 bool SavePreference(const char *key, int32_t value);
191 
192 /// @brief Map a file into memory and returns its contents via pointer.
193 /// @details In contrast to `LoadFile()`, this method calls mmap API to map the
194 /// whole or a part of the file.
195 /// @param[in] filename A UTF-8 C-string representing the file to load.
196 /// @param[in] offset An offset of the file contents to map.
197 /// @param[in/out] size A size to map. A size of 0 indicates to map whole file.
198 /// returns a mapped size of the file.
199 /// @return Returns a mapped pointer. nullptr when failed to map the file.
200 const void *MapFile(const char *filename, int32_t offset, int32_t *size);
201 
202 /// @brief Unmap a pointer that is mapped via MapFile() API.
203 /// @param[in] file A pointer to the file, returned via MapFile API.
204 /// @param[in] size A size to unmap.
205 void UnmapFile(const void *file, int32_t size);
206 
207 /// @brief Search and change to a given directory.
208 /// @param binary_dir A C-string corresponding to the current directory
209 /// to start searching from.
210 /// @param target_dir A C-string corresponding to the desired directory
211 /// that should be changed to, if found.
212 /// @return Returns `true` if it's found, `false` otherwise.
213 bool ChangeToUpstreamDir(const char *const binary_dir,
214  const char *const target_dir);
215 
216 /// @brief check if 16bpp MipMap is supported.
217 /// @return Return `true` if 16bpp MipMap generation is supported.
218 /// @note Basically always true, except on certain android devices.
220 
221 /// @brief Get the system's RAM size.
222 /// @return Returns the system RAM size in MB.
223 int32_t GetSystemRamSize();
224 
225 /// @brief Log a format string with `Info` priority to the console.
226 /// @param[in] fmt A C-string format string.
227 /// @param[in] args A variable length argument list for the format
228 /// string `fmt`.
229 void LogInfo(const char *fmt, va_list args);
230 
231 /// @brief Log a format string with `Error` priority to the console.
232 /// @param[in] fmt A C-string format string.
233 /// @param[in] args A variable length argument list for the format
234 /// string `fmt`.
235 void LogError(const char *fmt, va_list args);
236 
237 /// @brief Log a format string with `Info` priority to the console.
238 /// @param[in] category The LogCategory for the message.
239 /// @param[in] fmt A C-string format string.
240 /// @param[in] args A variable length argument list for the format
241 /// string `fmt`.
242 void LogInfo(LogCategory category, const char *fmt, va_list args);
243 
244 /// @brief Log a format string with `Error` priority to the console.
245 /// @param[in] category The LogCategory for the message.
246 /// @param[in] fmt A C-string format string.
247 /// @param[in] args A variable length argument list for the format
248 /// string `fmt`.
249 void LogError(LogCategory category, const char *fmt, va_list args);
250 
251 /// @brief Log a format string with `Info` priority to the console.
252 /// @param[in] fmt A C-string format string.
253 void LogInfo(const char *fmt, ...);
254 
255 /// @brief Log a format string with `Error` priority to the console.
256 /// @param[in] fmt A C-string format string.
257 void LogError(const char *fmt, ...);
258 
259 /// @brief Log a format string with `Info` priority to the console.
260 /// @param[in] category The LogCategory for the message.
261 /// @param[in] fmt A C-string format string.
262 void LogInfo(LogCategory category, const char *fmt, ...);
263 
264 /// @brief Log a format string with `Error` priority to the console.
265 /// @param[in] category The LogCategory for the message.
266 /// @param[in] fmt A C-string format string.
267 void LogError(LogCategory category, const char *fmt, ...);
268 
269 #if defined(__ANDROID__)
270 /// @brief Get the Android activity class.
271 /// @return Returns a pointer to the Java instance of the activity class
272 /// in an Android application.
273 jobject AndroidGetActivity();
274 
275 /// @brief Get the Java native interface object (JNIEnv).
276 /// @return Returns a pointer to the Java native interface object (JNIEnv) of
277 /// the current thread on an Android application.
278 JNIEnv *AndroidGetJNIEnv();
279 
280 /// @brief Register for handling vsync callbacks on android.
281 /// @note As with most callbacks, this will normally be called on a separate
282 /// thread, so you'll need to be careful about thread-safety with anything you
283 /// do during the callback.
284 /// @param callback The VSync callback function to register.
285 /// @return Return value is whatever callback was previously registered. (Or
286 /// `nullptr` if there was none.)
288 
289 /// @brief Blocks until the next time a VSync happens.
290 void WaitForVsync();
291 
292 /// @brief Get Vsync frame id.
293 /// @return Returns a unique ID representing the frame. Guaranteed to change
294 /// every time the frame increments.
295 /// @warning May eventually wrap.
296 int GetVsyncFrameId();
297 
298 /// @brief Triggers a keypress event on an Android device.
299 /// @param[in] android_keycode The key code corresponding to the
300 /// keypress that should be triggered.
301 void SendKeypressEventToAndroid(int android_keycode);
302 
303 /// @brief Get the name of the current activity class.
304 /// @note This can be used by C++ code to determine how the application was
305 /// started.
306 /// @return Returns a `std::string` containing the Android activity name.
307 std::string AndroidGetActivityName();
308 
309 /// @brief Determine whether the activity was started with `Intent.ACTION_VIEW`
310 /// and, if so, return the data the user wants to "view" in the application.
311 /// @return Returns a `std::string` contianing the View intent data.
312 std::string AndroidGetViewIntentData();
313 #endif // __ANDROID__
314 
315 #if defined(__ANDROID__) && defined(FPLBASE_BACKEND_STDLIB)
316 /// @brief Set an Android asset manager.
317 /// @param[in] manager A pointer to an already-created instance of
318 /// `AAssetManager`.
319 /// @note Must call this function once before loading any assets.
320 void SetAAssetManager(AAssetManager *manager);
321 /// @brief Set global Java virtual machine object.
322 /// @note This method should be called only once.
323 void AndroidSetJavaVM(JavaVM* vm, jint jni_version);
324 #endif
325 
326 /// @brief Retrieve a path where an app can store data files.
327 /// @param[in] app_name A C-string corresponding to the name of the
328 /// application.
329 /// @param[out] path A `std::string` to capture the storage path. Contains
330 /// `nullptr` if the function returns `false`.
331 /// @return Returns `true` if a storage path was found. Otherwise it
332 /// returns `false`.
333 bool GetStoragePath(const char *app_name, std::string *path);
334 
335 /// @brief Checks whether Head Mounted Displays, such as Cardboard, are
336 /// supported by the system being run on.
337 /// @return Returns `true` if Head Mounted Displays are supported.
339 
340 /// @brief Checks if the device has a touchscreen.
341 /// @return Returns `true` if the device has a touchscreen.
342 bool TouchScreenDevice();
343 
344 /// @brief Checks whether the device we are running on is an Android TV device.
345 /// @return Returns `true` if the device is an Android TV device.
346 /// @note Always returns `false` when not running on Android.
347 bool IsTvDevice();
348 
349 /// @brief Sets the performance mode.
350 /// @param[in] new_mode The `PerformanceMode` to set.
351 void SetPerformanceMode(PerformanceMode new_mode);
352 
353 /// @brief Get the current performance mode.
354 /// @return Returns the current `PerformanceMode`.
356 
357 /// @brief Relaunch the application.
358 void RelaunchApplication();
359 
360 #ifdef __ANDROID__
361 /// @brief Sets the specific parameters used by high-performance mode on
362 /// Android.
363 /// @param[in] params A const reference to a `HighPerformanceParams` struct
364 /// to set for use with high-performance mode.
366 
367 /// @brief Get the high performance parameters.
368 /// @return Returns the current performance parameters, in the form of a struct.
370 
371 /// @brief Get the Android device's model.
372 /// @return Returns the model of the Android device the app is currently being
373 /// run on.
374 std::string DeviceModel();
375 
376 /// @brief Get the Android device's API level.
377 /// @return Returns the API level of the Android device the app is currently
378 /// being run on.
379 int32_t AndroidGetApiLevel();
380 #endif
381 /// @}
382 } // namespace fplbase
383 
384 #endif // FPLBASE_UTILITIES_H
bool LoadPreferences(const char *filename, std::string *dest)
Load preference settings.
std::string DeviceModel()
Get the Android device's model.
int32_t AndroidGetApiLevel()
Get the Android device's API level.
void WaitForVsync()
Blocks until the next time a VSync happens.
bool MipmapGeneration16bppSupported()
check if 16bpp MipMap is supported.
void SetHighPerformanceParameters(const HighPerformanceParams &params)
Sets the specific parameters used by high-performance mode on Android.
void SetPerformanceMode(PerformanceMode new_mode)
Sets the performance mode.
void RelaunchApplication()
Relaunch the application.
bool SupportsHeadMountedDisplay()
Checks whether Head Mounted Displays, such as Cardboard, are supported by the system being run on...
const HighPerformanceParams & GetHighPerformanceParameters()
Get the high performance parameters.
void LogError(const char *fmt, va_list args)
Log a format string with Error priority to the console.
PerformanceMode GetPerformanceMode()
Get the current performance mode.
const void * MapFile(const char *filename, int32_t offset, int32_t *size)
Map a file into memory and returns its contents via pointer.
int32_t LoadPreference(const char *key, int32_t initial_value)
Load a single integer value to a preference.
bool SaveFile(const char *filename, const std::string &data)
Save a string to a file, overwriting the existing contents.
bool LoadFileRaw(const char *filename, std::string *dest)
Loads a file and returns its contents via string pointer.
bool LoadFile(const char *filename, std::string *dest)
Loads a file and returns its contents via string pointer.
PerformanceMode
Enum for use with the Set/GetPerformanceMode() functions.
Definition: utilities.h:70
const int kDefaultAndroidKeycode
Used for Android to simulate a keypress. Corresponds to F24, which is unavailable on most keyboards...
Definition: utilities.h:84
HighPerformanceParams are used on Android to configure simulated key presses, in order to stop the CP...
Definition: utilities.h:98
bool SavePreference(const char *key, int32_t value)
Save a single integer value to a preference.
LogCategory
Constants for use with LogInfo, LogError, etc.
Definition: utilities.h:42
void UnmapFile(const void *file, int32_t size)
Unmap a pointer that is mapped via MapFile() API.
JNIEnv * AndroidGetJNIEnv()
Get the Java native interface object (JNIEnv).
bool IsTvDevice()
Checks whether the device we are running on is an Android TV device.
bool TouchScreenDevice()
Checks if the device has a touchscreen.
bool ChangeToUpstreamDir(const char *const binary_dir, const char *const target_dir)
Search and change to a given directory.
std::function< bool(const char *filename, std::string *dest)> LoadFileFunction
Called by LoadFile().
Definition: utilities.h:67
void LogInfo(const char *fmt, va_list args)
Log a format string with Info priority to the console.
LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function)
Set the function called by LoadFile().
const double kDefaultTimeBetweenPresses
Used for Android. Corresponds to the time, in seconds, between simulated keypresses.
Definition: utilities.h:88
int32_t GetSystemRamSize()
Get the system's RAM size.
std::string AndroidGetViewIntentData()
Determine whether the activity was started with Intent.ACTION_VIEW and, if so, return the data the us...
int android_key_code
The key to press repeatedly, to keep the CPU active.
Definition: utilities.h:106
jobject AndroidGetActivity()
Get the Android activity class.
bool GetStoragePath(const char *app_name, std::string *path)
Retrieve a path where an app can store data files.
VsyncCallback RegisterVsyncCallback(VsyncCallback callback)
Register for handling vsync callbacks on android.
void(* VsyncCallback)(void)
Used for Android to represent a Vsync callback function.
Definition: utilities.h:80
int GetVsyncFrameId()
Get Vsync frame id.
std::string AndroidGetActivityName()
Get the name of the current activity class.
void SendKeypressEventToAndroid(int android_keycode)
Triggers a keypress event on an Android device.
bool SavePreferences(const char *filename, const void *data, size_t size)
Save preference settings.