platform-cocoa.m 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /*
  2. * Copyright (c) 2013-2014 Ruwen Hahn <[email protected]>
  3. * Hugh "Jim" Bailey <[email protected]>
  4. *
  5. * Permission to use, copy, modify, and distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #include "base.h"
  18. #include "platform.h"
  19. #include "dstr.h"
  20. #include <dlfcn.h>
  21. #include <time.h>
  22. #include <unistd.h>
  23. #include <CoreServices/CoreServices.h>
  24. #include <mach/mach.h>
  25. #include <mach/mach_time.h>
  26. #include <IOKit/pwr_mgt/IOPMLib.h>
  27. #import <Cocoa/Cocoa.h>
  28. /* clock function selection taken from libc++ */
  29. static uint64_t ns_time_simple()
  30. {
  31. return mach_absolute_time();
  32. }
  33. static double ns_time_compute_factor()
  34. {
  35. mach_timebase_info_data_t info = {1, 1};
  36. mach_timebase_info(&info);
  37. return ((double)info.numer) / info.denom;
  38. }
  39. static uint64_t ns_time_full()
  40. {
  41. static double factor = 0.;
  42. if (factor == 0.) factor = ns_time_compute_factor();
  43. return (uint64_t)(mach_absolute_time() * factor);
  44. }
  45. typedef uint64_t (*time_func)();
  46. static time_func ns_time_select_func()
  47. {
  48. mach_timebase_info_data_t info = {1, 1};
  49. mach_timebase_info(&info);
  50. if (info.denom == info.numer)
  51. return ns_time_simple;
  52. return ns_time_full;
  53. }
  54. uint64_t os_gettime_ns(void)
  55. {
  56. static time_func f = NULL;
  57. if (!f) f = ns_time_select_func();
  58. return f();
  59. }
  60. /* gets the location [domain mask]/Library/Application Support/[name] */
  61. static int os_get_path_internal(char *dst, size_t size, const char *name,
  62. NSSearchPathDomainMask domainMask)
  63. {
  64. NSArray *paths = NSSearchPathForDirectoriesInDomains(
  65. NSApplicationSupportDirectory, domainMask, YES);
  66. if([paths count] == 0)
  67. bcrash("Could not get home directory (platform-cocoa)");
  68. NSString *application_support = paths[0];
  69. const char *base_path = [application_support UTF8String];
  70. if (!name || !*name)
  71. return snprintf(dst, size, "%s", base_path);
  72. else
  73. return snprintf(dst, size, "%s/%s", base_path, name);
  74. }
  75. static char *os_get_path_ptr_internal(const char *name,
  76. NSSearchPathDomainMask domainMask)
  77. {
  78. NSArray *paths = NSSearchPathForDirectoriesInDomains(
  79. NSApplicationSupportDirectory, domainMask, YES);
  80. if([paths count] == 0)
  81. bcrash("Could not get home directory (platform-cocoa)");
  82. NSString *application_support = paths[0];
  83. NSUInteger len = [application_support
  84. lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  85. char *path_ptr = bmalloc(len+1);
  86. path_ptr[len] = 0;
  87. memcpy(path_ptr, [application_support UTF8String], len);
  88. struct dstr path;
  89. dstr_init_move_array(&path, path_ptr);
  90. dstr_cat(&path, "/");
  91. dstr_cat(&path, name);
  92. return path.array;
  93. }
  94. int os_get_config_path(char *dst, size_t size, const char *name)
  95. {
  96. return os_get_path_internal(dst, size, name, NSUserDomainMask);
  97. }
  98. char *os_get_config_path_ptr(const char *name)
  99. {
  100. return os_get_path_ptr_internal(name, NSUserDomainMask);
  101. }
  102. int os_get_program_data_path(char *dst, size_t size, const char *name)
  103. {
  104. return os_get_path_internal(dst, size, name, NSLocalDomainMask);
  105. }
  106. char *os_get_program_data_path_ptr(const char *name)
  107. {
  108. return os_get_path_ptr_internal(name, NSLocalDomainMask);
  109. }
  110. struct os_cpu_usage_info {
  111. int64_t last_cpu_time;
  112. int64_t last_sys_time;
  113. int core_count;
  114. };
  115. static inline void add_time_value(time_value_t *dst, time_value_t *a,
  116. time_value_t *b)
  117. {
  118. dst->microseconds = a->microseconds + b->microseconds;
  119. dst->seconds = a->seconds + b->seconds;
  120. if (dst->microseconds >= 1000000) {
  121. dst->seconds += dst->microseconds / 1000000;
  122. dst->microseconds %= 1000000;
  123. }
  124. }
  125. static bool get_time_info(int64_t *cpu_time, int64_t *sys_time)
  126. {
  127. mach_port_t task = mach_task_self();
  128. struct task_thread_times_info thread_data;
  129. struct task_basic_info_64 task_data;
  130. mach_msg_type_number_t count;
  131. kern_return_t kern_ret;
  132. time_value_t cur_time;
  133. *cpu_time = 0;
  134. *sys_time = 0;
  135. count = TASK_THREAD_TIMES_INFO_COUNT;
  136. kern_ret = task_info(task, TASK_THREAD_TIMES_INFO,
  137. (task_info_t)&thread_data, &count);
  138. if (kern_ret != KERN_SUCCESS)
  139. return false;
  140. count = TASK_BASIC_INFO_64_COUNT;
  141. kern_ret = task_info(task, TASK_BASIC_INFO_64,
  142. (task_info_t)&task_data, &count);
  143. if (kern_ret != KERN_SUCCESS)
  144. return false;
  145. add_time_value(&cur_time, &thread_data.user_time,
  146. &thread_data.system_time);
  147. add_time_value(&cur_time, &cur_time, &task_data.user_time);
  148. add_time_value(&cur_time, &cur_time, &task_data.system_time);
  149. *cpu_time = os_gettime_ns() / 1000;
  150. *sys_time = cur_time.seconds * 1000000 + cur_time.microseconds;
  151. return true;
  152. }
  153. os_cpu_usage_info_t *os_cpu_usage_info_start(void)
  154. {
  155. struct os_cpu_usage_info *info = bmalloc(sizeof(*info));
  156. if (!get_time_info(&info->last_cpu_time, &info->last_sys_time)) {
  157. bfree(info);
  158. return NULL;
  159. }
  160. info->core_count = sysconf(_SC_NPROCESSORS_ONLN);
  161. return info;
  162. }
  163. double os_cpu_usage_info_query(os_cpu_usage_info_t *info)
  164. {
  165. int64_t sys_time, cpu_time;
  166. int64_t sys_time_delta, cpu_time_delta;
  167. if (!info || !get_time_info(&cpu_time, &sys_time))
  168. return 0.0;
  169. sys_time_delta = sys_time - info->last_sys_time;
  170. cpu_time_delta = cpu_time - info->last_cpu_time;
  171. if (cpu_time_delta == 0)
  172. return 0.0;
  173. info->last_sys_time = sys_time;
  174. info->last_cpu_time = cpu_time;
  175. return (double)sys_time_delta * 100.0 / (double)cpu_time_delta /
  176. (double)info->core_count;
  177. }
  178. void os_cpu_usage_info_destroy(os_cpu_usage_info_t *info)
  179. {
  180. if (info)
  181. bfree(info);
  182. }
  183. os_performance_token_t *os_request_high_performance(const char *reason)
  184. {
  185. @autoreleasepool {
  186. NSProcessInfo *pi = [NSProcessInfo processInfo];
  187. SEL sel = @selector(beginActivityWithOptions:reason:);
  188. if (![pi respondsToSelector:sel])
  189. return nil;
  190. //taken from http://stackoverflow.com/a/20100906
  191. id activity = [pi beginActivityWithOptions:0x00FFFFFF
  192. reason:@(reason)];
  193. return CFBridgingRetain(activity);
  194. }
  195. }
  196. void os_end_high_performance(os_performance_token_t *token)
  197. {
  198. @autoreleasepool {
  199. NSProcessInfo *pi = [NSProcessInfo processInfo];
  200. SEL sel = @selector(beginActivityWithOptions:reason:);
  201. if (![pi respondsToSelector:sel])
  202. return;
  203. [pi endActivity:CFBridgingRelease(token)];
  204. }
  205. }
  206. struct os_inhibit_info {
  207. CFStringRef reason;
  208. IOPMAssertionID sleep_id;
  209. IOPMAssertionID user_id;
  210. bool active;
  211. };
  212. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  213. {
  214. struct os_inhibit_info *info = bzalloc(sizeof(*info));
  215. if (!reason)
  216. info->reason = CFStringCreateWithCString(kCFAllocatorDefault,
  217. reason, kCFStringEncodingUTF8);
  218. else
  219. info->reason = CFStringCreateCopy(kCFAllocatorDefault,
  220. CFSTR(""));
  221. return info;
  222. }
  223. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  224. {
  225. IOReturn success;
  226. if (!info)
  227. return false;
  228. if (info->active == active)
  229. return false;
  230. if (active) {
  231. IOPMAssertionDeclareUserActivity(info->reason,
  232. kIOPMUserActiveLocal, &info->user_id);
  233. success = IOPMAssertionCreateWithName(
  234. kIOPMAssertionTypeNoDisplaySleep,
  235. kIOPMAssertionLevelOn, info->reason,
  236. &info->sleep_id);
  237. if (success != kIOReturnSuccess) {
  238. blog(LOG_WARNING, "Failed to disable sleep");
  239. return false;
  240. }
  241. } else {
  242. IOPMAssertionRelease(info->sleep_id);
  243. }
  244. info->active = active;
  245. return true;
  246. }
  247. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  248. {
  249. if (info) {
  250. os_inhibit_sleep_set_active(info, false);
  251. CFRelease(info->reason);
  252. bfree(info);
  253. }
  254. }