1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.wm.shell.bubbles.storage 17 18 import android.content.Context 19 import android.util.AtomicFile 20 import android.util.Log 21 import android.util.SparseArray 22 import java.io.File 23 import java.io.FileOutputStream 24 import java.io.IOException 25 26 class BubblePersistentRepository(context: Context) { 27 28 private val bubbleFile: AtomicFile = AtomicFile(File(context.filesDir, 29 "overflow_bubbles.xml"), "overflow-bubbles") 30 persistsToDisknull31 fun persistsToDisk(bubbles: SparseArray<List<BubbleEntity>>): Boolean { 32 if (DEBUG) Log.d(TAG, "persisting ${bubbles.size()} bubbles") 33 synchronized(bubbleFile) { 34 val stream: FileOutputStream = try { bubbleFile.startWrite() } catch (e: IOException) { 35 Log.e(TAG, "Failed to save bubble file", e) 36 return false 37 } 38 try { 39 writeXml(stream, bubbles) 40 bubbleFile.finishWrite(stream) 41 if (DEBUG) Log.d(TAG, "persisted ${bubbles.size()} bubbles") 42 return true 43 } catch (e: Exception) { 44 Log.e(TAG, "Failed to save bubble file, restoring backup", e) 45 bubbleFile.failWrite(stream) 46 } 47 } 48 return false 49 } 50 readFromDisknull51 fun readFromDisk(): SparseArray<List<BubbleEntity>> { 52 synchronized(bubbleFile) { 53 if (!bubbleFile.exists()) return SparseArray() 54 try { return bubbleFile.openRead().use(::readXml) } catch (e: Throwable) { 55 Log.e(TAG, "Failed to open bubble file", e) 56 } 57 return SparseArray() 58 } 59 } 60 } 61 62 private const val TAG = "BubblePersistentRepository" 63 private const val DEBUG = false 64