refactoring, remove Loaded property from database. instead, make GetDb() return null if database is not loaded.

This commit is contained in:
Philipp Crocoll
2018-10-01 11:12:37 +02:00
parent 4f36de9900
commit 977393a9aa
16 changed files with 57 additions and 115 deletions

View File

@@ -45,7 +45,7 @@ namespace keepass2android
{ {
get get
{ {
return KpDatabase == null ? null : KpDatabase.IOConnectionInfo; return KpDatabase?.IOConnectionInfo;
} }
} }
@@ -74,8 +74,6 @@ namespace keepass2android
CanWrite = true; //default CanWrite = true; //default
} }
private bool _loaded;
private bool _reloadRequested; private bool _reloadRequested;
private IDatabaseFormat _databaseFormat = new KdbxDatabaseFormat(KdbxFormat.Default); private IDatabaseFormat _databaseFormat = new KdbxDatabaseFormat(KdbxFormat.Default);
@@ -85,19 +83,9 @@ namespace keepass2android
set { _reloadRequested = value; } set { _reloadRequested = value; }
} }
public bool Loaded {
get { return _loaded;}
set { _loaded = value; }
}
public bool DidOpenFileChange() public bool DidOpenFileChange()
{ {
if (Loaded == false)
{
return false;
}
return _app.GetFileStorage(Ioc).CheckForFileChangeFast(Ioc, LastFileVersion); return _app.GetFileStorage(Ioc).CheckForFileChangeFast(Ioc, LastFileVersion);
} }
@@ -112,32 +100,20 @@ namespace keepass2android
Stream s = databaseData ?? fileStorage.OpenFileForRead(iocInfo); Stream s = databaseData ?? fileStorage.OpenFileForRead(iocInfo);
var fileVersion = _app.GetFileStorage(iocInfo).GetCurrentFileVersionFast(iocInfo); var fileVersion = _app.GetFileStorage(iocInfo).GetCurrentFileVersionFast(iocInfo);
PopulateDatabaseFromStream(pwDatabase, s, iocInfo, compositeKey, status, databaseFormat); PopulateDatabaseFromStream(pwDatabase, s, iocInfo, compositeKey, status, databaseFormat);
try LastFileVersion = fileVersion;
{
LastFileVersion = fileVersion;
status.UpdateSubMessage(""); status.UpdateSubMessage("");
Root = pwDatabase.RootGroup; Root = pwDatabase.RootGroup;
PopulateGlobals(Root); PopulateGlobals(Root);
KpDatabase = pwDatabase; KpDatabase = pwDatabase;
SearchHelper = new SearchDbHelper(app); SearchHelper = new SearchDbHelper(app);
_databaseFormat = databaseFormat;
CanWrite = databaseFormat.CanWrite && !fileStorage.IsReadOnly(iocInfo);
Loaded = true;
}
catch (Exception)
{
Clear();
throw;
}
_databaseFormat = databaseFormat;
CanWrite = databaseFormat.CanWrite && !fileStorage.IsReadOnly(iocInfo);
} }
/// <summary> /// <summary>
@@ -267,24 +243,7 @@ namespace keepass2android
PopulateGlobals(currentGroup, _app.CheckForDuplicateUuids); PopulateGlobals(currentGroup, _app.CheckForDuplicateUuids);
} }
public void Clear() { public void MarkAllGroupsAsDirty() {
_loaded = false;
Groups.Clear();
Entries.Clear();
Dirty.Clear();
DrawableFactory.Clear();
Root = null;
KpDatabase = null;
CanWrite = true;
_reloadRequested = false;
OtpAuxFileIoc = null;
LastOpenedEntry = null;
}
public void MarkAllGroupsAsDirty() {
foreach ( PwGroup group in Groups.Values ) { foreach ( PwGroup group in Groups.Values ) {
Dirty.Add(group); Dirty.Add(group);
} }

View File

@@ -74,7 +74,6 @@ namespace keepass2android
// Set Database state // Set Database state
db.Root = db.KpDatabase.RootGroup; db.Root = db.KpDatabase.RootGroup;
db.Loaded = true;
db.SearchHelper = new SearchDbHelper(_app); db.SearchHelper = new SearchDbHelper(_app);
// Add a couple default groups // Add a couple default groups

View File

@@ -391,7 +391,7 @@ namespace keepass2android
Database db = App.Kp2a.GetDb(); Database db = App.Kp2a.GetDb();
// Likely the app has been killed exit the activity // Likely the app has been killed exit the activity
if (!db.Loaded || (App.Kp2a.QuickLocked)) if (db == null || (App.Kp2a.QuickLocked))
{ {
Finish(); Finish();
return; return;

View File

@@ -407,7 +407,7 @@ namespace keepass2android
AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent); AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);
// Likely the app has been killed exit the activity // Likely the app has been killed exit the activity
if (!App.Kp2a.GetDb().Loaded) if (App.Kp2a.GetDb() == null)
{ {
Finish(); Finish();
return; return;

View File

@@ -43,35 +43,30 @@ namespace keepass2android
{ {
base.OnStart(); base.OnStart();
if (App.Kp2a.GetDb().Loaded) var xcKey = App.Kp2a.GetDb()?.KpDatabase.MasterKey.GetUserKey<ChallengeXCKey>();
if (xcKey != null)
{ {
var xcKey = App.Kp2a.GetDb().KpDatabase.MasterKey.GetUserKey<ChallengeXCKey>(); xcKey.Activity = this;
if (xcKey != null) _currentlyWaitingKey = xcKey;
{
xcKey.Activity = this;
_currentlyWaitingKey = xcKey;
}
} }
}
}
protected override void OnStop() protected override void OnStop()
{ {
base.OnStop(); base.OnStop();
if (App.Kp2a.GetDb().Loaded) var xcKey = App.Kp2a.GetDb()?.KpDatabase.MasterKey.GetUserKey<ChallengeXCKey>();
if (xcKey != null)
{ {
var xcKey = App.Kp2a.GetDb().KpDatabase.MasterKey.GetUserKey<ChallengeXCKey>(); //don't store a pointer to this activity in the static database object to avoid memory leak
if (xcKey != null) if (xcKey.Activity == this) //don't reset if another activity has come to foreground already
{ xcKey.Activity = null;
//don't store a pointer to this activity in the static database object to avoid memory leak
if (xcKey.Activity == this) //don't reset if another activity has come to foreground already
xcKey.Activity = null;
}
} }
}
}
protected override void OnPause() { protected override void OnPause() {
base.OnPause(); base.OnPause();

View File

@@ -93,7 +93,7 @@ namespace keepass2android
return; return;
} }
if (App.Kp2a.GetDb().Loaded) if (App.Kp2a.GetDb() != null)
{ {
Toast.MakeText(this, GetString(Resource.String.otp_discarded_because_db_open), ToastLength.Long).Show(); Toast.MakeText(this, GetString(Resource.String.otp_discarded_because_db_open), ToastLength.Long).Show();
} }

View File

@@ -737,8 +737,7 @@ namespace keepass2android
} }
} }
if (App.Kp2a.GetDb().Loaded && App.Kp2a.GetDb().Ioc != null && if (App.Kp2a.GetDb()?.Ioc != null && App.Kp2a.GetDb().Ioc.GetDisplayName() != _ioConnection.GetDisplayName())
App.Kp2a.GetDb().Ioc.GetDisplayName() != _ioConnection.GetDisplayName())
{ {
// A different database is currently loaded, unload it before loading the new one requested // A different database is currently loaded, unload it before loading the new one requested
App.Kp2a.LockDatabase(false); App.Kp2a.LockDatabase(false);

View File

@@ -427,7 +427,7 @@ namespace keepass2android
private void CheckIfUnloaded() private void CheckIfUnloaded()
{ {
if ((App.Kp2a.GetDb() == null) || (App.Kp2a.GetDb().Loaded == false)) if (App.Kp2a.GetDb() == null)
{ {
Finish(); Finish();
} }

View File

@@ -46,7 +46,7 @@ namespace keepass2android
base.OnResume(); base.OnResume();
if (!IsFinishing) if (!IsFinishing)
{ {
if (!App.Kp2a.GetDb().Loaded) if (App.Kp2a.GetDb() == null)
{ {
// Load default database // Load default database
ISharedPreferences prefs = Android.Preferences.PreferenceManager.GetDefaultSharedPreferences(this); ISharedPreferences prefs = Android.Preferences.PreferenceManager.GetDefaultSharedPreferences(this);
@@ -128,7 +128,7 @@ namespace keepass2android
break; break;
case KeePass.ExitReloadDb: case KeePass.ExitReloadDb:
if (App.Kp2a.GetDb().Loaded) if (App.Kp2a.GetDb() != null)
{ {
//remember the composite key for reloading: //remember the composite key for reloading:
var compositeKey = App.Kp2a.GetDb().KpDatabase.MasterKey; var compositeKey = App.Kp2a.GetDb().KpDatabase.MasterKey;

View File

@@ -102,19 +102,18 @@ namespace keepass2android
{ {
public void LockDatabase(bool allowQuickUnlock = true) public void LockDatabase(bool allowQuickUnlock = true)
{ {
if (GetDb().Loaded) if (GetDb() != null)
{ {
if (QuickUnlockEnabled && allowQuickUnlock && if (QuickUnlockEnabled && allowQuickUnlock &&
_db.KpDatabase.MasterKey.ContainsType(typeof(KcpPassword)) && GetDb().KpDatabase.MasterKey.ContainsType(typeof(KcpPassword)) &&
!((KcpPassword)App.Kp2a.GetDb().KpDatabase.MasterKey.GetUserKey(typeof(KcpPassword))).Password.IsEmpty) !((KcpPassword)App.Kp2a.GetDb().KpDatabase.MasterKey.GetUserKey(typeof(KcpPassword))).Password.IsEmpty)
{ {
if (!QuickLocked) if (!QuickLocked)
{ {
Kp2aLog.Log("QuickLocking database"); Kp2aLog.Log("QuickLocking database");
BroadcastDatabaseAction(Application.Context, Strings.ActionLockDatabase); QuickLocked = true;
GetDb().LastOpenedEntry = null;
QuickLocked = true; BroadcastDatabaseAction(Application.Context, Strings.ActionLockDatabase);
_db.LastOpenedEntry = null;
} }
else else
{ {
@@ -127,8 +126,8 @@ namespace keepass2android
BroadcastDatabaseAction(Application.Context, Strings.ActionCloseDatabase); BroadcastDatabaseAction(Application.Context, Strings.ActionCloseDatabase);
// Couldn't quick-lock, so unload database instead // Couldn't quick-lock, so unload database instead
_db.Clear(); _db = null;
QuickLocked = false; QuickLocked = false;
} }
} }
@@ -181,7 +180,7 @@ namespace keepass2android
memoryStream.Seek(0, SeekOrigin.Begin); memoryStream.Seek(0, SeekOrigin.Begin);
} }
_db = CreateNewDatabase();
_db.LoadData(this, ioConnectionInfo, memoryStream, compositeKey, statusLogger, databaseFormat); _db.LoadData(this, ioConnectionInfo, memoryStream, compositeKey, statusLogger, databaseFormat);
if (createBackup) if (createBackup)
@@ -259,7 +258,7 @@ namespace keepass2android
public bool DatabaseIsUnlocked public bool DatabaseIsUnlocked
{ {
get { return _db.Loaded && !QuickLocked; } get { return GetDb() != null && !QuickLocked; }
} }
#region QuickUnlock #region QuickUnlock
@@ -300,11 +299,6 @@ namespace keepass2android
public Database GetDb() public Database GetDb()
{ {
if (_db == null)
{
_db = CreateNewDatabase();
}
return _db; return _db;
} }
@@ -331,9 +325,9 @@ namespace keepass2android
public void CheckForOpenFileChanged(Activity activity) public void CheckForOpenFileChanged(Activity activity)
{ {
if (_db.DidOpenFileChange()) if (GetDb()?.DidOpenFileChange() == true)
{ {
if (_db.ReloadRequested) if (GetDb().ReloadRequested)
{ {
LockDatabase(false); LockDatabase(false);
activity.SetResult(KeePass.ExitReloadDb); activity.SetResult(KeePass.ExitReloadDb);
@@ -353,7 +347,7 @@ namespace keepass2android
builder.SetPositiveButton(activity.GetString(Android.Resource.String.Yes), builder.SetPositiveButton(activity.GetString(Android.Resource.String.Yes),
(dlgSender, dlgEvt) => (dlgSender, dlgEvt) =>
{ {
_db.ReloadRequested = true; GetDb().ReloadRequested = true;
activity.SetResult(KeePass.ExitReloadDb); activity.SetResult(KeePass.ExitReloadDb);
activity.Finish(); activity.Finish();
@@ -729,15 +723,14 @@ namespace keepass2android
internal void OnTerminate() internal void OnTerminate()
{ {
if (_db != null)
{ _db = null;
_db.Clear();
}
if (FileDbHelper != null && FileDbHelper.IsOpen()) if (FileDbHelper != null && FileDbHelper.IsOpen())
{ {
FileDbHelper.Close(); FileDbHelper.Close();
} }
GC.Collect();
} }
internal void OnCreate(Application app) internal void OnCreate(Application app)

View File

@@ -943,7 +943,7 @@ namespace keepass2android
PwUuid nextGroupPwUuid = new PwUuid (MemUtil.HexStringToByteArray (nextGroupUuid)); PwUuid nextGroupPwUuid = new PwUuid (MemUtil.HexStringToByteArray (nextGroupUuid));
// Create Group Activity // Create Group Activity
PwGroup nextGroup = App.Kp2a.GetDb ().Groups [nextGroupPwUuid]; PwGroup nextGroup = App.Kp2a.GetDb ().Groups[nextGroupPwUuid];
GroupActivity.Launch (groupBaseActivity, nextGroup, this); GroupActivity.Launch (groupBaseActivity, nextGroup, this);
} }
return; return;

View File

@@ -461,7 +461,7 @@ namespace keepass2android
Kp2aLog.Log("FileSelect.OnStart"); Kp2aLog.Log("FileSelect.OnStart");
var db = App.Kp2a.GetDb(); var db = App.Kp2a.GetDb();
if (db.Loaded) if (db != null)
{ {
LaunchPasswordActivityForIoc(db.Ioc); LaunchPasswordActivityForIoc(db.Ioc);
} }

View File

@@ -48,8 +48,6 @@ namespace keepass2android.search
private const string IconIdParameter = "IconId"; private const string IconIdParameter = "IconId";
private const string CustomIconUuidParameter = "CustomIconUuid"; private const string CustomIconUuidParameter = "CustomIconUuid";
private Database _db;
private static UriMatcher UriMatcher = BuildUriMatcher(); private static UriMatcher UriMatcher = BuildUriMatcher();
static UriMatcher BuildUriMatcher() static UriMatcher BuildUriMatcher()
@@ -65,7 +63,6 @@ namespace keepass2android.search
public override bool OnCreate() public override bool OnCreate()
{ {
_db = App.Kp2a.GetDb();
return true; return true;
} }
@@ -82,7 +79,7 @@ namespace keepass2android.search
try try
{ {
var resultsContexts = new Dictionary<PwUuid, KeyValuePair<string, string>>(); var resultsContexts = new Dictionary<PwUuid, KeyValuePair<string, string>>();
var result = _db.Search(new SearchParameters { SearchString = searchString }, resultsContexts ); var result = App.Kp2a.GetDb().Search(new SearchParameters { SearchString = searchString }, resultsContexts );
return new GroupCursor(result, resultsContexts); return new GroupCursor(result, resultsContexts);
} }
catch (Exception e) catch (Exception e)
@@ -120,8 +117,8 @@ namespace keepass2android.search
var iconId = (PwIcon)Enum.Parse(typeof(PwIcon), uri.GetQueryParameter(IconIdParameter)); var iconId = (PwIcon)Enum.Parse(typeof(PwIcon), uri.GetQueryParameter(IconIdParameter));
var customIconUuid = new PwUuid(MemUtil.HexStringToByteArray(uri.GetQueryParameter(CustomIconUuidParameter))); var customIconUuid = new PwUuid(MemUtil.HexStringToByteArray(uri.GetQueryParameter(CustomIconUuidParameter)));
var iconDrawable = _db.DrawableFactory.GetIconDrawable(App.Context, _db.KpDatabase, iconId, customIconUuid, false) as BitmapDrawable; var iconDrawable = App.Kp2a.GetDb().DrawableFactory.GetIconDrawable(App.Context, App.Kp2a.GetDb().KpDatabase, iconId, customIconUuid, false) as BitmapDrawable;
if ((iconDrawable != null) && (iconDrawable.Bitmap != null)) if (iconDrawable?.Bitmap != null)
{ {
var pipe = ParcelFileDescriptor.CreatePipe(); var pipe = ParcelFileDescriptor.CreatePipe();

View File

@@ -39,7 +39,7 @@ namespace keepass2android.services.Kp2aAutofill
protected override FilledAutofillFieldCollection GetDataset(Intent data) protected override FilledAutofillFieldCollection GetDataset(Intent data)
{ {
if (!App.Kp2a.GetDb().Loaded || (App.Kp2a.QuickLocked)) if (App.Kp2a.GetDb()==null || (App.Kp2a.QuickLocked))
return null; return null;
var entryOutput = App.Kp2a.GetDb().LastOpenedEntry; var entryOutput = App.Kp2a.GetDb().LastOpenedEntry;

View File

@@ -424,7 +424,7 @@ namespace keepass2android
FindPreference(GetString(Resource.String.design_key)).PreferenceChange += (sender, args) => Activity.Recreate(); FindPreference(GetString(Resource.String.design_key)).PreferenceChange += (sender, args) => Activity.Recreate();
Database db = App.Kp2a.GetDb(); Database db = App.Kp2a.GetDb();
if (db.Loaded) if (db != null)
{ {
ListPreference kdfPref = (ListPreference) FindPreference(GetString(Resource.String.kdf_key)); ListPreference kdfPref = (ListPreference) FindPreference(GetString(Resource.String.kdf_key));
kdfPref.SetEntries(KdfPool.Engines.Select(eng => eng.Name).ToArray()); kdfPref.SetEntries(KdfPool.Engines.Select(eng => eng.Name).ToArray());
@@ -791,7 +791,7 @@ namespace keepass2android
private void OnUseOfflineCacheChanged(object sender, Preference.PreferenceChangeEventArgs e) private void OnUseOfflineCacheChanged(object sender, Preference.PreferenceChangeEventArgs e)
{ {
//ensure the user gets a matching database //ensure the user gets a matching database
if (App.Kp2a.GetDb().Loaded && !App.Kp2a.GetDb().Ioc.IsLocalFile()) if (App.Kp2a.GetDb() != null && !App.Kp2a.GetDb().Ioc.IsLocalFile())
App.Kp2a.LockDatabase(false); App.Kp2a.LockDatabase(false);
if (!(bool)e.NewValue) if (!(bool)e.NewValue)

View File

@@ -83,7 +83,7 @@ namespace keepass2android
public static void Resume(Activity act) public static void Resume(Activity act)
{ {
if ( App.Kp2a.GetDb().Loaded ) if ( App.Kp2a.GetDb() != null)
{ {
Timeout.Cancel(act); Timeout.Cancel(act);
} }