コード例 #1
1
ファイル: EntryEditActivity.cs プロジェクト: pythe/wristpass
        public static void Launch(Activity act, PwEntry pw, AppTask appTask)
        {
            Intent i = new Intent(act, typeof(EntryEditActivity));

            i.PutExtra(KeyEntry, pw.Uuid.ToHexString());

            appTask.ToIntent(i);

            act.StartActivityForResult(i, 0);
        }
コード例 #2
0
ファイル: AppTask.cs プロジェクト: pythe/wristpass
        public static AppTask CreateFromBundle(Bundle b, AppTask failureReturn)
        {
            if (b == null)
                return failureReturn;

            string taskType = b.GetString(AppTaskKey);

            if (string.IsNullOrEmpty(taskType))
                return failureReturn;

            try
            {
                Type type = Type.GetType("keepass2android." + taskType);
                if (type == null)
                    return failureReturn;
                AppTask task = (AppTask)Activator.CreateInstance(type);
                task.Setup(b);
                return task;
            }
            catch (Exception e)
            {
                Kp2aLog.Log("Cannot convert " + taskType + " in task: " + e);
                return failureReturn;
            }
        }
コード例 #3
0
ファイル: SearchActivity.cs プロジェクト: pythe/wristpass
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            _appTask = AppTask.GetTaskInOnCreate(bundle, Intent);
            SetContentView(Resource.Layout.search);
            SearchParameters sp = new SearchParameters();
            PopulateCheckBox(Resource.Id.cbSearchInTitle, sp.SearchInTitles);
            PopulateCheckBox(Resource.Id.cbSearchInUsername, sp.SearchInUserNames);
            PopulateCheckBox(Resource.Id.cbSearchInNotes, sp.SearchInNotes);
            PopulateCheckBox(Resource.Id.cbSearchInPassword, sp.SearchInPasswords);
            PopulateCheckBox(Resource.Id.cbSearchInTags, sp.SearchInTags);
            PopulateCheckBox(Resource.Id.cbSearchInGroupName, sp.SearchInGroupNames);
            PopulateCheckBox(Resource.Id.cbSearchInUrl, sp.SearchInUrls);
            PopulateCheckBox(Resource.Id.cbSearchInOtherStrings, sp.SearchInOther);
            PopulateCheckBox(Resource.Id.cbRegEx, sp.RegularExpression);

            StringComparison sc = sp.ComparisonMode;
            bool caseSensitive = ((sc != StringComparison.CurrentCultureIgnoreCase) &&
                                         (sc != StringComparison.InvariantCultureIgnoreCase) &&
                                         (sc != StringComparison.OrdinalIgnoreCase));
            PopulateCheckBox(Resource.Id.cbCaseSensitive, caseSensitive);
            PopulateCheckBox(Resource.Id.cbExcludeExpiredEntries, sp.ExcludeExpired);

            ImageButton btnSearch = (ImageButton)FindViewById(Resource.Id.search_button);

            btnSearch.Click += (sender, e) => PerformSearch();

            FindViewById<EditText>(Resource.Id.searchEditText).EditorAction += (sender, e) =>
            {
                if (e.ActionId == Android.Views.InputMethods.ImeAction.Search) {
                    PerformSearch();
                }
            };
        }
コード例 #4
0
        protected override void OnResume()
        {
            base.OnResume();
            if (!IsFinishing && !LaunchingOther)
            {
                if (App.Kp2a.OpenDatabases.Any() == false)
                {
                    StartFileSelect(true);
                    return;
                }

                //database loaded
                if (App.Kp2a.QuickLocked)
                {
                    var i = new Intent(this, typeof(QuickUnlock));
                    Util.PutIoConnectionToIntent(App.Kp2a.GetDbForQuickUnlock().Ioc, i);
                    Kp2aLog.Log("Starting QuickUnlock");
                    StartActivityForResult(i, 0);
                    return;
                }

                //see if there are any AutoOpen items to open

                foreach (var db in App.Kp2a.OpenDatabases)
                {
                    try
                    {
                        if (OpenAutoExecEntries(db))
                        {
                            return;
                        }
                    }
                    catch (Exception e)
                    {
                        Toast.MakeText(this, "Failed to open child databases", ToastLength.Long).Show();
                        Kp2aLog.LogUnexpectedError(e);
                    }
                }

                //database(s) unlocked
                if ((App.Kp2a.OpenDatabases.Count() == 1) || (AppTask is SearchUrlTask))
                {
                    LaunchingOther = true;
                    AppTask.LaunchFirstGroupActivity(this);
                    return;
                }

                //more than one database open or user requested to load another db. Don't launch another activity.
                _adapter.Update();
                _adapter.NotifyDataSetChanged();
            }
            base.OnResume();
        }
コード例 #5
0
        public static void Launch(Activity act, PwGroup g, AppTask appTask, ActivityLaunchMode launchMode)
        {
            Intent i = new Intent(act, typeof(GroupActivity));

            if (g != null)
            {
                i.PutExtra(KeyEntry, g.Uuid.ToHexString());
            }
            appTask.ToIntent(i);

            launchMode.Launch(act, i);
        }
コード例 #6
0
        public static void Launch(Activity act, PwGroup pw, PwUuid templateUuid, AppTask appTask)
        {
            Intent i = new Intent(act, typeof(EntryEditActivity));

            PwGroup parent = pw;

            i.PutExtra(KeyParent, parent.Uuid.ToHexString());
            i.PutExtra(KeyTemplateUuid, templateUuid.ToHexString());

            appTask.ToIntent(i);

            act.StartActivityForResult(i, 0);
        }
コード例 #7
0
 public override void OnBackPressed()
 {
     base.OnBackPressed();
     if (PreferenceManager.GetDefaultSharedPreferences(this)
         .GetBoolean(GetString(Resource.String.LockWhenNavigateBack_key), false))
     {
         App.Kp2a.Lock();
     }
     //by leaving the app with the back button, the user probably wants to cancel the task
     //The activity might be resumed (through Android's recent tasks list), then use a NullTask:
     AppTask = new NullTask();
     Finish();
 }
コード例 #8
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            _design.ApplyTheme();
            base.OnCreate(savedInstanceState);

            Android.Util.Log.Debug("KP2A", "Creating GBA");

            AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            // Likely the app has been killed exit the activity
            if (!App.Kp2a.GetDb().Loaded)
            {
                Finish();
                return;
            }

            _prefs = PreferenceManager.GetDefaultSharedPreferences(this);


            SetContentView(ContentResourceId);

            if (FindViewById(Resource.Id.fabCancelAddNew) != null)
            {
                FindViewById(Resource.Id.fabAddNew).Click += (sender, args) =>
                {
                    FindViewById(Resource.Id.fabCancelAddNew).Visibility = ViewStates.Visible;
                    FindViewById(Resource.Id.fabAddNewGroup).Visibility  = AddGroupEnabled ? ViewStates.Visible : ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewEntry).Visibility  = AddEntryEnabled ? ViewStates.Visible : ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNew).Visibility       = ViewStates.Gone;
                };

                FindViewById(Resource.Id.fabCancelAddNew).Click += (sender, args) =>
                {
                    FindViewById(Resource.Id.fabCancelAddNew).Visibility = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewGroup).Visibility  = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewEntry).Visibility  = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNew).Visibility       = ViewStates.Visible;
                };
            }


            if (FindViewById(Resource.Id.cancel_insert_element) != null)
            {
                FindViewById(Resource.Id.cancel_insert_element).Click += (sender, args) => StopMovingElements();
                FindViewById(Resource.Id.insert_element).Click        += (sender, args) => InsertElements();
                Util.MoveBottomBarButtons(Resource.Id.cancel_insert_element, Resource.Id.insert_element, Resource.Id.bottom_bar, this);
            }


            SetResult(KeePass.ExitNormal);
        }
コード例 #9
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (AppTask.TryGetFromActivityResult(data, ref AppTask))
            {
                //make sure the app task is passed to the calling activity
                AppTask.SetActivityResult(this, KeePass.ExitNormal);
            }

            if ((GroupEditActivity.RequestCodeGroupEdit == requestCode) && (resultCode == Result.Ok))
            {
                String groupName         = data.Extras.GetString(GroupEditActivity.KeyName);
                int    groupIconId       = data.Extras.GetInt(GroupEditActivity.KeyIconId);
                PwUuid groupCustomIconId =
                    new PwUuid(MemUtil.HexStringToByteArray(data.Extras.GetString(GroupEditActivity.KeyCustomIconId)));
                String            strGroupUuid = data.Extras.GetString(GroupEditActivity.KeyGroupUuid);
                GroupBaseActivity act          = this;
                Handler           handler      = new Handler();
                RunnableOnFinish  task;
                if (strGroupUuid == null)
                {
                    task = AddGroup.GetInstance(this, App.Kp2a, groupName, groupIconId, groupCustomIconId, Group, new RefreshTask(handler, this), false);
                }
                else
                {
                    PwUuid groupUuid = new PwUuid(MemUtil.HexStringToByteArray(strGroupUuid));
                    task = new EditGroup(this, App.Kp2a, groupName, (PwIcon)groupIconId, groupCustomIconId, App.Kp2a.GetDb().Groups[groupUuid],
                                         new RefreshTask(handler, this));
                }
                ProgressTask pt = new ProgressTask(App.Kp2a, act, task);
                pt.Run();
            }

            if (resultCode == KeePass.ExitCloseAfterTaskComplete)
            {
                AppTask.SetActivityResult(this, KeePass.ExitCloseAfterTaskComplete);
                Finish();
            }

            if (resultCode == KeePass.ExitReloadDb)
            {
                AppTask.SetActivityResult(this, KeePass.ExitReloadDb);
                Finish();
            }
        }
コード例 #10
0
        /// <summary>
        /// Tries to extract the task from the data given as an Intent object in OnActivityResult. If successful, the task is assigned,
        /// otherwise, false is returned.
        /// </summary>
        public static bool TryGetFromActivityResult(Intent data, ref AppTask task)
        {
            if (data == null)
            {
                Kp2aLog.Log("TryGetFromActivityResult: no data");
                return(false);
            }
            AppTask tempTask = CreateFromBundle(data.Extras, null);

            if (tempTask == null)
            {
                Kp2aLog.Log("No AppTask in OnActivityResult");
                return(false);
            }

            task = tempTask;
            Kp2aLog.Log("AppTask " + task + " in OnActivityResult");
            return(true);
        }
コード例 #11
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            _design.ApplyTheme();
            base.OnCreate(savedInstanceState);

            //see comment to this in PasswordActivity.
            //Note that this activity is affected even though it's finished when the app is closed because it
            //seems that the "app launch intent" is re-delivered, so this might end up here.
            if ((_appTask == null) && (Intent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory)))
            {
                _appTask = new NullTask();
            }
            else
            {
                _appTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);
            }


            Kp2aLog.Log("KeePass.OnCreate");
        }
コード例 #12
0
ファイル: GroupActivity.cs プロジェクト: pythe/wristpass
        public static void Launch(Activity act, PwGroup g, AppTask appTask)
        {
            // Need to use PwDatabase since group may be null
            PwDatabase db = App.Kp2a.GetDb().KpDatabase;

            if (db == null) {
                // Reached if db is null
                Log.Debug (Tag, "Tried to launch with null db");
                return;
            }

            Intent i = new Intent(act, typeof(GroupActivity));

            if ( g != null ) {
                i.PutExtra(KeyEntry, g.Uuid.ToHexString());
            }
            appTask.ToIntent(i);

            act.StartActivityForResult(i,0);
        }
コード例 #13
0
        public static void Launch(Activity act, PwGroup g, AppTask appTask)
        {
            // Need to use PwDatabase since group may be null
            PwDatabase db = App.Kp2a.GetDb().KpDatabase;

            if (db == null)
            {
                // Reached if db is null
                Log.Debug(Tag, "Tried to launch with null db");
                return;
            }

            Intent i = new Intent(act, typeof(GroupActivity));

            if (g != null)
            {
                i.PutExtra(KeyEntry, g.Uuid.ToHexString());
            }
            appTask.ToIntent(i);

            act.StartActivityForResult(i, 0);
        }
コード例 #14
0
ファイル: EntryActivity.cs プロジェクト: ypid/keepass2android
        public static void Launch(Activity act, PwEntry pw, int pos, AppTask appTask, ActivityFlags?flags = null)
        {
            Intent i = new Intent(act, typeof(EntryActivity));

            i.PutExtra(KeyEntry, pw.Uuid.ToHexString());
            i.PutExtra(KeyRefreshPos, pos);

            if (flags != null)
            {
                i.SetFlags((ActivityFlags)flags);
            }

            appTask.ToIntent(i);
            if (flags != null && (((ActivityFlags)flags) | ActivityFlags.ForwardResult) == ActivityFlags.ForwardResult)
            {
                act.StartActivity(i);
            }
            else
            {
                act.StartActivityForResult(i, 0);
            }
        }
コード例 #15
0
ファイル: EntryActivity.cs プロジェクト: ypid/keepass2android
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            if (AppTask.TryGetFromActivityResult(data, ref _appTask))
            {
                //make sure app task is passed to calling activity.
                //the result code might be modified later.
                Intent retData = new Intent();
                _appTask.ToIntent(retData);
                SetResult(KeePass.ExitNormal, retData);
            }



            if (resultCode == KeePass.ExitRefresh || resultCode == KeePass.ExitRefreshTitle)
            {
                if (resultCode == KeePass.ExitRefreshTitle)
                {
                    RequiresRefresh();
                }
                Recreate();
            }
        }
コード例 #16
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            AppTask = AppTask.GetTaskInOnCreate(bundle, Intent);
            SetContentView(Resource.Layout.search);
            SearchParameters sp = new SearchParameters();

            PopulateCheckBox(Resource.Id.cbSearchInTitle, sp.SearchInTitles);
            PopulateCheckBox(Resource.Id.cbSearchInUsername, sp.SearchInUserNames);
            PopulateCheckBox(Resource.Id.cbSearchInNotes, sp.SearchInNotes);
            PopulateCheckBox(Resource.Id.cbSearchInPassword, sp.SearchInPasswords);
            PopulateCheckBox(Resource.Id.cbSearchInTags, sp.SearchInTags);
            PopulateCheckBox(Resource.Id.cbSearchInGroupName, sp.SearchInGroupNames);
            PopulateCheckBox(Resource.Id.cbSearchInUrl, sp.SearchInUrls);
            PopulateCheckBox(Resource.Id.cbSearchInOtherStrings, sp.SearchInOther);
            PopulateCheckBox(Resource.Id.cbRegEx, sp.RegularExpression);

            StringComparison sc            = sp.ComparisonMode;
            bool             caseSensitive = ((sc != StringComparison.CurrentCultureIgnoreCase) &&
                                              (sc != StringComparison.InvariantCultureIgnoreCase) &&
                                              (sc != StringComparison.OrdinalIgnoreCase));

            PopulateCheckBox(Resource.Id.cbCaseSensitive, caseSensitive);
            PopulateCheckBox(Resource.Id.cbExcludeExpiredEntries, sp.ExcludeExpired);

            ImageButton btnSearch = (ImageButton)FindViewById(Resource.Id.search_button);

            btnSearch.Click += (sender, e) => PerformSearch();

            FindViewById <EditText>(Resource.Id.searchEditText).EditorAction += (sender, e) =>
            {
                if (e.ActionId == Android.Views.InputMethods.ImeAction.Search)
                {
                    PerformSearch();
                }
            };
        }
コード例 #17
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            Kp2aLog.Log($"{MyDebugName}: OnActivityResult " + resultCode + "/" + requestCode);

            AppTask appTask = null;

            if (AppTask.TryGetFromActivityResult(data, ref appTask))
            {
                this.AppTask = appTask;
            }

            if (requestCode == ReqCodeOpenNewDb)
            {
                switch ((int)resultCode)
                {
                case (int)Result.Ok:

                    string           iocString = data?.GetStringExtra("ioc");
                    IOConnectionInfo ioc       = IOConnectionInfo.UnserializeFromString(iocString);
                    if (App.Kp2a.TrySelectCurrentDb(ioc))
                    {
                        if (OpenAutoExecEntries(App.Kp2a.CurrentDb))
                        {
                            return;
                        }
                        LaunchingOther = true;
                        AppTask.CanActivateSearchViewOnStart = true;
                        AppTask.LaunchFirstGroupActivity(this);
                    }


                    break;

                case PasswordActivity.ResultSelectOtherFile:
                    StartFileSelect(true, true);
                    break;

                case (int)Result.Canceled:
                    if (App.Kp2a.OpenDatabases.Any() == false)
                    {
                        //don't open fileselect/password activity again
                        OnBackPressed();
                    }
                    break;

                default:
                    break;
                }

                return;
            }

            switch (resultCode)
            {
            case KeePass.ExitNormal:     // Returned to this screen using the Back key
                if (App.Kp2a.OpenDatabases.Count() == 1)
                {
                    OnBackPressed();
                }
                break;

            case KeePass.ExitLock:
                // The database has already been locked. No need to immediately return to quick unlock. Especially as this causes trouble for users with face unlock
                // (db immediately unlocked again) and confused some users as the biometric prompt seemed to disable the device back button or at least they didn't understand
                // why they should unlock...
                SetResult(KeePass.ExitClose);
                if (!IsFinishing)
                {
                    Finish();
                }
                break;

            case KeePass.ExitLockByTimeout:
                //don't finish, bring up QuickUnlock
                break;

            case KeePass.ExitCloseAfterTaskComplete:
                // Do not lock the database
                SetResult(KeePass.ExitCloseAfterTaskComplete);
                if (!IsFinishing)
                {
                    Finish();
                }
                break;

            case KeePass.ExitClose:
                SetResult(KeePass.ExitClose);
                if (!IsFinishing)
                {
                    Finish();
                }
                break;

            case KeePass.ExitReloadDb:

                if (App.Kp2a.CurrentDb != null)
                {
                    //remember the composite key for reloading:
                    var compositeKey = App.Kp2a.CurrentDb.KpDatabase.MasterKey;
                    var ioc          = App.Kp2a.CurrentDb.Ioc;

                    //lock the database:
                    App.Kp2a.CloseDatabase(App.Kp2a.CurrentDb);

                    LaunchPasswordActivityForReload(ioc, compositeKey);
                }

                break;

            case KeePass.ExitLoadAnotherDb:
                StartFileSelect(true, true);
                break;
            }
        }
コード例 #18
0
ファイル: EntryEditActivity.cs プロジェクト: pythe/wristpass
        public static void Launch(Activity act, PwGroup pw, AppTask appTask)
        {
            Intent i = new Intent(act, typeof(EntryEditActivity));

            PwGroup parent = pw;
            i.PutExtra(KeyParent, parent.Uuid.ToHexString());

            appTask.ToIntent(i);

            act.StartActivityForResult(i, 0);
        }
コード例 #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="keepass2android.NavigateAndLaunchTask"/> class.
 /// </summary>
 /// <param name="groups">Groups.</param>
 /// <param name="taskToBeLaunchedAfterNavigation">Task to be launched after navigation.</param>
 /// <param name="toastEnable">If set to <c>true</c>, toast will be displayed after navigation.</param>
 protected NavigateAndLaunchTask(PwGroup groups, AppTask taskToBeLaunchedAfterNavigation, bool toastEnable = false)
 {
     TaskToBeLaunchedAfterNavigation = taskToBeLaunchedAfterNavigation;
     PopulateGroups(groups);
     ToastEnable = toastEnable;
 }
コード例 #20
0
ファイル: FileSelectActivity.cs プロジェクト: pythe/wristpass
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _design.ApplyTheme();

            Kp2aLog.Log("FileSelect.OnCreate");
            Kp2aLog.Log("FileSelect:apptask="+Intent.GetStringExtra("KP2A_APPTASK"));

            if (Intent.Action == Intent.ActionSend)
            {
                AppTask = new SearchUrlTask { UrlToSearchFor = Intent.GetStringExtra(Intent.ExtraText) };
            }
            else
            {
                //see PasswordActivity for an explanation
                if (Intent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory))
                {
                    AppTask = new NullTask();
                }
                else
                {
                    AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);
                }
            }

            _dbHelper = App.Kp2a.FileDbHelper;
            if (ShowRecentFiles())
            {
                _recentMode = true;

                SetContentView(Resource.Layout.file_selection);
                _fileSelectButtons = new view.FileSelectButtons(this);
                ((ListView)FindViewById(Android.Resource.Id.List)).AddFooterView(
                    _fileSelectButtons);

            } else
            {
                SetContentView(Resource.Layout.file_selection_no_recent);
                _fileSelectButtons = (view.FileSelectButtons)FindViewById(Resource.Id.file_select);
            #if NoNet
                ImageView imgView = FindViewById(Resource.Id.imglogo) as ImageView;
                if (imgView != null)
                {
                    imgView.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.ic_keepass2android_nonet));
                }
            #endif
            }

            Button openFileButton = (Button)FindViewById(Resource.Id.start_open_file);

            EventHandler openFileButtonClick = (sender, e) =>
            {
                Intent intent = new Intent(this, typeof(SelectStorageLocationActivity));
                intent.PutExtra(FileStorageSelectionActivity.AllowThirdPartyAppGet, true);
                intent.PutExtra(FileStorageSelectionActivity.AllowThirdPartyAppSend, false);
                intent.PutExtra(SelectStorageLocationActivity.ExtraKeyWritableRequirements, (int) SelectStorageLocationActivity.WritableRequirements.WriteDesired);
                intent.PutExtra(FileStorageSetupDefs.ExtraIsForSave, false);
                StartActivityForResult(intent, RequestCodeSelectIoc);

            };
            openFileButton.Click += openFileButtonClick;
            //OPEN URL
            Button openUrlButton = (Button)FindViewById(Resource.Id.start_open_url);

            openUrlButton.Visibility = ViewStates.Gone;

            //EventHandler openUrlButtonClick = (sender, e) => ShowFilenameDialog(true, false, false, "", GetString(Resource.String.enter_filename_details_url), Intents.RequestCodeFileBrowseForOpen);

            //CREATE NEW
            Button createNewButton = (Button)FindViewById(Resource.Id.start_create);
            EventHandler createNewButtonClick = (sender, e) =>
                {
                    //ShowFilenameDialog(false, true, true, Android.OS.Environment.ExternalStorageDirectory + GetString(Resource.String.default_file_path), "", Intents.RequestCodeFileBrowseForCreate)
                    Intent i = new Intent(this, typeof (CreateDatabaseActivity));
                    this.AppTask.ToIntent(i);
                    StartActivityForResult(i, 0);
                };
            createNewButton.Click += createNewButtonClick;

            /*//CREATE + IMPORT
            Button createImportButton = (Button)FindViewById(Resource.Id.start_create_import);
            createImportButton.Click += (object sender, EventArgs e) =>
            {
                openButton.Visibility = ViewStates.Gone;
                createButton.Visibility = ViewStates.Visible;
                enterFilenameDetails.Text = GetString(Resource.String.enter_filename_details_create_import);
                enterFilenameDetails.Visibility = enterFilenameDetails.Text == "" ? ViewStates.Gone : ViewStates.Visible;
                // Set the initial value of the filename
                EditText filename = (EditText)FindViewById(Resource.Id.file_filename);
                filename.Text = Android.OS.Environment.ExternalStorageDirectory + GetString(Resource.String.default_file_path);

            };*/

            FillData();

            RegisterForContextMenu(ListView);

            if (savedInstanceState != null)
            {
                AppTask = AppTask.CreateFromBundle(savedInstanceState);
                _recentMode = savedInstanceState.GetBoolean(BundleKeyRecentMode, _recentMode);
            }
        }
コード例 #21
0
ファイル: PasswordActivity.cs プロジェクト: pythe/wristpass
        public static void Launch(Activity act, String fileName, AppTask appTask)
        {
            File dbFile = new File(fileName);
            if ( ! dbFile.Exists() ) {
                throw new FileNotFoundException();
            }

            Intent i = new Intent(act, typeof(PasswordActivity));
            i.SetFlags(ActivityFlags.ForwardResult);
            i.PutExtra(KeyFilename, fileName);
            appTask.ToIntent(i);

            act.StartActivity(i);
        }
コード例 #22
0
 private void OnLockDatabase()
 {
     //app tasks are assumed to be finished/cancelled when the database is locked
     AppTask = new NullTask();
 }
コード例 #23
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.open_db_selection);

            var toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.mytoolbar);

            SetSupportActionBar(toolbar);

            SupportActionBar.Title = GetString(Resource.String.select_database);


            //only load the AppTask if this is the "first" OnCreate (not because of kill/resume, i.e. savedInstanceState==null)
            // and if the activity is not launched from history (i.e. recent tasks) because this would mean that
            // the Activity was closed already (user cancelling the task or task complete) but is restarted due recent tasks.
            // Don't re-start the task (especially bad if tak was complete already)
            if (Intent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory))
            {
                AppTask = new NullTask();
            }
            else
            {
                AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);
            }

            _adapter = new OpenDatabaseAdapter(this);
            var gridView = FindViewById <GridView>(Resource.Id.gridview);

            gridView.Adapter = _adapter;

            if (!string.IsNullOrEmpty(Intent.GetStringExtra(Util.KeyFilename)))
            {
                //forward to password activity
                Intent           i   = new Intent(this, typeof(PasswordActivity));
                IOConnectionInfo ioc = new IOConnectionInfo();
                Util.SetIoConnectionFromIntent(ioc, Intent);
                Util.PutIoConnectionToIntent(ioc, i);
                i.PutExtra(PasswordActivity.KeyKeyfile, i.GetStringExtra(PasswordActivity.KeyKeyfile));
                i.PutExtra(PasswordActivity.KeyPassword, i.GetStringExtra(PasswordActivity.KeyPassword));
                LaunchingOther = true;
                StartActivityForResult(i, ReqCodeOpenNewDb);
            }
            else
            {
                if (Intent.Action == Intent.ActionView)
                {
                    GetIocFromViewIntent(Intent);
                }
                else if (Intent.Action == Intent.ActionSend)
                {
                    AppTask = new SearchUrlTask {
                        UrlToSearchFor = Intent.GetStringExtra(Intent.ExtraText)
                    };
                }
            }

            _intentReceiver = new MyBroadcastReceiver(this);
            IntentFilter filter = new IntentFilter();

            filter.AddAction(Intents.DatabaseLocked);
            RegisterReceiver(_intentReceiver, filter);
        }
コード例 #24
0
ファイル: GroupBaseActivity.cs プロジェクト: pythe/wristpass
 public void StartTask(AppTask task)
 {
     AppTask = task;
     task.StartInGroupActivity(this);
 }
コード例 #25
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            _design.ApplyTheme();
            base.OnCreate(savedInstanceState);

            Android.Util.Log.Debug("KP2A", "Creating GBA");

            AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            // Likely the app has been killed exit the activity
            if (!App.Kp2a.GetDb().Loaded)
            {
                Finish();
                return;
            }

            _prefs = PreferenceManager.GetDefaultSharedPreferences(this);


            SetContentView(ContentResourceId);

            if (FindViewById(Resource.Id.enable_autofill) != null)
            {
                FindViewById(Resource.Id.enable_autofill).Click += (sender, args) =>
                {
                    var intent = new Intent(Settings.ActionRequestSetAutofillService);
                    intent.SetData(Android.Net.Uri.Parse("package:" + PackageName));
                    try
                    {
                        StartActivity(intent);
                    }
                    catch (ActivityNotFoundException e)
                    {
                        //this exception was reported by many Huawei users
                        Kp2aLog.LogUnexpectedError(e);
                        new AlertDialog.Builder(this)
                        .SetTitle(Resource.String.autofill_enable)
                        .SetMessage(Resource.String.autofill_enable_failed)
                        .SetPositiveButton(Resource.String.ok, (o, eventArgs) => { })
                        .Show();
                        const string autofillservicewasenabled = "AutofillServiceWasEnabled";
                        _prefs.Edit().PutBoolean(autofillservicewasenabled, true).Commit();
                        UpdateBottomBarElementVisibility(Resource.Id.autofill_infotext, false);
                    }
                };
            }

            if (FindViewById(Resource.Id.fabCancelAddNew) != null)
            {
                FindViewById(Resource.Id.fabAddNew).Click += (sender, args) =>
                {
                    FindViewById(Resource.Id.fabCancelAddNew).Visibility = ViewStates.Visible;
                    FindViewById(Resource.Id.fabAddNewGroup).Visibility  = AddGroupEnabled ? ViewStates.Visible : ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewEntry).Visibility  = AddEntryEnabled ? ViewStates.Visible : ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNew).Visibility       = ViewStates.Gone;
                };

                FindViewById(Resource.Id.fabCancelAddNew).Click += (sender, args) =>
                {
                    FindViewById(Resource.Id.fabCancelAddNew).Visibility = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewGroup).Visibility  = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewEntry).Visibility  = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNew).Visibility       = ViewStates.Visible;
                };
            }


            if (FindViewById(Resource.Id.cancel_insert_element) != null)
            {
                FindViewById(Resource.Id.cancel_insert_element).Click += (sender, args) => StopMovingElements();
                FindViewById(Resource.Id.insert_element).Click        += (sender, args) => InsertElements();
                Util.MoveBottomBarButtons(Resource.Id.cancel_insert_element, Resource.Id.insert_element, Resource.Id.bottom_bar, this);
            }

            if (FindViewById(Resource.Id.show_autofill_info) != null)
            {
                FindViewById(Resource.Id.show_autofill_info).Click += (sender, args) => Util.GotoUrl(this, "https://philippc.github.io/keepass2android/OreoAutoFill.html");
                Util.MoveBottomBarButtons(Resource.Id.show_autofill_info, Resource.Id.enable_autofill, Resource.Id.autofill_buttons, this);
            }

            if (FindViewById(Resource.Id.configure_notification_channels) != null)
            {
                FindViewById(Resource.Id.configure_notification_channels).Click += (sender, args) =>
                {
                    Intent intent = new Intent(Settings.ActionChannelNotificationSettings);
                    intent.PutExtra(Settings.ExtraChannelId, App.NotificationChannelIdQuicklocked);
                    intent.PutExtra(Settings.ExtraAppPackage, PackageName);
                    try
                    {
                        StartActivity(intent);
                    }
                    catch (Exception e)
                    {
                        new AlertDialog.Builder(this)
                        .SetTitle("Unexpected error")
                        .SetMessage(
                            "Opening the settings failed. Please report this to [email protected] including information about your device vendor and OS. Please try to configure the notifications by long pressing a KP2A notification. Details: " + e.ToString())
                        .Show();
                    }
                    UpdateAndroid8NotificationInfo(true);
                };
                FindViewById(Resource.Id.ignore_notification_channel).Click += (sender, args) =>
                {
                    UpdateAndroid8NotificationInfo(true);
                };
            }



            string lastInfoText;

            if (IsTimeForInfotext(out lastInfoText))
            {
                FingerprintUnlockMode um;
                Enum.TryParse(_prefs.GetString(Database.GetFingerprintModePrefKey(App.Kp2a.GetDb().Ioc), ""), out um);
                bool isFingerprintEnabled = (um == FingerprintUnlockMode.FullUnlock);

                string masterKeyKey = "MasterKey" + isFingerprintEnabled;
                string emergencyKey = "Emergency";
                string backupKey    = "Backup";

                List <string> applicableInfoTextKeys = new List <string> {
                    masterKeyKey
                };

                if (App.Kp2a.GetFileStorage(App.Kp2a.GetDb().Ioc).UserShouldBackup)
                {
                    applicableInfoTextKeys.Add(backupKey);
                }
                if (App.Kp2a.GetDb().Entries.Count > 15)
                {
                    applicableInfoTextKeys.Add(emergencyKey);
                }

                List <string> enabledInfoTextKeys = new List <string>();
                foreach (string key in applicableInfoTextKeys)
                {
                    if (!InfoTextWasDisabled(key))
                    {
                        enabledInfoTextKeys.Add(key);
                    }
                }

                if (enabledInfoTextKeys.Any())
                {
                    string infoTextKey = "", infoHead = "", infoMain = "", infoNote = "";

                    if (enabledInfoTextKeys.Count > 1)
                    {
                        foreach (string key in enabledInfoTextKeys)
                        {
                            if (key == lastInfoText)
                            {
                                enabledInfoTextKeys.Remove(key);
                                break;
                            }
                        }
                        infoTextKey = enabledInfoTextKeys[new Random().Next(enabledInfoTextKeys.Count)];
                    }

                    if (infoTextKey == masterKeyKey)
                    {
                        infoHead = GetString(Resource.String.masterkey_infotext_head);
                        infoMain = GetString(Resource.String.masterkey_infotext_main);
                        if (isFingerprintEnabled)
                        {
                            infoNote = GetString(Resource.String.masterkey_infotext_fingerprint_note);
                        }
                    }
                    else if (infoTextKey == emergencyKey)
                    {
                        infoHead = GetString(Resource.String.emergency_infotext_head);
                        infoMain = GetString(Resource.String.emergency_infotext_main);
                    }
                    else if (infoTextKey == backupKey)
                    {
                        infoHead = GetString(Resource.String.backup_infotext_head);
                        infoMain = GetString(Resource.String.backup_infotext_main);
                        infoNote = GetString(Resource.String.backup_infotext_note, GetString(Resource.String.menu_app_settings), GetString(Resource.String.menu_db_settings), GetString(Resource.String.export_prefs));
                    }



                    FindViewById <TextView>(Resource.Id.info_head).Text = infoHead;
                    FindViewById <TextView>(Resource.Id.info_main).Text = infoMain;
                    var additionalInfoText = FindViewById <TextView>(Resource.Id.info_additional);
                    additionalInfoText.Text       = infoNote;
                    additionalInfoText.Visibility = string.IsNullOrEmpty(infoNote) ? ViewStates.Gone : ViewStates.Visible;

                    if (infoTextKey != "")
                    {
                        RegisterInfoTextDisplay(infoTextKey);
                        FindViewById(Resource.Id.info_ok).Click += (sender, args) =>
                        {
                            UpdateBottomBarElementVisibility(Resource.Id.infotext, false);
                        };
                        FindViewById(Resource.Id.info_dont_show_again).Click += (sender, args) =>
                        {
                            UpdateBottomBarElementVisibility(Resource.Id.infotext, false);
                            DisableInfoTextDisplay(infoTextKey);
                        };

                        UpdateBottomBarElementVisibility(Resource.Id.infotext, true);
                    }
                }
            }



            SetResult(KeePass.ExitNormal);
        }
コード例 #26
0
 public void StartTask(AppTask task)
 {
     AppTask = task;
     task.StartInGroupActivity(this);
 }
コード例 #27
0
ファイル: AppTask.cs プロジェクト: pythe/wristpass
 /// <summary>
 /// Initializes a new instance of the <see cref="keepass2android.NavigateAndLaunchTask"/> class.
 /// </summary>
 /// <param name="groups">Groups.</param>
 /// <param name="taskToBeLaunchedAfterNavigation">Task to be launched after navigation.</param>
 /// <param name="toastEnable">If set to <c>true</c>, toast will be displayed after navigation.</param>
 protected NavigateAndLaunchTask(PwGroup groups, AppTask taskToBeLaunchedAfterNavigation, bool toastEnable = false)
 {
     TaskToBeLaunchedAfterNavigation = taskToBeLaunchedAfterNavigation;
     PopulateGroups (groups);
     ToastEnable = toastEnable;
 }
コード例 #28
0
ファイル: AppTask.cs プロジェクト: pythe/wristpass
 protected NavigateAndLaunchTask()
 {
     TaskToBeLaunchedAfterNavigation = new NullTask();
     FullGroupName = "";
     ToastEnable = false;
 }
コード例 #29
0
ファイル: AppTask.cs プロジェクト: pythe/wristpass
        /// <summary>
        /// Tries to extract the task from the data given as an Intent object in OnActivityResult. If successful, the task is assigned,
        /// otherwise, false is returned.
        /// </summary>
        public static bool TryGetFromActivityResult(Intent data, ref AppTask task)
        {
            if (data == null)
            {
                Kp2aLog.Log("TryGetFromActivityResult: no data");
                return false;
            }
            AppTask tempTask = CreateFromBundle(data.Extras, null);
            if (tempTask == null)
            {
                Kp2aLog.Log("No AppTask in OnActivityResult");
                return false;
            }

            task = tempTask;
            Kp2aLog.Log("AppTask " +task+" in OnActivityResult");
            return true;
        }
コード例 #30
0
ファイル: PasswordActivity.cs プロジェクト: pythe/wristpass
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            _keepPasswordInOnResume = true;
            Kp2aLog.Log("PasswordActivity.OnActivityResult "+resultCode+"/"+requestCode);

            AppTask.TryGetFromActivityResult(data, ref AppTask);

            //NOTE: original code from k eepassdroid used switch ((Android.App.Result)requestCode) { (but doesn't work here, although k eepassdroid works)
            switch(resultCode) {

                case KeePass.ExitNormal: // Returned to this screen using the Back key
                    if (PreferenceManager.GetDefaultSharedPreferences(this)
                                         .GetBoolean(GetString(Resource.String.LockWhenNavigateBack_key), false))
                    {
                        App.Kp2a.LockDatabase();
                    }
                    //by leaving the app with the back button, the user probably wants to cancel the task
                    //The activity might be resumed (through Android's recent tasks list), then use a NullTask:
                    AppTask = new NullTask();
                    Finish();
                    break;
                case KeePass.ExitLock:
                    // The database has already been locked, and the quick unlock screen will be shown if appropriate

                    _rememberKeyfile = _prefs.GetBoolean(GetString(Resource.String.keyfile_key), Resources.GetBoolean(Resource.Boolean.keyfile_default)); //update value
                    if ((KeyProviderType == KeyProviders.KeyFile) && (_rememberKeyfile))
                    {
                        //check if the keyfile was changed (by importing to internal directory)
                        var newKeyFile = GetKeyFile(_ioConnection.Path);
                        if (newKeyFile != _keyFileOrProvider)
                        {
                            _keyFileOrProvider = newKeyFile;
                            UpdateKeyfileIocView();
                        }
                    }
                    break;
                case KeePass.ExitCloseAfterTaskComplete:
                    // Do not lock the database
                    SetResult(KeePass.ExitCloseAfterTaskComplete);
                    Finish();
                    break;
                case KeePass.ExitClose:
                    SetResult(KeePass.ExitClose);
                    Finish();
                    break;
                case KeePass.ExitReloadDb:

                    if (App.Kp2a.GetDb().Loaded)
                    {
                        //remember the composite key for reloading:
                        var compositeKey = App.Kp2a.GetDb().KpDatabase.MasterKey;

                        //lock the database:
                        App.Kp2a.LockDatabase(false);

                        //reload the database (without most other stuff performed in PerformLoadDatabase.
                        // We're assuming that the db file (and if appropriate also the key file) are still available
                        // and there's no need to re-init the file storage. if it is, loading will fail and the user has
                        // to retry with typing the full password, but that's intended to avoid showing the password to a
                        // a potentially unauthorized user (feature request https://keepass2android.codeplex.com/workitem/274)
                        Handler handler = new Handler();
                        OnFinish onFinish = new AfterLoad(handler, this);
                        _performingLoad = true;
                        LoadDb task = new LoadDb(App.Kp2a, _ioConnection, _loadDbTask, compositeKey, _keyFileOrProvider, onFinish);
                        _loadDbTask = null; // prevent accidental re-use
                        new ProgressTask(App.Kp2a, this, task).Run();
                    }

                    break;
                case Result.Ok:
                    if (requestCode == RequestCodeSelectKeyfile)
                    {
                        IOConnectionInfo ioc = new IOConnectionInfo();
                        SetIoConnectionFromIntent(ioc, data);
                        _keyFileOrProvider = IOConnectionInfo.SerializeToString(ioc);
                        UpdateKeyfileIocView();
                    }
                    break;
                case (Result)FileStorageResults.FileUsagePrepared:
                    if (requestCode == RequestCodePrepareDbFile)
                    {
                        if (KeyProviderType == KeyProviders.KeyFile)
                        {
                            var iocKeyfile = IOConnectionInfo.UnserializeFromString(_keyFileOrProvider);

                            App.Kp2a.GetFileStorage(iocKeyfile)
                                .PrepareFileUsage(new FileStorageSetupInitiatorActivity(this, OnActivityResult, null), iocKeyfile,
                                         RequestCodePrepareKeyFile, false);
                        }
                        else
                            PerformLoadDatabase();
                    }
                    if (requestCode == RequestCodePrepareKeyFile)
                    {
                        PerformLoadDatabase();
                    }
                    if (requestCode == RequestCodePrepareOtpAuxFile)
                    {
                        GetAuxFileLoader().LoadAuxFile(true);
                    }
                    break;
            }
            if (requestCode == RequestCodeSelectAuxFile && resultCode == Result.Ok)
            {
                IOConnectionInfo auxFileIoc = new IOConnectionInfo();
                SetIoConnectionFromIntent(auxFileIoc, data);

                PreferenceManager.GetDefaultSharedPreferences(this).Edit()
                                 .PutString("KP2A.PasswordAct.AuxFileIoc" + IOConnectionInfo.SerializeToString(_ioConnection),
                                            IOConnectionInfo.SerializeToString(auxFileIoc))
                                 .Apply();

                GetAuxFileLoader().LoadAuxFile(false);
            }
            if (requestCode == RequestCodeChallengeYubikey && resultCode == Result.Ok)
            {
                try
                {
                    _challengeProv = new KeeChallengeProv();
                    byte[] challengeResponse = data.GetByteArrayExtra("response");
                    _challengeSecret = _challengeProv.GetSecret(_chalInfo, challengeResponse);
                    Array.Clear(challengeResponse, 0, challengeResponse.Length);
                }
                catch (Exception e)
                {
                    Kp2aLog.Log(e.ToString());
                    Toast.MakeText(this, "Error: " + e.Message, ToastLength.Long).Show();
                    return;
                }

                UpdateOkButtonState();
                FindViewById(Resource.Id.otpInitView).Visibility = ViewStates.Gone;

                if (_challengeSecret != null)
                {
                    new LoadingDialog<object, object, object>(this, true,
                        //doInBackground
                    delegate
                    {
                        //save aux file
                        try
                        {
                            ChallengeInfo temp = _challengeProv.Encrypt(_challengeSecret);
                            IFileStorage fileStorage = App.Kp2a.GetOtpAuxFileStorage(_ioConnection);
                            IOConnectionInfo iocAux = fileStorage.GetFilePath(fileStorage.GetParentPath(_ioConnection),
                                fileStorage.GetFilenameWithoutPathAndExt(_ioConnection) + ".xml");
                            if (!temp.Save(iocAux))
                            {
                                Toast.MakeText(this, Resource.String.ErrorUpdatingChalAuxFile, ToastLength.Long).Show();
                                return false;
                            }

                        }
                        catch (Exception e)
                        {
                            Kp2aLog.Log(e.ToString());
                        }
                        return null;
                    }
                    , delegate
                    {

                    }).Execute();

                }
                else
                {
                    Toast.MakeText(this, Resource.String.bad_resp, ToastLength.Long).Show();
                    return;
                }
            }
        }
コード例 #31
0
ファイル: GroupBaseActivity.cs プロジェクト: pythe/wristpass
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            // Likely the app has been killed exit the activity
            if ( ! App.Kp2a.GetDb().Loaded ) {
                Finish();
                return;
            }

            _prefs = PreferenceManager.GetDefaultSharedPreferences(this);

            GroupView = new GroupView(this);
            SetContentView(GroupView);

            FindViewById(Resource.Id.cancel_insert_element).Click += (sender, args) => StopMovingElement();
            FindViewById(Resource.Id.insert_element).Click += (sender, args) => InsertElement();

            SetResult(KeePass.ExitNormal);

            StyleScrollBars();
        }
コード例 #32
0
 private void OnDatabaseSelected(Database selectedDatabase)
 {
     App.Kp2a.CurrentDb = selectedDatabase;
     LaunchingOther     = true;
     AppTask.LaunchFirstGroupActivity(this);
 }
コード例 #33
0
 public static void Launch(Activity act, AppTask appTask)
 {
     Launch(act, null, appTask);
 }
コード例 #34
0
ファイル: PasswordActivity.cs プロジェクト: pythe/wristpass
        public static void Launch(Activity act, IOConnectionInfo ioc, AppTask appTask)
        {
            if (ioc.IsLocalFile())
            {
                Launch(act, ioc.Path, appTask);
                return;
            }

            Intent i = new Intent(act, typeof(PasswordActivity));

            PutIoConnectionToIntent(ioc, i);
            i.SetFlags(ActivityFlags.ForwardResult);

            appTask.ToIntent(i);

            act.StartActivity(i);
        }
コード例 #35
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            _design.ApplyTheme();
            base.OnCreate(savedInstanceState);

            Android.Util.Log.Debug("KP2A", "Creating GBA");

            AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            // Likely the app has been killed exit the activity
            if (!App.Kp2a.GetDb().Loaded)
            {
                Finish();
                return;
            }

            _prefs = PreferenceManager.GetDefaultSharedPreferences(this);


            SetContentView(ContentResourceId);

            if (FindViewById(Resource.Id.enable_autofill) != null)
            {
                FindViewById(Resource.Id.enable_autofill).Click += (sender, args) =>
                {
                    var intent = new Intent(Settings.ActionRequestSetAutofillService);
                    intent.SetData(Android.Net.Uri.Parse("package:" + PackageName));
                    StartActivity(intent);
                };
            }

            if (FindViewById(Resource.Id.fabCancelAddNew) != null)
            {
                FindViewById(Resource.Id.fabAddNew).Click += (sender, args) =>
                {
                    FindViewById(Resource.Id.fabCancelAddNew).Visibility = ViewStates.Visible;
                    FindViewById(Resource.Id.fabAddNewGroup).Visibility  = AddGroupEnabled ? ViewStates.Visible : ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewEntry).Visibility  = AddEntryEnabled ? ViewStates.Visible : ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNew).Visibility       = ViewStates.Gone;
                };

                FindViewById(Resource.Id.fabCancelAddNew).Click += (sender, args) =>
                {
                    FindViewById(Resource.Id.fabCancelAddNew).Visibility = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewGroup).Visibility  = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewEntry).Visibility  = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNew).Visibility       = ViewStates.Visible;
                };
            }


            if (FindViewById(Resource.Id.cancel_insert_element) != null)
            {
                FindViewById(Resource.Id.cancel_insert_element).Click += (sender, args) => StopMovingElements();
                FindViewById(Resource.Id.insert_element).Click        += (sender, args) => InsertElements();
                Util.MoveBottomBarButtons(Resource.Id.cancel_insert_element, Resource.Id.insert_element, Resource.Id.bottom_bar, this);
            }

            if (FindViewById(Resource.Id.show_autofill_info) != null)
            {
                FindViewById(Resource.Id.show_autofill_info).Click += (sender, args) => Util.GotoUrl(this, "https://philippc.github.io/keepass2android/OreoAutoFill.html");
                Util.MoveBottomBarButtons(Resource.Id.show_autofill_info, Resource.Id.enable_autofill, Resource.Id.autofill_buttons, this);
            }



            SetResult(KeePass.ExitNormal);
        }
コード例 #36
0
 protected override void OnSaveInstanceState(Bundle outState)
 {
     base.OnSaveInstanceState(outState);
     AppTask.ToBundle(outState);
 }
コード例 #37
0
ファイル: PasswordActivity.cs プロジェクト: pythe/wristpass
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _design.ApplyTheme();

            //use FlagSecure to make sure the last (revealed) character of the master password is not visible in recent apps
            if (PreferenceManager.GetDefaultSharedPreferences(this).GetBoolean(
                GetString(Resource.String.ViewDatabaseSecure_key), true))
            {
                Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
            }

            Intent i = Intent;

            //only load the AppTask if this is the "first" OnCreate (not because of kill/resume, i.e. savedInstanceState==null)
            // and if the activity is not launched from history (i.e. recent tasks) because this would mean that
            // the Activity was closed already (user cancelling the task or task complete) but is restarted due recent tasks.
            // Don't re-start the task (especially bad if tak was complete already)
            if (Intent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory))
            {
                AppTask = new NullTask();
            }
            else
            {
                AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);
            }

            String action = i.Action;

            _prefs = PreferenceManager.GetDefaultSharedPreferences(this);
            _rememberKeyfile = _prefs.GetBoolean(GetString(Resource.String.keyfile_key), Resources.GetBoolean(Resource.Boolean.keyfile_default));

            _ioConnection = new IOConnectionInfo();

            if (action != null && action.Equals(ViewIntent))
            {
                if (!GetIocFromViewIntent(i)) return;
            }
            else if ((action != null) && (action.Equals(Intents.StartWithOtp)))
            {
                if (!GetIocFromOtpIntent(savedInstanceState, i)) return;
                _keepPasswordInOnResume = true;
            }
            else
            {
                SetIoConnectionFromIntent(_ioConnection, i);
                var keyFileFromIntent = i.GetStringExtra(KeyKeyfile);
                if (keyFileFromIntent != null)
                {
                    Kp2aLog.Log("try get keyfile from intent");
                    _keyFileOrProvider = IOConnectionInfo.SerializeToString(IOConnectionInfo.FromPath(keyFileFromIntent));
                    Kp2aLog.Log("try get keyfile from intent ok");
                }
                else
                {
                    _keyFileOrProvider = null;
                }
                _password = i.GetStringExtra(KeyPassword) ?? "";
                if (string.IsNullOrEmpty(_keyFileOrProvider))
                {
                    _keyFileOrProvider = GetKeyFile(_ioConnection.Path);
                }
                if ((!string.IsNullOrEmpty(_keyFileOrProvider)) || (_password != ""))
                {
                    _keepPasswordInOnResume = true;
                }
            }

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

            SetContentView(Resource.Layout.password);
            InitializeFilenameView();

            if (KeyProviderType == KeyProviders.KeyFile)
            {
                UpdateKeyfileIocView();
            }

            FindViewById<EditText>(Resource.Id.password).TextChanged +=
                (sender, args) =>
                {
                    _password = FindViewById<EditText>(Resource.Id.password).Text;
                    UpdateOkButtonState();
                };
            FindViewById<EditText>(Resource.Id.password).EditorAction += (sender, args) =>
                {
                    if ((args.ActionId == ImeAction.Done) || ((args.ActionId == ImeAction.ImeNull) && (args.Event.Action == KeyEventActions.Down)))
                        OnOk();
                };

            FindViewById<EditText>(Resource.Id.pass_otpsecret).TextChanged += (sender, args) => UpdateOkButtonState();

            EditText passwordEdit = FindViewById<EditText>(Resource.Id.password);
            passwordEdit.Text = _password;
            passwordEdit.RequestFocus();
            Window.SetSoftInputMode(SoftInput.StateVisible);

            InitializeOkButton();

            InitializePasswordModeSpinner();

            InitializeOtpSecretSpinner();

            UpdateOkButtonState();

            InitializeTogglePasswordButton();
            InitializeKeyfileBrowseButton();

            InitializeQuickUnlockCheckbox();

            RestoreState(savedInstanceState);

            if (i.GetBooleanExtra("launchImmediately", false))
            {
                App.Kp2a.GetFileStorage(_ioConnection)
                       .PrepareFileUsage(new FileStorageSetupInitiatorActivity(this, OnActivityResult, null), _ioConnection,
                                         RequestCodePrepareDbFile, false);
            }
        }
コード例 #38
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            _design.ApplyTheme();

            SetContentView(Resource.Layout.create_database);
            _appTask = AppTask.GetTaskInOnCreate(bundle, Intent);

            SetDefaultIoc();

            FindViewById(Resource.Id.keyfile_filename).Visibility = ViewStates.Gone;

            var keyfileCheckbox = FindViewById<CheckBox>(Resource.Id.use_keyfile);

            if (bundle != null)
            {
                _keyfileFilename = bundle.GetString(KeyfilefilenameBundleKey, null);
                if (_keyfileFilename != null)
                {
                    FindViewById<TextView>(Resource.Id.keyfile_filename).Text = ConvertFilenameToIocPath(_keyfileFilename);
                    FindViewById(Resource.Id.keyfile_filename).Visibility = ViewStates.Visible;
                    keyfileCheckbox.Checked = true;
                }

                if (bundle.GetString(PasswordActivity.KeyFilename, null) != null)
                {
                    _ioc = new IOConnectionInfo
                        {
                            Path = bundle.GetString(PasswordActivity.KeyFilename),
                            UserName = bundle.GetString(PasswordActivity.KeyServerusername),
                            Password = bundle.GetString(PasswordActivity.KeyServerpassword),
                            CredSaveMode = (IOCredSaveMode) bundle.GetInt(PasswordActivity.KeyServercredmode),
                        };
                }
            }

            UpdateIocView();

            keyfileCheckbox.CheckedChange += (sender, args) =>
                {
                    if (keyfileCheckbox.Checked)
                    {
                        if (_restoringInstanceState)
                            return;

                        string defaulFilename = _keyfileFilename;
                        if (_keyfileFilename == null)
                        {
                            defaulFilename = _keyfileFilename = SdDir + "keyfile.txt";
                            if (defaulFilename.StartsWith("file://") == false)
                                defaulFilename = "file://" + defaulFilename;
                        }

                        StartFileChooser(defaulFilename, RequestCodeKeyFile, false);

                    }
                    else
                    {
                        FindViewById(Resource.Id.keyfile_filename).Visibility = ViewStates.Gone;
                        _keyfileFilename = null;
                    }
                };

            FindViewById(Resource.Id.btn_change_location).Click += (sender, args) =>
            {
                Intent intent = new Intent(this, typeof(FileStorageSelectionActivity));
                StartActivityForResult(intent, 0);
            };

            Button generatePassword = (Button)FindViewById(Resource.Id.generate_button);
            generatePassword.Click += (sender, e) =>
            {
                GeneratePasswordActivity.LaunchWithoutLockCheck(this);
            };

            FindViewById(Resource.Id.btn_create).Click += (sender, evt) =>
            {
                CreateDatabase();
            };

            ImageButton btnTogglePassword = (ImageButton)FindViewById(Resource.Id.toggle_password);
            btnTogglePassword.Click += (sender, e) =>
            {
                _showPassword = !_showPassword;
                MakePasswordMaskedOrVisible();
            };
        }
コード例 #39
0
ファイル: EntryActivity.cs プロジェクト: pythe/wristpass
        public static void Launch(Activity act, PwEntry pw, int pos, AppTask appTask, ActivityFlags? flags = null)
        {
            Intent i = new Intent(act, typeof(EntryActivity));

            i.PutExtra(KeyEntry, pw.Uuid.ToHexString());
            i.PutExtra(KeyRefreshPos, pos);

            if (flags != null)
                i.SetFlags((ActivityFlags) flags);

            appTask.ToIntent(i);
            if (flags != null && (((ActivityFlags) flags) | ActivityFlags.ForwardResult) == ActivityFlags.ForwardResult)
                act.StartActivity(i);
            else
                act.StartActivityForResult(i, 0);
        }
コード例 #40
0
 protected NavigateAndLaunchTask()
 {
     TaskToBeLaunchedAfterNavigation = new NullTask();
     FullGroupName = "";
     ToastEnable   = false;
 }
コード例 #41
0
ファイル: EntryActivity.cs プロジェクト: pythe/wristpass
        protected override void OnCreate(Bundle savedInstanceState)
        {
            ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);

            long usageCount = prefs.GetLong(GetString(Resource.String.UsageCount_key), 0);

            ISharedPreferencesEditor edit = prefs.Edit();
            edit.PutLong(GetString(Resource.String.UsageCount_key), usageCount + 1);
            edit.Commit();

            _showPassword =
                !prefs.GetBoolean(GetString(Resource.String.maskpass_key), Resources.GetBoolean(Resource.Boolean.maskpass_default));

            base.OnCreate(savedInstanceState);
            RequestWindowFeature(WindowFeatures.IndeterminateProgress);

            new ActivityDesign(this).ApplyTheme();

            SetEntryView();

            Database db = App.Kp2a.GetDb();
            // Likely the app has been killed exit the activity
            if (!db.Loaded || (App.Kp2a.QuickLocked))
            {
                Finish();
                return;
            }

            SetResult(KeePass.ExitNormal);

            Intent i = Intent;
            PwUuid uuid = new PwUuid(MemUtil.HexStringToByteArray(i.GetStringExtra(KeyEntry)));
            _pos = i.GetIntExtra(KeyRefreshPos, -1);

            _appTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            Entry = db.Entries[uuid];
            Android.Util.Log.Debug("KP2A", "Notes: " + Entry.Strings.ReadSafe(PwDefs.NotesField));

            // Refresh Menu contents in case onCreateMenuOptions was called before Entry was set
            ActivityCompat.InvalidateOptionsMenu(this);

            // Update last access time.
            Entry.Touch(false);

            if (PwDefs.IsTanEntry(Entry) && prefs.GetBoolean(GetString(Resource.String.TanExpiresOnUse_key), Resources.GetBoolean(Resource.Boolean.TanExpiresOnUse_default)) && ((Entry.Expires == false) || Entry.ExpiryTime > DateTime.Now))
            {
                PwEntry backupEntry = Entry.CloneDeep();
                Entry.ExpiryTime = DateTime.Now;
                Entry.Expires = true;
                Entry.Touch(true);
                RequiresRefresh();
                UpdateEntry update = new UpdateEntry(this, App.Kp2a, backupEntry, Entry, null);
                ProgressTask pt = new ProgressTask(App.Kp2a, this, update);
                pt.Run();
            }
            FillData();

            SetupEditButtons();
            SetupMoveButtons ();

            App.Kp2a.GetDb().LastOpenedEntry = new PwEntryOutput(Entry, App.Kp2a.GetDb().KpDatabase);

            _pluginActionReceiver = new PluginActionReceiver(this);
            RegisterReceiver(_pluginActionReceiver, new IntentFilter(Strings.ActionAddEntryAction));
            _pluginFieldReceiver = new PluginFieldReceiver(this);
            RegisterReceiver(_pluginFieldReceiver, new IntentFilter(Strings.ActionSetEntryField));

            new Thread(NotifyPluginsOnOpen).Start();

            //the rest of the things to do depends on the current app task:
            _appTask.CompleteOnCreateEntryActivity(this);
        }
コード例 #42
0
ファイル: EntryActivity.cs プロジェクト: ypid/keepass2android
        protected override void OnCreate(Bundle savedInstanceState)
        {
            ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);

            long usageCount = prefs.GetLong(GetString(Resource.String.UsageCount_key), 0);

            ISharedPreferencesEditor edit = prefs.Edit();

            edit.PutLong(GetString(Resource.String.UsageCount_key), usageCount + 1);
            edit.Commit();

            _showPassword =
                !prefs.GetBoolean(GetString(Resource.String.maskpass_key), Resources.GetBoolean(Resource.Boolean.maskpass_default));

            RequestWindowFeature(WindowFeatures.IndeterminateProgress);

            _activityDesign.ApplyTheme();
            base.OnCreate(savedInstanceState);



            SetEntryView();

            Database db = App.Kp2a.GetDb();

            // Likely the app has been killed exit the activity
            if (!db.Loaded || (App.Kp2a.QuickLocked))
            {
                Finish();
                return;
            }

            SetResult(KeePass.ExitNormal);

            Intent i    = Intent;
            PwUuid uuid = new PwUuid(MemUtil.HexStringToByteArray(i.GetStringExtra(KeyEntry)));

            _pos = i.GetIntExtra(KeyRefreshPos, -1);

            _appTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            Entry = db.Entries[uuid];

            // Refresh Menu contents in case onCreateMenuOptions was called before Entry was set
            ActivityCompat.InvalidateOptionsMenu(this);

            // Update last access time.
            Entry.Touch(false);

            if (PwDefs.IsTanEntry(Entry) && prefs.GetBoolean(GetString(Resource.String.TanExpiresOnUse_key), Resources.GetBoolean(Resource.Boolean.TanExpiresOnUse_default)) && ((Entry.Expires == false) || Entry.ExpiryTime > DateTime.Now))
            {
                PwEntry backupEntry = Entry.CloneDeep();
                Entry.ExpiryTime = DateTime.Now;
                Entry.Expires    = true;
                Entry.Touch(true);
                RequiresRefresh();
                UpdateEntry  update = new UpdateEntry(this, App.Kp2a, backupEntry, Entry, null);
                ProgressTask pt     = new ProgressTask(App.Kp2a, this, update);
                pt.Run();
            }
            FillData();

            SetupEditButtons();

            App.Kp2a.GetDb().LastOpenedEntry = new PwEntryOutput(Entry, App.Kp2a.GetDb().KpDatabase);

            _pluginActionReceiver = new PluginActionReceiver(this);
            RegisterReceiver(_pluginActionReceiver, new IntentFilter(Strings.ActionAddEntryAction));
            _pluginFieldReceiver = new PluginFieldReceiver(this);
            RegisterReceiver(_pluginFieldReceiver, new IntentFilter(Strings.ActionSetEntryField));

            new Thread(NotifyPluginsOnOpen).Start();

            //the rest of the things to do depends on the current app task:
            _appTask.CompleteOnCreateEntryActivity(this);
        }
コード例 #43
0
 public static void Launch(Activity act, AppTask appTask, ActivityLaunchMode launchMode)
 {
     Launch(act, null, appTask, launchMode);
 }
コード例 #44
0
ファイル: KeePass.cs プロジェクト: pythe/wristpass
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _design.ApplyTheme();
            //see comment to this in PasswordActivity.
            //Note that this activity is affected even though it's finished when the app is closed because it
            //seems that the "app launch intent" is re-delivered, so this might end up here.
            if ((_appTask == null) && (Intent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory)))
            {
                _appTask = new NullTask();
            }
            else
            {
                _appTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);
            }

            Kp2aLog.Log("KeePass.OnCreate");
        }
コード例 #45
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            _design.ApplyTheme();
            base.OnCreate(savedInstanceState);

            Android.Util.Log.Debug("KP2A", "Creating GBA");

            AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            // Likely the app has been killed exit the activity
            if (!App.Kp2a.GetDb().Loaded)
            {
                Finish();
                return;
            }

            _prefs = PreferenceManager.GetDefaultSharedPreferences(this);


            SetContentView(ContentResourceId);

            if (FindViewById(Resource.Id.enable_autofill) != null)
            {
                FindViewById(Resource.Id.enable_autofill).Click += (sender, args) =>
                {
                    var intent = new Intent(Settings.ActionRequestSetAutofillService);
                    intent.SetData(Android.Net.Uri.Parse("package:" + PackageName));
                    try
                    {
                        StartActivity(intent);
                    }
                    catch (ActivityNotFoundException e)
                    {
                        //this exception was reported by many Huawei users
                        Kp2aLog.LogUnexpectedError(e);
                        new AlertDialog.Builder(this)
                        .SetTitle(Resource.String.autofill_enable)
                        .SetMessage(Resource.String.autofill_enable_failed)
                        .SetPositiveButton(Resource.String.ok, (o, eventArgs) => { })
                        .Show();
                        const string autofillservicewasenabled = "AutofillServiceWasEnabled";
                        _prefs.Edit().PutBoolean(autofillservicewasenabled, true).Commit();
                        UpdateBottomBarElementVisibility(Resource.Id.autofill_infotext, false);
                    }
                };
            }


            if (FindViewById(Resource.Id.info_dont_show_autofill_again) != null)
            {
                FindViewById(Resource.Id.info_dont_show_autofill_again).Click += (sender, args) =>
                {
                    _prefs.Edit().PutBoolean(autofillservicewasenabled_prefskey, true).Commit();
                    UpdateAutofillInfo();
                };
            }

            if (FindViewById(Resource.Id.fabCancelAddNew) != null)
            {
                FindViewById(Resource.Id.fabAddNew).Click += (sender, args) =>
                {
                    FindViewById(Resource.Id.fabCancelAddNew).Visibility = ViewStates.Visible;
                    FindViewById(Resource.Id.fabAddNewGroup).Visibility  = AddGroupEnabled ? ViewStates.Visible : ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewEntry).Visibility  = AddEntryEnabled ? ViewStates.Visible : ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNew).Visibility       = ViewStates.Gone;
                };

                FindViewById(Resource.Id.fabCancelAddNew).Click += (sender, args) =>
                {
                    FindViewById(Resource.Id.fabCancelAddNew).Visibility = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewGroup).Visibility  = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewEntry).Visibility  = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNew).Visibility       = ViewStates.Visible;
                };
            }


            if (FindViewById(Resource.Id.cancel_insert_element) != null)
            {
                FindViewById(Resource.Id.cancel_insert_element).Click += (sender, args) => StopMovingElements();
                FindViewById(Resource.Id.insert_element).Click        += (sender, args) => InsertElements();
                Util.MoveBottomBarButtons(Resource.Id.cancel_insert_element, Resource.Id.insert_element, Resource.Id.bottom_bar, this);
            }

            if (FindViewById(Resource.Id.show_autofill_info) != null)
            {
                FindViewById(Resource.Id.show_autofill_info).Click += (sender, args) => Util.GotoUrl(this, "https://philippc.github.io/keepass2android/OreoAutoFill.html");
                Util.MoveBottomBarButtons(Resource.Id.show_autofill_info, Resource.Id.enable_autofill, Resource.Id.autofill_buttons, this);
            }

            if (FindViewById(Resource.Id.configure_notification_channels) != null)
            {
                FindViewById(Resource.Id.configure_notification_channels).Click += (sender, args) =>
                {
                    Intent intent = new Intent(Settings.ActionChannelNotificationSettings);
                    intent.PutExtra(Settings.ExtraChannelId, App.NotificationChannelIdQuicklocked);
                    intent.PutExtra(Settings.ExtraAppPackage, PackageName);
                    try
                    {
                        StartActivity(intent);
                    }
                    catch (Exception e)
                    {
                        new AlertDialog.Builder(this)
                        .SetTitle("Unexpected error")
                        .SetMessage(
                            "Opening the settings failed. Please report this to [email protected] including information about your device vendor and OS. Please try to configure the notifications by long pressing a KP2A notification. Details: " + e.ToString())
                        .Show();
                    }
                    UpdateAndroid8NotificationInfo(true);
                };
                FindViewById(Resource.Id.ignore_notification_channel).Click += (sender, args) =>
                {
                    UpdateAndroid8NotificationInfo(true);
                };
            }



            SetResult(KeePass.ExitNormal);
        }
コード例 #46
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            if (LastNonConfigurationInstance != null)
            {
                //bug in Mono for Android or whatever: after config change the extra fields are wrong
                // -> reload:
                Reload();
                return;
            }

            _appTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            SetContentView(Resource.Layout.entry_edit);
            _closeForReload = false;

            // Likely the app has been killed exit the activity
            if (!App.Kp2a.DatabaseIsUnlocked)
            {
                Finish();
                return;
            }


            if (Intent.GetBooleanExtra(IntentContinueWithEditing, false))
            {
                //property "State" will return the state
            }
            else
            {
                Database db = App.Kp2a.GetDb();

                App.Kp2a.EntryEditActivityState = new EntryEditActivityState();
                ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
                State.ShowPassword = !prefs.GetBoolean(GetString(Resource.String.maskpass_key), Resources.GetBoolean(Resource.Boolean.maskpass_default));

                Intent i         = Intent;
                String uuidBytes = i.GetStringExtra(KeyEntry);

                PwUuid entryId = PwUuid.Zero;
                if (uuidBytes != null)
                {
                    entryId = new PwUuid(MemUtil.HexStringToByteArray(uuidBytes));
                }

                State.ParentGroup = null;
                if (entryId.Equals(PwUuid.Zero))
                {
                    //creating new entry
                    String groupId = i.GetStringExtra(KeyParent);
                    State.ParentGroup = db.KpDatabase.RootGroup.FindGroup(new PwUuid(MemUtil.HexStringToByteArray(groupId)), true);

                    PwUuid  templateId    = new PwUuid(MemUtil.HexStringToByteArray(i.GetStringExtra(KeyTemplateUuid)));
                    PwEntry templateEntry = null;
                    if (!PwUuid.Zero.Equals(templateId))
                    {
                        templateEntry = db.Entries[templateId];
                    }

                    if (KpEntryTemplatedEdit.IsTemplate(templateEntry))
                    {
                        CreateNewFromKpEntryTemplate(db, templateEntry);
                    }
                    else if (templateEntry != null)
                    {
                        CreateNewFromStandardTemplate(templateEntry);
                    }
                    else
                    {
                        CreateNewWithoutTemplate(db);
                    }

                    _appTask.PrepareNewEntry(State.EntryInDatabase);
                    State.IsNew         = true;
                    State.EntryModified = true;
                }
                else
                {
                    Debug.Assert(entryId != null);

                    State.EntryInDatabase = db.Entries [entryId];
                    State.IsNew           = false;
                }

                State.Entry = State.EntryInDatabase.CloneDeep();
                if (KpEntryTemplatedEdit.IsTemplated(db, State.Entry))
                {
                    State.EditMode = new KpEntryTemplatedEdit(db, State.Entry);
                }
                else
                {
                    State.EditMode = new DefaultEdit();
                }
            }

            if (!State.EntryModified)
            {
                SetResult(KeePass.ExitNormal);
            }
            else
            {
                SetResult(KeePass.ExitRefreshTitle);
            }



            FillData();
            View scrollView = FindViewById(Resource.Id.entry_scroll);

            scrollView.ScrollBarStyle = ScrollbarStyles.InsideInset;

            ImageButton iconButton = (ImageButton)FindViewById(Resource.Id.icon_button);

            if (State.SelectedIcon)
            {
                App.Kp2a.GetDb().DrawableFactory.AssignDrawableTo(iconButton, this, App.Kp2a.GetDb().KpDatabase, (PwIcon)State.SelectedIconId, State.SelectedCustomIconId, false);
            }
            iconButton.Click += (sender, evt) => {
                UpdateEntryFromUi(State.Entry);
                IconPickerActivity.Launch(this);
            };


            // Generate password button
            FindViewById(Resource.Id.generate_button).Click += (sender, e) =>
            {
                UpdateEntryFromUi(State.Entry);
                GeneratePasswordActivity.Launch(this);
            };



            // Save button
            //SupportActionBar.SetCustomView(Resource.Layout.SaveButton);

            if (State.IsNew)
            {
                SupportActionBar.Title = GetString(Resource.String.add_entry);
            }
            else
            {
                SupportActionBar.Title = GetString(Resource.String.edit_entry);
            }

            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetHomeButtonEnabled(true);

            // Respect mask password setting
            MakePasswordVisibleOrHidden();

            ImageButton btnTogglePassword = (ImageButton)FindViewById(Resource.Id.toggle_password);

            btnTogglePassword.Click += (sender, e) =>
            {
                State.ShowPassword = !State.ShowPassword;
                MakePasswordVisibleOrHidden();
            };
            PorterDuff.Mode mMode = PorterDuff.Mode.SrcAtop;
            Color           color = new Color(189, 189, 189);

            btnTogglePassword.SetColorFilter(color, mMode);


            Button addButton = (Button)FindViewById(Resource.Id.add_advanced);

            addButton.Visibility = ViewStates.Visible;
            addButton.Click     += (sender, e) =>
            {
                LinearLayout container = (LinearLayout)FindViewById(Resource.Id.advanced_container);

                KeyValuePair <string, ProtectedString> pair = new KeyValuePair <string, ProtectedString>("", new ProtectedString(true, ""));
                View ees = CreateExtraStringView(pair);
                container.AddView(ees);

                State.EntryModified = true;

                /*TextView keyView = (TextView) ees.FindViewById(Resource.Id.title);
                 * keyView.RequestFocus();*/
                EditAdvancedString(ees.FindViewById(Resource.Id.edit_extra));
            };
            SetAddExtraStringEnabled();

            ((CheckBox)FindViewById(Resource.Id.entry_expires_checkbox)).CheckedChange += (sender, e) =>
            {
                State.Entry.Expires = e.IsChecked;
                if (e.IsChecked)
                {
                    if (State.Entry.ExpiryTime < DateTime.Now)
                    {
                        State.Entry.ExpiryTime = DateTime.Now;
                    }
                }
                UpdateExpires();
                State.EntryModified = true;
            };
        }
コード例 #47
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            _design.ApplyTheme();
            base.OnCreate(savedInstanceState);


            Kp2aLog.Log("FileSelect.OnCreate");
            Kp2aLog.Log("FileSelect:apptask=" + Intent.GetStringExtra("KP2A_APPTASK"));

            if (Intent.Action == Intent.ActionSend)
            {
                AppTask = new SearchUrlTask {
                    UrlToSearchFor = Intent.GetStringExtra(Intent.ExtraText)
                };
            }
            else
            {
                //see PasswordActivity for an explanation
                if (Intent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory))
                {
                    AppTask = new NullTask();
                }
                else
                {
                    AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);
                }
            }


            _dbHelper = App.Kp2a.FileDbHelper;
            SetContentView(Resource.Layout.file_selection);


            if (ShowRecentFiles())
            {
                _recentMode = true;


                FindViewById(Resource.Id.recent_files).Visibility = ViewStates.Visible;
                Android.Util.Log.Debug("KP2A", "Recent files visible");
            }
            else
            {
                FindViewById(Resource.Id.recent_files).Visibility = ViewStates.Invisible;
                Android.Util.Log.Debug("KP2A", "Recent files invisible");
#if NoNet
                ImageView imgView = FindViewById(Resource.Id.splashlogo) as ImageView;
                if (imgView != null)
                {
                    imgView.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.splashlogo_offline));
                }
#endif
            }

            Button openFileButton = (Button)FindViewById(Resource.Id.start_open_file);

            EventHandler openFileButtonClick = (sender, e) =>
            {
                Intent intent = new Intent(this, typeof(SelectStorageLocationActivity));
                intent.PutExtra(FileStorageSelectionActivity.AllowThirdPartyAppGet, true);
                intent.PutExtra(FileStorageSelectionActivity.AllowThirdPartyAppSend, false);
                intent.PutExtra(SelectStorageLocationActivity.ExtraKeyWritableRequirements, (int)SelectStorageLocationActivity.WritableRequirements.WriteDesired);
                intent.PutExtra(FileStorageSetupDefs.ExtraIsForSave, false);
                StartActivityForResult(intent, RequestCodeSelectIoc);
            };
            openFileButton.Click += openFileButtonClick;

            //CREATE NEW
            Button       createNewButton      = (Button)FindViewById(Resource.Id.start_create);
            EventHandler createNewButtonClick = (sender, e) =>
            {
                //ShowFilenameDialog(false, true, true, Android.OS.Environment.ExternalStorageDirectory + GetString(Resource.String.default_file_path), "", Intents.RequestCodeFileBrowseForCreate)
                Intent i = new Intent(this, typeof(CreateDatabaseActivity));
                this.AppTask.ToIntent(i);
                StartActivityForResult(i, 0);
            };
            createNewButton.Click += createNewButtonClick;

            /*//CREATE + IMPORT
             *          Button createImportButton = (Button)FindViewById(Resource.Id.start_create_import);
             *          createImportButton.Click += (object sender, EventArgs e) =>
             *          {
             *                  openButton.Visibility = ViewStates.Gone;
             *                  createButton.Visibility = ViewStates.Visible;
             *                  enterFilenameDetails.Text = GetString(Resource.String.enter_filename_details_create_import);
             *                  enterFilenameDetails.Visibility = enterFilenameDetails.Text == "" ? ViewStates.Gone : ViewStates.Visible;
             *                  // Set the initial value of the filename
             *                  EditText filename = (EditText)FindViewById(Resource.Id.file_filename);
             *                  filename.Text = Android.OS.Environment.ExternalStorageDirectory + GetString(Resource.String.default_file_path);
             *
             *          };*/

            FindViewById <Switch>(Resource.Id.local_backups_switch).CheckedChange += (sender, args) => { FillData(); };

            FillData();

            if (savedInstanceState != null)
            {
                AppTask     = AppTask.CreateFromBundle(savedInstanceState);
                _recentMode = savedInstanceState.GetBoolean(BundleKeyRecentMode, _recentMode);
            }
        }
コード例 #48
0
ファイル: GroupBaseActivity.cs プロジェクト: pythe/wristpass
        public void StopMovingElement()
        {
            try
            {
                MoveElementTask moveElementTask = (MoveElementTask)AppTask;
                IStructureItem elementToMove = App.Kp2a.GetDb().KpDatabase.RootGroup.FindObject(moveElementTask.Uuid, true, null);
                if (elementToMove.ParentGroup != Group)
                    App.Kp2a.GetDb().Dirty.Add(elementToMove.ParentGroup);
            }
            catch (Exception e)
            {
                //don't crash if adding to dirty fails but log the exception:
                Kp2aLog.Log(e.ToString());
            }

            AppTask = new NullTask();
            AppTask.SetupGroupBaseActivityButtons(this);
            GroupView.ListView.InvalidateViews();
            BaseAdapter adapter = (BaseAdapter)ListAdapter;
            adapter.NotifyDataSetChanged();
        }
コード例 #49
0
ファイル: GroupActivity.cs プロジェクト: pythe/wristpass
 public static void Launch(Activity act, AppTask appTask)
 {
     Launch(act, null, appTask);
 }
コード例 #50
0
        protected override void OnCreate(Bundle bundle)
        {
            _design.ApplyTheme();
            base.OnCreate(bundle);


            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetHomeButtonEnabled(true);

            SetContentView(Resource.Layout.create_database);
            _appTask = AppTask.GetTaskInOnCreate(bundle, Intent);

            SetDefaultIoc();

            FindViewById(Resource.Id.keyfile_filename).Visibility = ViewStates.Gone;


            var keyfileCheckbox = FindViewById <CheckBox>(Resource.Id.use_keyfile);

            if (bundle != null)
            {
                _keyfileFilename = bundle.GetString(KeyfilefilenameBundleKey, null);
                if (_keyfileFilename != null)
                {
                    FindViewById <TextView>(Resource.Id.keyfile_filename).Text = FileSelectHelper.ConvertFilenameToIocPath(_keyfileFilename);
                    FindViewById(Resource.Id.keyfile_filename).Visibility      = ViewStates.Visible;
                    keyfileCheckbox.Checked = true;
                }

                if (bundle.GetString(Util.KeyFilename, null) != null)
                {
                    _ioc = new IOConnectionInfo
                    {
                        Path         = bundle.GetString(Util.KeyFilename),
                        UserName     = bundle.GetString(Util.KeyServerusername),
                        Password     = bundle.GetString(Util.KeyServerpassword),
                        CredSaveMode = (IOCredSaveMode)bundle.GetInt(Util.KeyServercredmode),
                    };
                }
            }

            UpdateIocView();

            keyfileCheckbox.CheckedChange += (sender, args) =>
            {
                if (keyfileCheckbox.Checked)
                {
                    if (_restoringInstanceState)
                    {
                        return;
                    }

                    Util.ShowBrowseDialog(this, RequestCodeKeyFile, false, true);
                }
                else
                {
                    FindViewById(Resource.Id.keyfile_filename).Visibility = ViewStates.Gone;
                    _keyfileFilename = null;
                }
            };


            FindViewById(Resource.Id.btn_change_location).Click += (sender, args) =>
            {
                Intent intent = new Intent(this, typeof(FileStorageSelectionActivity));
                StartActivityForResult(intent, RequestCodeDbFilename);
            };

            Button generatePassword = (Button)FindViewById(Resource.Id.generate_button);

            generatePassword.Click += (sender, e) =>
            {
                GeneratePasswordActivity.LaunchWithoutLockCheck(this);
            };

            FindViewById(Resource.Id.btn_create).Click += (sender, evt) =>
            {
                CreateDatabase(Intent.GetBooleanExtra("MakeCurrent", true));
            };

            ImageButton btnTogglePassword = (ImageButton)FindViewById(Resource.Id.toggle_password);

            btnTogglePassword.Click += (sender, e) =>
            {
                _showPassword = !_showPassword;
                MakePasswordMaskedOrVisible();
            };
            Android.Graphics.PorterDuff.Mode mMode = Android.Graphics.PorterDuff.Mode.SrcAtop;
            Android.Graphics.Color           color = new Android.Graphics.Color(224, 224, 224);
            btnTogglePassword.SetColorFilter(color, mMode);
        }
コード例 #51
0
ファイル: EntryEditActivity.cs プロジェクト: pythe/wristpass
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            if (LastNonConfigurationInstance != null)
            {
                //bug in Mono for Android or whatever: after config change the extra fields are wrong
                // -> reload:
                Reload();
                return;
            }

            _appTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            SetContentView(Resource.Layout.entry_edit);
            _closeForReload = false;

            // Likely the app has been killed exit the activity
            if (!App.Kp2a.DatabaseIsUnlocked)
            {
                Finish();
                return;
            }

            if (Intent.GetBooleanExtra(IntentContinueWithEditing, false))
            {
                //property "State" will return the state

            } else
            {
                Database db = App.Kp2a.GetDb();

                App.Kp2a.EntryEditActivityState = new EntryEditActivityState();
                ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
                State.ShowPassword = ! prefs.GetBoolean(GetString(Resource.String.maskpass_key), Resources.GetBoolean(Resource.Boolean.maskpass_default));

                Intent i = Intent;
                String uuidBytes = i.GetStringExtra(KeyEntry);

                PwUuid entryId = PwUuid.Zero;
                if (uuidBytes != null)
                    entryId = new PwUuid(MemUtil.HexStringToByteArray(uuidBytes));

                State.ParentGroup = null;
                if (entryId.Equals(PwUuid.Zero))
                {
                    String groupId = i.GetStringExtra(KeyParent);
                    State.ParentGroup = db.KpDatabase.RootGroup.FindGroup(new PwUuid(MemUtil.HexStringToByteArray(groupId)), true);

                    State.EntryInDatabase = new PwEntry(true, true);
                    State.EntryInDatabase.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                        db.KpDatabase.MemoryProtection.ProtectUserName, db.KpDatabase.DefaultUserName));

                    /*KPDesktop
                 * ProtectedString psAutoGen;
            PwGenerator.Generate(out psAutoGen, Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile,
                null, Program.PwGeneratorPool);
            psAutoGen = psAutoGen.WithProtection(pwDb.MemoryProtection.ProtectPassword);
            pwe.Strings.Set(PwDefs.PasswordField, psAutoGen);

            int nExpireDays = Program.Config.Defaults.NewEntryExpiresInDays;
            if(nExpireDays >= 0)
            {
                pwe.Expires = true;
                pwe.ExpiryTime = DateTime.Now.AddDays(nExpireDays);
            }*/

                    if ((State.ParentGroup.IconId != PwIcon.Folder) && (State.ParentGroup.IconId != PwIcon.FolderOpen) &&
                        (State.ParentGroup.IconId != PwIcon.FolderPackage))
                    {
                        State.EntryInDatabase.IconId = State.ParentGroup.IconId; // Inherit icon from group
                    }
                    State.EntryInDatabase.CustomIconUuid = State.ParentGroup.CustomIconUuid;

                    /*
                 * KPDesktop
            if(strDefaultSeq.Length == 0)
            {
                PwGroup pg = m_pwEntry.ParentGroup;
                if(pg != null)
                {
                    strDefaultSeq = pg.GetAutoTypeSequenceInherited();

                    if(strDefaultSeq.Length == 0)
                    {
                        if(PwDefs.IsTanEntry(m_pwEntry))
                            strDefaultSeq = PwDefs.DefaultAutoTypeSequenceTan;
                        else
                            strDefaultSeq = PwDefs.DefaultAutoTypeSequence;
                    }
                }
            }*/
                    _appTask.PrepareNewEntry(State.EntryInDatabase);
                    State.IsNew = true;
                    State.EntryModified = true;

                } else
                {

                    System.Diagnostics.Debug.Assert(entryId != null);

                    State.EntryInDatabase = db.Entries [entryId];
                    State.IsNew = false;

                }

                State.Entry = State.EntryInDatabase.CloneDeep();

            }

            if (!State.EntryModified)
                SetResult(KeePass.ExitNormal);
            else
                SetResult(KeePass.ExitRefreshTitle);

            FillData();
            View scrollView = FindViewById(Resource.Id.entry_scroll);
            scrollView.ScrollBarStyle = ScrollbarStyles.InsideInset;

            ImageButton iconButton = (ImageButton)FindViewById(Resource.Id.icon_button);

            if (State.SelectedIcon)
            {
                //TODO: custom image
                iconButton.SetImageResource(Icons.IconToResId(State.SelectedIconId));
            }
            iconButton.Click += (sender, evt) => {
                UpdateEntryFromUi(State.Entry);
                IconPickerActivity.Launch(this);
            };

            // Generate password button
            Button generatePassword = (Button)FindViewById(Resource.Id.generate_button);
            generatePassword.Click += (sender, e) => {
                UpdateEntryFromUi(State.Entry);
                GeneratePasswordActivity.Launch(this);
            };

            // Save button
            ActionBar.SetCustomView(Resource.Layout.SaveButton);
            ActionBar.SetDisplayShowCustomEnabled(true);
            ActionBar.SetDisplayShowTitleEnabled(false);
            ActionBar.SetDisplayUseLogoEnabled(false);
            ActionBar.SetDisplayShowHomeEnabled(false);
            ActionBar.SetDisplayOptions(ActionBarDisplayOptions.ShowCustom,
                                        ActionBarDisplayOptions.ShowCustom);
            var save = FindViewById(Resource.Id.entry_save);
            save.Click += (sender, e) =>
            {
                SaveEntry();
            };

            FindViewById(Resource.Id.entry_save_cancel).Click += (sender, args) => Finish();

            // Respect mask password setting
            MakePasswordVisibleOrHidden();

            ImageButton btnTogglePassword = (ImageButton)FindViewById(Resource.Id.toggle_password);
            btnTogglePassword.Click += (sender, e) =>
            {
                State.ShowPassword = !State.ShowPassword;
                MakePasswordVisibleOrHidden();
            };

            Button addButton = (Button) FindViewById(Resource.Id.add_advanced);
            addButton.Visibility = ViewStates.Visible;
            addButton.Click += (sender, e) =>
            {
                LinearLayout container = (LinearLayout) FindViewById(Resource.Id.advanced_container);

                KeyValuePair<string, ProtectedString> pair = new KeyValuePair<string, ProtectedString>("" , new ProtectedString(true, ""));
                LinearLayout ees = CreateExtraStringView(pair);
                container.AddView(ees);

                State.EntryModified = true;

                TextView keyView = (TextView) ees.FindViewById(Resource.Id.title);
                keyView.RequestFocus();
            };
            SetAddExtraStringEnabled();

            ((CheckBox)FindViewById(Resource.Id.entry_expires_checkbox)).CheckedChange += (sender, e) =>
            {
                State.Entry.Expires = e.IsChecked;
                if (e.IsChecked)
                {
                    if (State.Entry.ExpiryTime < DateTime.Now)
                        State.Entry.ExpiryTime = DateTime.Now;
                }
                UpdateExpires();
                State.EntryModified = true;
            };
        }