previous_session_info.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #import "components/previous_session_info/previous_session_info.h"
  5. #include <mach/mach.h>
  6. #import <UIKit/UIKit.h>
  7. #include "base/ios/ios_util.h"
  8. #include "base/strings/sys_string_conversions.h"
  9. #include "base/system/sys_info.h"
  10. #include "base/time/time.h"
  11. #include "base/timer/timer.h"
  12. #import "components/previous_session_info/previous_session_info_private.h"
  13. #include "components/version_info/version_info.h"
  14. #if !defined(__has_feature) || !__has_feature(objc_arc)
  15. #error "This file requires ARC support."
  16. #endif
  17. using previous_session_info_constants::DeviceBatteryState;
  18. using previous_session_info_constants::DeviceThermalState;
  19. namespace {
  20. // Returns timestamp (in seconds since January 2001) when OS has started.
  21. NSTimeInterval GetOSStartTimeIntervalSinceReferenceDate() {
  22. return NSDate.timeIntervalSinceReferenceDate -
  23. NSProcessInfo.processInfo.systemUptime;
  24. }
  25. // Translates a UIDeviceBatteryState value to DeviceBatteryState value.
  26. DeviceBatteryState GetBatteryStateFromUIDeviceBatteryState(
  27. UIDeviceBatteryState device_battery_state) {
  28. switch (device_battery_state) {
  29. case UIDeviceBatteryStateUnknown:
  30. return DeviceBatteryState::kUnknown;
  31. case UIDeviceBatteryStateUnplugged:
  32. return DeviceBatteryState::kUnplugged;
  33. case UIDeviceBatteryStateCharging:
  34. return DeviceBatteryState::kCharging;
  35. case UIDeviceBatteryStateFull:
  36. return DeviceBatteryState::kFull;
  37. }
  38. return DeviceBatteryState::kUnknown;
  39. }
  40. // Translates a NSProcessInfoThermalState value to DeviceThermalState value.
  41. DeviceThermalState GetThermalStateFromNSProcessInfoThermalState(
  42. NSProcessInfoThermalState process_info_thermal_state) {
  43. switch (process_info_thermal_state) {
  44. case NSProcessInfoThermalStateNominal:
  45. return DeviceThermalState::kNominal;
  46. case NSProcessInfoThermalStateFair:
  47. return DeviceThermalState::kFair;
  48. case NSProcessInfoThermalStateSerious:
  49. return DeviceThermalState::kSerious;
  50. case NSProcessInfoThermalStateCritical:
  51. return DeviceThermalState::kCritical;
  52. }
  53. return DeviceThermalState::kUnknown;
  54. }
  55. // NSUserDefaults keys.
  56. // - The (string) application version.
  57. NSString* const kLastRanVersion = @"LastRanVersion";
  58. // - The (string) device language.
  59. NSString* const kLastRanLanguage = @"LastRanLanguage";
  60. // - The (integer) available device storage, in kilobytes.
  61. NSString* const kPreviousSessionInfoAvailableDeviceStorage =
  62. @"PreviousSessionInfoAvailableDeviceStorage";
  63. // - The (float) battery charge level.
  64. NSString* const kPreviousSessionInfoBatteryLevel =
  65. @"PreviousSessionInfoBatteryLevel";
  66. // - The (integer) underlying value of the DeviceBatteryState enum representing
  67. // the device battery state.
  68. NSString* const kPreviousSessionInfoBatteryState =
  69. @"PreviousSessionInfoBatteryState";
  70. // - The (Date) of the recording start.
  71. NSString* const kPreviousSessionInfoStartTime = @"PreviousSessionInfoStartTime";
  72. // - The (Date) of the estimated end of the session.
  73. NSString* const kPreviousSessionInfoEndTime = @"PreviousSessionInfoEndTime";
  74. // - The (string) OS version.
  75. NSString* const kPreviousSessionInfoOSVersion = @"PreviousSessionInfoOSVersion";
  76. // - The (integer) underlying value of the DeviceThermalState enum representing
  77. // the device thermal state.
  78. NSString* const kPreviousSessionInfoThermalState =
  79. @"PreviousSessionInfoThermalState";
  80. // TODO(crbug.com/1266034): Remove key for no longer logged state.
  81. // - A (boolean) describing whether or not low power mode is enabled.
  82. NSString* const kPreviousSessionInfoLowPowerMode =
  83. @"PreviousSessionInfoLowPowerMode";
  84. // TODO(crbug.com/1295763): Remove key for no longer used state.
  85. // - A (boolean) describing whether the last session was on Multi-Window enabled
  86. // version of the application.
  87. NSString* const kPreviousSessionInfoMultiWindowEnabled =
  88. @"PreviousSessionInfoMultiWindowEnabled";
  89. // - A (boolean) describing whether the last session received
  90. // ApplicationWillTerminate Notification.
  91. NSString* const kPreviousSessionInfoAppWillTerminate =
  92. @"PreviousSessionInfoAppWillTerminate";
  93. } // namespace
  94. namespace previous_session_info_constants {
  95. NSString* const kPreviousSessionInfoApplicationState =
  96. @"PreviousSessionInfoApplicationState";
  97. NSString* const kDidSeeMemoryWarningShortlyBeforeTerminating =
  98. @"DidSeeMemoryWarning";
  99. NSString* const kOSStartTime = @"OSStartTime";
  100. NSString* const kPreviousSessionInfoRestoringSession =
  101. @"PreviousSessionInfoRestoringSession";
  102. NSString* const kPreviousSessionInfoConnectedSceneSessionIDs =
  103. @"PreviousSessionInfoConnectedSceneSessionIDs";
  104. NSString* const kPreviousSessionInfoParams = @"PreviousSessionInfoParams";
  105. NSString* const kPreviousSessionInfoMemoryFootprint =
  106. @"PreviousSessionInfoMemoryFootprint";
  107. NSString* const kPreviousSessionInfoTabCount = @"PreviousSessionInfoTabCount";
  108. NSString* const kPreviousSessionInfoOTRTabCount =
  109. @"PreviousSessionInfoOTRTabCount";
  110. } // namespace previous_session_info_constants
  111. @interface PreviousSessionInfo ()
  112. // Whether beginRecordingCurrentSession was called.
  113. @property(nonatomic, assign) BOOL didBeginRecordingCurrentSession;
  114. // Whether recording data is in progress.
  115. @property(nonatomic, assign) BOOL recordingCurrentSession;
  116. // Used for setting and resetting kPreviousSessionInfoRestoringSession flag.
  117. // Can be greater than one if multiple sessions are being restored in parallel.
  118. @property(atomic, assign) int numberOfSessionsBeingRestored;
  119. // Redefined to be read-write.
  120. @property(nonatomic, assign) NSInteger availableDeviceStorage;
  121. @property(nonatomic, assign) float deviceBatteryLevel;
  122. @property(nonatomic, assign) DeviceBatteryState deviceBatteryState;
  123. @property(nonatomic, assign) DeviceThermalState deviceThermalState;
  124. @property(nonatomic, assign) BOOL didSeeMemoryWarningShortlyBeforeTerminating;
  125. @property(nonatomic, assign) BOOL isFirstSessionAfterUpgrade;
  126. @property(nonatomic, assign) BOOL isFirstSessionAfterLanguageChange;
  127. @property(nonatomic, assign) BOOL OSRestartedAfterPreviousSession;
  128. @property(nonatomic, strong) NSString* OSVersion;
  129. @property(nonatomic, strong) NSDate* sessionStartTime;
  130. @property(nonatomic, strong) NSDate* sessionEndTime;
  131. @property(nonatomic, assign) BOOL terminatedDuringSessionRestoration;
  132. @property(nonatomic, strong) NSMutableSet<NSString*>* connectedSceneSessionsIDs;
  133. @property(nonatomic, copy) NSDictionary<NSString*, NSString*>* reportParameters;
  134. @property(nonatomic, assign) NSInteger memoryFootprint;
  135. @property(nonatomic, assign) BOOL applicationWillTerminateWasReceived;
  136. @property(nonatomic, assign) NSInteger tabCount;
  137. @property(nonatomic, assign) NSInteger OTRTabCount;
  138. @end
  139. @implementation PreviousSessionInfo {
  140. std::unique_ptr<UIApplicationState> _applicationState;
  141. base::RepeatingTimer _memoryFootprintUpdateTimer;
  142. }
  143. // Singleton PreviousSessionInfo.
  144. static PreviousSessionInfo* gSharedInstance = nil;
  145. + (instancetype)sharedInstance {
  146. if (!gSharedInstance) {
  147. gSharedInstance = [[PreviousSessionInfo alloc] init];
  148. // Load the persisted information.
  149. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  150. gSharedInstance->_applicationState.reset();
  151. if ([defaults objectForKey:previous_session_info_constants::
  152. kPreviousSessionInfoApplicationState]) {
  153. gSharedInstance->_applicationState = std::make_unique<UIApplicationState>(
  154. static_cast<UIApplicationState>([defaults
  155. integerForKey:previous_session_info_constants::
  156. kPreviousSessionInfoApplicationState]));
  157. }
  158. gSharedInstance.availableDeviceStorage = -1;
  159. if ([defaults objectForKey:kPreviousSessionInfoAvailableDeviceStorage]) {
  160. gSharedInstance.availableDeviceStorage =
  161. [defaults integerForKey:kPreviousSessionInfoAvailableDeviceStorage];
  162. }
  163. gSharedInstance.didSeeMemoryWarningShortlyBeforeTerminating =
  164. [defaults boolForKey:previous_session_info_constants::
  165. kDidSeeMemoryWarningShortlyBeforeTerminating];
  166. gSharedInstance.deviceBatteryState = static_cast<DeviceBatteryState>(
  167. [defaults integerForKey:kPreviousSessionInfoBatteryState]);
  168. gSharedInstance.deviceBatteryLevel =
  169. [defaults floatForKey:kPreviousSessionInfoBatteryLevel];
  170. gSharedInstance.deviceThermalState = static_cast<DeviceThermalState>(
  171. [defaults integerForKey:kPreviousSessionInfoThermalState]);
  172. gSharedInstance.sessionStartTime =
  173. [defaults objectForKey:kPreviousSessionInfoStartTime];
  174. gSharedInstance.sessionEndTime =
  175. [defaults objectForKey:kPreviousSessionInfoEndTime];
  176. NSString* versionOfOSAtLastRun =
  177. [defaults stringForKey:kPreviousSessionInfoOSVersion];
  178. gSharedInstance.OSVersion = versionOfOSAtLastRun;
  179. NSString* lastRanVersion = [defaults stringForKey:kLastRanVersion];
  180. NSString* currentVersion =
  181. base::SysUTF8ToNSString(version_info::GetVersionNumber());
  182. gSharedInstance.isFirstSessionAfterUpgrade =
  183. ![lastRanVersion isEqualToString:currentVersion];
  184. // This key is no longer being used so we remove it here,
  185. // but this should be cleaned-up in many milestones.
  186. // TODO(crbug.com/1295763): Remove this line.
  187. [[NSUserDefaults standardUserDefaults]
  188. removeObjectForKey:kPreviousSessionInfoMultiWindowEnabled];
  189. gSharedInstance.connectedSceneSessionsIDs = [NSMutableSet
  190. setWithArray:[defaults
  191. stringArrayForKey:
  192. previous_session_info_constants::
  193. kPreviousSessionInfoConnectedSceneSessionIDs]];
  194. NSTimeInterval lastSystemStartTime =
  195. [defaults doubleForKey:previous_session_info_constants::kOSStartTime];
  196. gSharedInstance.OSRestartedAfterPreviousSession =
  197. // Allow 5 seconds variation to account for rounding error.
  198. (abs(lastSystemStartTime - GetOSStartTimeIntervalSinceReferenceDate()) >
  199. 5) &&
  200. // Ensure that previous session actually exists.
  201. lastSystemStartTime;
  202. NSString* lastRanLanguage = [defaults stringForKey:kLastRanLanguage];
  203. NSString* currentLanguage = [[NSLocale preferredLanguages] objectAtIndex:0];
  204. gSharedInstance.isFirstSessionAfterLanguageChange =
  205. ![lastRanLanguage isEqualToString:currentLanguage];
  206. gSharedInstance.terminatedDuringSessionRestoration =
  207. [defaults boolForKey:previous_session_info_constants::
  208. kPreviousSessionInfoRestoringSession];
  209. gSharedInstance.reportParameters =
  210. [defaults dictionaryForKey:previous_session_info_constants::
  211. kPreviousSessionInfoParams];
  212. gSharedInstance.memoryFootprint =
  213. [defaults integerForKey:previous_session_info_constants::
  214. kPreviousSessionInfoMemoryFootprint];
  215. gSharedInstance.applicationWillTerminateWasReceived =
  216. [defaults boolForKey:kPreviousSessionInfoAppWillTerminate];
  217. gSharedInstance.tabCount =
  218. [defaults integerForKey:previous_session_info_constants::
  219. kPreviousSessionInfoTabCount];
  220. gSharedInstance.OTRTabCount =
  221. [defaults integerForKey:previous_session_info_constants::
  222. kPreviousSessionInfoOTRTabCount];
  223. }
  224. return gSharedInstance;
  225. }
  226. + (void)resetSharedInstanceForTesting {
  227. gSharedInstance = nil;
  228. }
  229. - (void)beginRecordingCurrentSession {
  230. if (self.didBeginRecordingCurrentSession)
  231. return;
  232. self.didBeginRecordingCurrentSession = YES;
  233. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  234. // Set the current Chrome version.
  235. NSString* currentVersion =
  236. base::SysUTF8ToNSString(version_info::GetVersionNumber());
  237. [defaults setObject:currentVersion forKey:kLastRanVersion];
  238. // Set the current OS start time.
  239. [defaults setDouble:GetOSStartTimeIntervalSinceReferenceDate()
  240. forKey:previous_session_info_constants::kOSStartTime];
  241. // Set the current OS version.
  242. NSString* currentOSVersion =
  243. base::SysUTF8ToNSString(base::SysInfo::OperatingSystemVersion());
  244. [defaults setObject:currentOSVersion forKey:kPreviousSessionInfoOSVersion];
  245. // Set the current language.
  246. NSString* currentLanguage = [[NSLocale preferredLanguages] objectAtIndex:0];
  247. [defaults setObject:currentLanguage forKey:kLastRanLanguage];
  248. // Clear the memory warning flag.
  249. [defaults
  250. removeObjectForKey:previous_session_info_constants::
  251. kDidSeeMemoryWarningShortlyBeforeTerminating];
  252. [[NSUserDefaults standardUserDefaults]
  253. removeObjectForKey:kPreviousSessionInfoAppWillTerminate];
  254. [[NSUserDefaults standardUserDefaults]
  255. removeObjectForKey:kPreviousSessionInfoLowPowerMode];
  256. [defaults setObject:[NSDate date] forKey:kPreviousSessionInfoStartTime];
  257. [[NSNotificationCenter defaultCenter]
  258. addObserver:self
  259. selector:@selector(updateApplicationState)
  260. name:UIApplicationDidEnterBackgroundNotification
  261. object:nil];
  262. [[NSNotificationCenter defaultCenter]
  263. addObserver:self
  264. selector:@selector(updateApplicationState)
  265. name:UIApplicationWillEnterForegroundNotification
  266. object:nil];
  267. [[NSNotificationCenter defaultCenter]
  268. addObserver:self
  269. selector:@selector(protectedDataWillBecomeUnavailable)
  270. name:UIApplicationProtectedDataWillBecomeUnavailable
  271. object:nil];
  272. [[NSNotificationCenter defaultCenter]
  273. addObserver:self
  274. selector:@selector(protectedDataDidBecomeAvailable)
  275. name:UIApplicationProtectedDataWillBecomeUnavailable
  276. object:nil];
  277. [[NSNotificationCenter defaultCenter]
  278. addObserver:self
  279. selector:@selector(updateApplicationState)
  280. name:UIApplicationDidBecomeActiveNotification
  281. object:nil];
  282. [[NSNotificationCenter defaultCenter]
  283. addObserver:self
  284. selector:@selector(updateApplicationState)
  285. name:UIApplicationWillResignActiveNotification
  286. object:nil];
  287. [UIDevice currentDevice].batteryMonitoringEnabled = YES;
  288. [[NSNotificationCenter defaultCenter]
  289. addObserver:self
  290. selector:@selector(updateStoredBatteryLevel)
  291. name:UIDeviceBatteryLevelDidChangeNotification
  292. object:nil];
  293. [[NSNotificationCenter defaultCenter]
  294. addObserver:self
  295. selector:@selector(updateStoredBatteryState)
  296. name:UIDeviceBatteryStateDidChangeNotification
  297. object:nil];
  298. [[NSNotificationCenter defaultCenter]
  299. addObserver:self
  300. selector:@selector(updateStoredThermalState)
  301. name:NSProcessInfoThermalStateDidChangeNotification
  302. object:nil];
  303. [[NSNotificationCenter defaultCenter]
  304. addObserver:self
  305. selector:@selector(applicationWillTerminate)
  306. name:UIApplicationWillTerminateNotification
  307. object:nil];
  308. [self resumeRecordingCurrentSession];
  309. }
  310. - (void)startRecordingMemoryFootprintWithInterval:(base::TimeDelta)interval {
  311. _memoryFootprintUpdateTimer.Start(FROM_HERE, interval, base::BindRepeating(^{
  312. [self updateMemoryFootprint];
  313. }));
  314. }
  315. - (void)stopRecordingMemoryFootprint {
  316. _memoryFootprintUpdateTimer.Stop();
  317. }
  318. - (void)resumeRecordingCurrentSession {
  319. if (self.recordingCurrentSession)
  320. return;
  321. self.recordingCurrentSession = YES;
  322. [self updateApplicationState];
  323. [self updateStoredBatteryLevel];
  324. [self updateStoredBatteryState];
  325. [self updateStoredThermalState];
  326. // Save critical state information for crash detection.
  327. [[NSUserDefaults standardUserDefaults] synchronize];
  328. }
  329. - (void)pauseRecordingCurrentSession {
  330. self.recordingCurrentSession = NO;
  331. }
  332. - (void)protectedDataWillBecomeUnavailable {
  333. [self pauseRecordingCurrentSession];
  334. }
  335. - (void)protectedDataDidBecomeAvailable {
  336. [self resumeRecordingCurrentSession];
  337. }
  338. - (UIApplicationState*)applicationState {
  339. return _applicationState.get();
  340. }
  341. - (void)updateAvailableDeviceStorage:(NSInteger)availableStorage {
  342. if (!self.recordingCurrentSession)
  343. return;
  344. [[NSUserDefaults standardUserDefaults]
  345. setInteger:availableStorage
  346. forKey:kPreviousSessionInfoAvailableDeviceStorage];
  347. [self updateSessionEndTime];
  348. }
  349. - (void)updateSessionEndTime {
  350. if (!self.recordingCurrentSession)
  351. return;
  352. [[NSUserDefaults standardUserDefaults] setObject:[NSDate date]
  353. forKey:kPreviousSessionInfoEndTime];
  354. }
  355. - (void)updateStoredBatteryLevel {
  356. if (!self.recordingCurrentSession)
  357. return;
  358. [[NSUserDefaults standardUserDefaults]
  359. setFloat:[UIDevice currentDevice].batteryLevel
  360. forKey:kPreviousSessionInfoBatteryLevel];
  361. [self updateSessionEndTime];
  362. }
  363. - (void)updateApplicationState {
  364. if (!self.recordingCurrentSession)
  365. return;
  366. [[NSUserDefaults standardUserDefaults]
  367. setInteger:UIApplication.sharedApplication.applicationState
  368. forKey:previous_session_info_constants::
  369. kPreviousSessionInfoApplicationState];
  370. [self updateSessionEndTime];
  371. }
  372. - (void)updateStoredBatteryState {
  373. if (!self.recordingCurrentSession)
  374. return;
  375. UIDevice* device = [UIDevice currentDevice];
  376. // Translate value to an app defined enum as the system could change the
  377. // underlying values of UIDeviceBatteryState between OS versions.
  378. DeviceBatteryState batteryState =
  379. GetBatteryStateFromUIDeviceBatteryState(device.batteryState);
  380. NSInteger batteryStateValue =
  381. static_cast<std::underlying_type<DeviceBatteryState>::type>(batteryState);
  382. [[NSUserDefaults standardUserDefaults]
  383. setInteger:batteryStateValue
  384. forKey:kPreviousSessionInfoBatteryState];
  385. [self updateSessionEndTime];
  386. }
  387. - (void)updateStoredThermalState {
  388. if (!self.recordingCurrentSession)
  389. return;
  390. NSProcessInfo* processInfo = [NSProcessInfo processInfo];
  391. // Translate value to an app defined enum as the system could change the
  392. // underlying values of NSProcessInfoThermalState between OS versions.
  393. DeviceThermalState thermalState =
  394. GetThermalStateFromNSProcessInfoThermalState([processInfo thermalState]);
  395. NSInteger thermalStateValue =
  396. static_cast<std::underlying_type<DeviceThermalState>::type>(thermalState);
  397. [[NSUserDefaults standardUserDefaults]
  398. setInteger:thermalStateValue
  399. forKey:kPreviousSessionInfoThermalState];
  400. [self updateSessionEndTime];
  401. }
  402. - (void)applicationWillTerminate {
  403. [NSUserDefaults.standardUserDefaults
  404. setBool:YES
  405. forKey:kPreviousSessionInfoAppWillTerminate];
  406. [NSUserDefaults.standardUserDefaults synchronize];
  407. }
  408. - (void)updateMemoryFootprint {
  409. if (!self.recordingCurrentSession)
  410. return;
  411. task_vm_info taskInfoData;
  412. mach_msg_type_number_t count = sizeof(task_vm_info) / sizeof(natural_t);
  413. kern_return_t result =
  414. task_info(mach_task_self(), TASK_VM_INFO,
  415. reinterpret_cast<task_info_t>(&taskInfoData), &count);
  416. if (result == KERN_SUCCESS) {
  417. [NSUserDefaults.standardUserDefaults
  418. setInteger:taskInfoData.phys_footprint
  419. forKey:previous_session_info_constants::
  420. kPreviousSessionInfoMemoryFootprint];
  421. [self updateSessionEndTime];
  422. }
  423. }
  424. - (void)setMemoryWarningFlag {
  425. if (!self.didBeginRecordingCurrentSession)
  426. return;
  427. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  428. [defaults setBool:YES
  429. forKey:previous_session_info_constants::
  430. kDidSeeMemoryWarningShortlyBeforeTerminating];
  431. // Save critical state information for crash detection.
  432. [defaults synchronize];
  433. }
  434. - (void)resetMemoryWarningFlag {
  435. if (!self.didBeginRecordingCurrentSession)
  436. return;
  437. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  438. [defaults
  439. removeObjectForKey:previous_session_info_constants::
  440. kDidSeeMemoryWarningShortlyBeforeTerminating];
  441. // Save critical state information for crash detection.
  442. [defaults synchronize];
  443. }
  444. - (void)synchronizeSceneSessionIDs {
  445. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  446. [defaults setObject:[self.connectedSceneSessionsIDs allObjects]
  447. forKey:previous_session_info_constants::
  448. kPreviousSessionInfoConnectedSceneSessionIDs];
  449. [defaults synchronize];
  450. }
  451. - (void)addSceneSessionID:(NSString*)sessionID {
  452. [self.connectedSceneSessionsIDs addObject:sessionID];
  453. [self synchronizeSceneSessionIDs];
  454. }
  455. - (void)removeSceneSessionID:(NSString*)sessionID {
  456. [self.connectedSceneSessionsIDs removeObject:sessionID];
  457. [self synchronizeSceneSessionIDs];
  458. }
  459. - (void)resetConnectedSceneSessionIDs {
  460. self.connectedSceneSessionsIDs = [[NSMutableSet alloc] init];
  461. [self synchronizeSceneSessionIDs];
  462. }
  463. - (base::ScopedClosureRunner)startSessionRestoration {
  464. if (self.numberOfSessionsBeingRestored == 0) {
  465. [NSUserDefaults.standardUserDefaults
  466. setBool:YES
  467. forKey:previous_session_info_constants::
  468. kPreviousSessionInfoRestoringSession];
  469. // Save critical state information for crash detection.
  470. [NSUserDefaults.standardUserDefaults synchronize];
  471. }
  472. ++self.numberOfSessionsBeingRestored;
  473. return base::ScopedClosureRunner(base::BindOnce(^{
  474. --self.numberOfSessionsBeingRestored;
  475. if (self.numberOfSessionsBeingRestored == 0) {
  476. [self resetSessionRestorationFlag];
  477. }
  478. }));
  479. }
  480. - (void)resetSessionRestorationFlag {
  481. gSharedInstance.terminatedDuringSessionRestoration = NO;
  482. [NSUserDefaults.standardUserDefaults
  483. removeObjectForKey:previous_session_info_constants::
  484. kPreviousSessionInfoRestoringSession];
  485. // Save critical state information for crash detection.
  486. [NSUserDefaults.standardUserDefaults synchronize];
  487. }
  488. - (void)updateCurrentSessionTabCount:(NSInteger)count {
  489. [NSUserDefaults.standardUserDefaults
  490. setInteger:count
  491. forKey:previous_session_info_constants::kPreviousSessionInfoTabCount];
  492. [NSUserDefaults.standardUserDefaults synchronize];
  493. }
  494. - (void)updateCurrentSessionOTRTabCount:(NSInteger)count {
  495. [NSUserDefaults.standardUserDefaults
  496. setInteger:count
  497. forKey:previous_session_info_constants::
  498. kPreviousSessionInfoOTRTabCount];
  499. [NSUserDefaults.standardUserDefaults synchronize];
  500. }
  501. - (void)setReportParameterValue:(NSString*)value forKey:(NSString*)key {
  502. NSMutableDictionary* params = [[NSUserDefaults.standardUserDefaults
  503. dictionaryForKey:previous_session_info_constants::
  504. kPreviousSessionInfoParams] mutableCopy];
  505. if (!params) {
  506. params = [NSMutableDictionary dictionaryWithCapacity:1];
  507. }
  508. params[key] = value;
  509. [NSUserDefaults.standardUserDefaults
  510. setObject:params
  511. forKey:previous_session_info_constants::kPreviousSessionInfoParams];
  512. [NSUserDefaults.standardUserDefaults synchronize];
  513. }
  514. - (void)setReportParameterURL:(const GURL&)URL forKey:(NSString*)key {
  515. // Store only URL origin (not whole URL spec) as requested by Privacy Team.
  516. [self
  517. setReportParameterValue:base::SysUTF8ToNSString(
  518. URL.DeprecatedGetOriginAsURL().spec().c_str())
  519. forKey:key];
  520. }
  521. - (void)removeReportParameterForKey:(NSString*)key {
  522. NSMutableDictionary* URLs = [[NSUserDefaults.standardUserDefaults
  523. dictionaryForKey:previous_session_info_constants::
  524. kPreviousSessionInfoParams] mutableCopy];
  525. if (URLs) {
  526. URLs[key] = nil;
  527. if (URLs.count == 0) {
  528. URLs = nil;
  529. }
  530. [NSUserDefaults.standardUserDefaults
  531. setObject:URLs
  532. forKey:previous_session_info_constants::kPreviousSessionInfoParams];
  533. [NSUserDefaults.standardUserDefaults synchronize];
  534. }
  535. }
  536. @end