The Battle for Wesnoth  1.19.24+dev
apple_battery_info.mm
Go to the documentation of this file.
1 /*
2  Copyright (C) 2018 - 2025
3  by Martin HrubĂ˝ <hrubymar10@gmail.com>
4  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
5 
6  This program is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation; either version 2 of the License, or
9  (at your option) any later version.
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY.
12 
13  See the COPYING file for more details.
14 */
15 
16 #ifdef __APPLE__
17 
18 #include "apple_battery_info.hpp"
19 
20 #if defined(SDL_PLATFORM_IOS)
21 
22 #import <UIKit/UIDevice.h>
23 
24 #else
25 
26 #import <Foundation/Foundation.h>
27 #import <IOKit/ps/IOPowerSources.h>
28 #import <IOKit/ps/IOPSKeys.h>
29 #import <IOKit/pwr_mgt/IOPM.h>
30 
31 #endif
32 
33 namespace desktop {
34 namespace battery_info {
35 namespace apple {
36 
38 #if defined(SDL_PLATFORM_IOS)
39  UIDevice.currentDevice.batteryMonitoringEnabled = YES;
40  if (UIDevice.currentDevice.batteryState == UIDeviceBatteryStateUnknown) {
41  return false;
42  } else {
43  return true;
44  }
45 #else
46  if (get_battery_percentage() == -1) {
47  return false;
48  } else {
49  return true;
50  }
51 #endif
52 }
53 
54 #if !defined(SDL_PLATFORM_IOS)
55 inline NSDictionary* get_iops_battery_info() {
56  //Code taken from https://github.com/Hammerspoon/hammerspoon/blob/master/extensions/battery/internal.m
57  CFTypeRef info = IOPSCopyPowerSourcesInfo();
58 
59  if (info == NULL)
60  return NULL;
61 
62 
63  CFArrayRef list = IOPSCopyPowerSourcesList(info);
64 
65  if (list == NULL || !CFArrayGetCount(list)) {
66  if (list)
67  CFRelease(list);
68 
69  CFRelease(info);
70  return NULL;
71  }
72 
73  CFDictionaryRef battery = CFDictionaryCreateCopy(NULL, IOPSGetPowerSourceDescription(info, CFArrayGetValueAtIndex(list, 0)));
74 
75  CFRelease(list);
76  CFRelease(info);
77 
78  return static_cast<NSDictionary*>(battery);
79 }
80 #endif
81 
82 double get_battery_percentage() {
83 #if defined(SDL_PLATFORM_IOS)
84  return UIDevice.currentDevice.batteryLevel * 100;
85 #else
86  //Code taken from https://github.com/Hammerspoon/hammerspoon/blob/master/extensions/battery/internal.m
87  NSDictionary* battery = get_iops_battery_info();
88 
89  NSNumber *maxCapacity = [battery objectForKey:@kIOPSMaxCapacityKey];
90  NSNumber *currentCapacity = [battery objectForKey:@kIOPSCurrentCapacityKey];
91 
92  if (maxCapacity && currentCapacity) {
93  return ([currentCapacity doubleValue] / [maxCapacity doubleValue]) * 100;
94  } else {
95  return -1;
96  }
97 #endif
98 }
99 
100 } // end namespace apple
101 } // end namespace battery_info
102 } // end namespace desktop
103 
104 #endif //end __APPLE__
logger & info()
Definition: log.cpp:351