Esempio n. 1
0
  private void saveConfiguration(FilterListItem filterListItem) {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    String sql = null, contentValuesString = null, title = null;

    if (filterListItem != null && filterListItem instanceof Filter) {
      sql = ((Filter) filterListItem).getSqlQuery();
      ContentValues values = ((Filter) filterListItem).valuesForNewTasks;
      if (values != null)
        contentValuesString = AndroidUtilities.contentValuesToSerializedString(values);
      title = ((Filter) filterListItem).title;
    }

    Preferences.setString(WidgetConfigActivity.PREF_TITLE + mAppWidgetId, title);
    Preferences.setString(WidgetConfigActivity.PREF_SQL + mAppWidgetId, sql);
    Preferences.setString(WidgetConfigActivity.PREF_VALUES + mAppWidgetId, contentValuesString);

    if (filterListItem instanceof FilterWithCustomIntent) {
      String flattenedName =
          ((FilterWithCustomIntent) filterListItem).customTaskList.flattenToString();
      Preferences.setString(WidgetConfigActivity.PREF_CUSTOM_INTENT + mAppWidgetId, flattenedName);
      String flattenedExtras =
          AndroidUtilities.bundleToSerializedString(
              ((FilterWithCustomIntent) filterListItem).customExtras);
      if (flattenedExtras != null)
        Preferences.setString(
            WidgetConfigActivity.PREF_CUSTOM_EXTRAS + mAppWidgetId, flattenedExtras);
    }
  }
Esempio n. 2
0
  /**
   * Migration for existing users to assert that the "hide always" section divider exists in the
   * preferences. Knowing that this section will always be in the constructed list of controls
   * simplifies the logic a bit.
   *
   * @param c
   */
  public static void assertHideUntilSectionExists(Context c, long latestSetVersion) {
    if (latestSetVersion == 0) Preferences.setBoolean(BEAST_MODE_ASSERTED_HIDE_ALWAYS, true);

    if (Preferences.getBoolean(BEAST_MODE_ASSERTED_HIDE_ALWAYS, false)) return;

    String order = Preferences.getStringValue(BEAST_MODE_ORDER_PREF);
    String hideSectionPref = c.getString(R.string.TEA_ctrl_hide_section_pref);
    if (TextUtils.isEmpty(order)) {
      // create preference and stick hide always at the end of it
      String[] items = c.getResources().getStringArray(R.array.TEA_control_sets_prefs);
      StringBuilder builder = new StringBuilder();
      for (String item : items) {
        if (item.equals(hideSectionPref)) continue;
        builder.append(item);
        builder.append(BEAST_MODE_PREF_ITEM_SEPARATOR);
      }

      builder.append(hideSectionPref);
      builder.append(BEAST_MODE_PREF_ITEM_SEPARATOR);
      order = builder.toString();
    } else if (!order.contains(hideSectionPref)) {
      order += (hideSectionPref + BEAST_MODE_PREF_ITEM_SEPARATOR);
    }
    Preferences.setString(BEAST_MODE_ORDER_PREF, order);

    Preferences.setBoolean(BEAST_MODE_ASSERTED_HIDE_ALWAYS, true);
  }
Esempio n. 3
0
  @Override
  public boolean createNew(Task item) {
    if (!item.containsValue(Task.CREATION_DATE))
      item.setValue(Task.CREATION_DATE, DateUtilities.now());
    item.setValue(Task.MODIFICATION_DATE, DateUtilities.now());

    // set up task defaults
    if (!item.containsValue(Task.IMPORTANCE))
      item.setValue(
          Task.IMPORTANCE,
          Preferences.getIntegerFromString(
              R.string.p_default_importance_key, Task.IMPORTANCE_SHOULD_DO));
    if (!item.containsValue(Task.DUE_DATE)) {
      int setting =
          Preferences.getIntegerFromString(R.string.p_default_urgency_key, Task.URGENCY_NONE);
      item.setValue(Task.DUE_DATE, Task.createDueDate(setting, 0));
    }
    createDefaultHideUntil(item);

    setDefaultReminders(item);

    ContentValues values = item.getSetValues();
    boolean result = super.createNew(item);
    if (result) {
      userRetentionMetrics();
      afterSave(item, values);
    }
    return result;
  }
Esempio n. 4
0
 /**
  * Moves sorting prefs to public pref store
  *
  * @param context
  */
 private void upgrade3To3_6(final Context context) {
   SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(context);
   Editor editor = publicPrefs.edit();
   editor.putInt(SortHelper.PREF_SORT_FLAGS, Preferences.getInt(SortHelper.PREF_SORT_FLAGS, 0));
   editor.putInt(SortHelper.PREF_SORT_SORT, Preferences.getInt(SortHelper.PREF_SORT_SORT, 0));
   editor.commit();
 }
Esempio n. 5
0
 private void showTaskCreateHelpPopover() {
   if (!AstridPreferences.canShowPopover()) return;
   if (!Preferences.getBoolean(R.string.p_showed_add_task_help, false)) {
     Preferences.setBoolean(R.string.p_showed_add_task_help, true);
     HelpInfoPopover.showPopover(
         getActivity(), quickAddBar.getQuickAddBox(), R.string.help_popover_add_task, null);
   }
 }
Esempio n. 6
0
 /** @return get user id */
 public static String userId() {
   try {
     String value = Preferences.getStringValue(PREF_USER_ID);
     if (value == null) {
       return Long.toString(Preferences.getLong(PREF_USER_ID, -2L));
     }
     return value;
   } catch (Exception e) {
     return Long.toString(Preferences.getLong(PREF_USER_ID, -2L));
   }
 }
Esempio n. 7
0
  /**
   * Perform upgrade from one version to the next. Needs to be called on the UI thread so it can
   * display a progress bar and then show users a change log.
   *
   * @param from
   * @param to
   */
  public void performUpgrade(final Context context, final int from) {
    if (from == 135) AddOnService.recordOem();

    if (from > 0 && from < V3_8_2) {
      if (Preferences.getBoolean(R.string.p_transparent_deprecated, false))
        Preferences.setString(R.string.p_theme, "transparent"); // $NON-NLS-1$
      else Preferences.setString(R.string.p_theme, "black"); // $NON-NLS-1$
    }

    if (from <= V3_9_1_1) {
      actFmPreferenceService.clearLastSyncDate();
    }

    // long running tasks: pop up a progress dialog
    final ProgressDialog dialog;
    if (from < V4_0_6 && context instanceof Activity)
      dialog = DialogUtilities.progressDialog(context, context.getString(R.string.DLG_upgrading));
    else dialog = null;

    final String lastSetVersionName = AstridPreferences.getCurrentVersionName();

    Preferences.setInt(AstridPreferences.P_UPGRADE_FROM, from);

    new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  // NOTE: This line should be uncommented whenever any new version requires a data
                  // migration
                  // TasksXmlExporter.exportTasks(context,
                  // TasksXmlExporter.ExportType.EXPORT_TYPE_ON_UPGRADE, null, null,
                  // lastSetVersionName);

                  if (from < V3_0_0) new Astrid2To3UpgradeHelper().upgrade2To3(context, from);

                  if (from < V3_1_0) new Astrid2To3UpgradeHelper().upgrade3To3_1(context, from);

                  if (from < V3_8_3_1) new TagCaseMigrator().performTagCaseMigration(context);

                  if (from < V3_8_4 && Preferences.getBoolean(R.string.p_showNotes, false))
                    taskService.clearDetails(Task.NOTES.neq("")); // $NON-NLS-1$

                  if (from < V4_0_6) new DueDateTimeMigrator().migrateDueTimes();

                } finally {
                  DialogUtilities.dismissDialog((Activity) context, dialog);
                  context.sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH));
                }
              }
            })
        .start();
  }
Esempio n. 8
0
 private static void populateUser() {
   try {
     user.put("name", Preferences.getStringValue(PREF_NAME));
     user.put("first_name", Preferences.getStringValue(PREF_FIRST_NAME));
     user.put("last_name", Preferences.getStringValue(PREF_LAST_NAME));
     user.put("premium", isPremiumUser());
     user.put("email", Preferences.getStringValue(PREF_EMAIL));
     user.put("picture", Preferences.getStringValue(PREF_PICTURE));
     user.put("id", ActFmPreferenceService.userId());
   } catch (JSONException e) {
     throw new RuntimeException(e);
   }
 }
Esempio n. 9
0
  @SuppressWarnings("nls")
  private void refreshMembersPage() {
    tagName.setText(tagData.getValue(TagData.NAME));
    picture.setUrl(tagData.getValue(TagData.PICTURE));

    TextView ownerLabel = (TextView) findViewById(R.id.tag_owner);
    try {
      if (tagData.getFlag(TagData.FLAGS, TagData.FLAG_EMERGENT)) {
        ownerLabel.setText(String.format("<%s>", getString(R.string.actfm_TVA_tag_owner_none)));
      } else if (tagData.getValue(TagData.USER_ID) == 0) {
        ownerLabel.setText(Preferences.getStringValue(ActFmPreferenceService.PREF_NAME));
      } else {
        JSONObject owner = new JSONObject(tagData.getValue(TagData.USER));
        ownerLabel.setText(owner.getString("name"));
      }
    } catch (JSONException e) {
      Log.e("tag-view-activity", "json error refresh owner", e);
      ownerLabel.setText("<error>");
      System.err.println(tagData.getValue(TagData.USER));
    }

    tagMembers.removeAllViews();
    String peopleJson = tagData.getValue(TagData.MEMBERS);
    if (!TextUtils.isEmpty(peopleJson)) {
      try {
        JSONArray people = new JSONArray(peopleJson);
        for (int i = 0; i < people.length(); i++) {
          JSONObject person = people.getJSONObject(i);
          TextView textView = null;

          if (person.has("id") && person.getLong("id") == ActFmPreferenceService.userId())
            textView =
                tagMembers.addPerson(Preferences.getStringValue(ActFmPreferenceService.PREF_NAME));
          else if (!TextUtils.isEmpty(person.optString("name")))
            textView = tagMembers.addPerson(person.getString("name"));
          else if (!TextUtils.isEmpty(person.optString("email")))
            textView = tagMembers.addPerson(person.getString("email"));

          if (textView != null) {
            textView.setTag(person);
            textView.setEnabled(false);
          }
        }
      } catch (JSONException e) {
        System.err.println(peopleJson);
        Log.e("tag-view-activity", "json error refresh members", e);
      }
    }

    tagMembers.addPerson(""); // $NON-NLS-1$
  }
Esempio n. 10
0
 @Override
 public void onReceive(Context context, Intent intent) {
   lastSyncFromNetworkChange = Preferences.getLong(PREF_LAST_SYNC_FROM_NETWORK_CHANGE, 0L);
   if (DateUtilities.now() - lastSyncFromNetworkChange > DateUtilities.ONE_MINUTE * 10) {
     NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
     if (info != null
         && NetworkInfo.State.CONNECTED.equals(info.getState())
         && PluginServices.getActFmPreferenceService().isLoggedIn()) {
       ActFmSyncThread syncThread = ActFmSyncThread.getInstance();
       syncThread.repopulateQueueFromOutstandingTables();
       Preferences.setLong(PREF_LAST_SYNC_FROM_NETWORK_CHANGE, DateUtilities.now());
     }
   }
 }
Esempio n. 11
0
  @Override
  public boolean persist(Metadata item) {
    if (!item.containsValue(Metadata.CREATION_DATE))
      item.setValue(Metadata.CREATION_DATE, DateUtilities.now());

    boolean state = super.persist(item);
    if (Preferences.getBoolean(AstridPreferences.P_FIRST_LIST, true)) {
      if (state && item.getValue(Metadata.KEY).equals(TagService.KEY)) {
        StatisticsService.reportEvent(StatisticsConstants.USER_FIRST_LIST);
        Preferences.setBoolean(AstridPreferences.P_FIRST_LIST, false);
      }
    }
    Astrid2TaskProvider.notifyDatabaseModification();
    return state;
  }
Esempio n. 12
0
    private Filter getFilter(int widgetId) {
      // base our filter off the inbox filter, replace stuff if we have it
      Filter filter = CoreFilterExposer.buildInboxFilter(getResources());
      String sql = Preferences.getStringValue(WidgetConfigActivity.PREF_SQL + widgetId);
      if (sql != null) filter.sqlQuery = sql;
      String title = Preferences.getStringValue(WidgetConfigActivity.PREF_TITLE + widgetId);
      if (title != null) filter.title = title;
      String contentValues =
          Preferences.getStringValue(WidgetConfigActivity.PREF_VALUES + widgetId);
      if (contentValues != null)
        filter.valuesForNewTasks =
            AndroidUtilities.contentValuesFromSerializedString(contentValues);

      return filter;
    }
Esempio n. 13
0
 @Override
 public boolean shouldShowToast() {
   if (Preferences.getBoolean(AstridPreferences.P_FIRST_TASK, true)) {
     return false;
   }
   return super.shouldShowToast();
 }
Esempio n. 14
0
 public static void createDefaultHideUntil(Task item) {
   if (!item.containsValue(Task.HIDE_UNTIL)) {
     int setting =
         Preferences.getIntegerFromString(R.string.p_default_hideUntil_key, Task.HIDE_UNTIL_NONE);
     item.setValue(Task.HIDE_UNTIL, item.createHideUntil(setting, 0));
   }
 }
Esempio n. 15
0
 private static void accept(Activity activity) {
   if (activity instanceof EulaCallback) {
     ((EulaCallback) activity).eulaAccepted();
   }
   Preferences.setBoolean(PREFERENCE_EULA_ACCEPTED, true);
   StatisticsService.reportEvent(StatisticsConstants.EULA_ACCEPTED);
 }
Esempio n. 16
0
  /**
   * Invalidates and then revalidates the auth token for the currently logged in user Shouldn't be
   * called from the main thread--will block on network calls
   *
   * @return valid token on success, null on failure
   */
  public static synchronized String validateAuthToken(Context c, String token)
      throws GoogleTasksException {
    GoogleAccountManager accountManager = new GoogleAccountManager(ContextManager.getContext());

    if (testToken(token)) {
      return token;
    }

    // If fail, token may have expired -- get a new one and return that
    String accountName = Preferences.getStringValue(GtasksPreferenceService.PREF_USER_NAME);
    Account a = accountManager.getAccountByName(accountName);
    if (a == null) {
      throw new GoogleTasksException(
          c.getString(R.string.gtasks_error_accountNotFound, accountName), "account-not-found");
    }

    for (int i = 0; i < REVALIDATION_TRIES; i++) {
      accountManager.invalidateAuthToken(token);

      // try with notify-auth-failure = false
      AccountManagerFuture<Bundle> future =
          accountManager.manager.getAuthToken(a, GtasksInvoker.AUTH_TOKEN_TYPE, false, null, null);
      token = getTokenFromFuture(c, future);

      if (TOKEN_INTENT_RECEIVED.equals(token)) {
        return null;
      } else if (token != null && testToken(token)) {
        return token;
      }
    }

    throw new GoogleTasksException(
        c.getString(R.string.gtasks_error_authRefresh), "auth-token-refresh");
  }
Esempio n. 17
0
  private void write(GtasksTaskContainer task) throws IOException {
    //  merge astrid dates with google dates
    if (!task.task.isSaved() && actFmPreferenceService.isLoggedIn()) titleMatchWithActFm(task.task);

    if (task.task.isSaved()) {
      Task local =
          PluginServices.getTaskService()
              .fetchById(task.task.getId(), Task.DUE_DATE, Task.COMPLETION_DATE);
      if (local == null) {
        task.task.clearValue(Task.ID);
      } else {
        mergeDates(task.task, local);
        if (task.task.isCompleted() && !local.isCompleted())
          StatisticsService.reportEvent(StatisticsConstants.GTASKS_TASK_COMPLETED);
      }
    } else { // Set default importance and reminders for remotely created tasks
      task.task.setValue(
          Task.IMPORTANCE,
          Preferences.getIntegerFromString(
              R.string.p_default_importance_key, Task.IMPORTANCE_SHOULD_DO));
      TaskDao.setDefaultReminders(task.task);
    }
    if (!TextUtils.isEmpty(task.task.getValue(Task.TITLE))) {
      task.task.putTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC, true);
      gtasksMetadataService.saveTaskAndMetadata(task);
    }
  }
Esempio n. 18
0
  /** @param resource if null, updates all resources */
  @Override
  public void updatePreferences(Preference preference, Object value) {
    Resources r = getResources();

    if (r.getString(R.string.p_rmd_quietStart).equals(preference.getKey())) {
      int index =
          AndroidUtilities.indexOf(
              r.getStringArray(R.array.EPr_quiet_hours_start_values), (String) value);
      Preference endPreference = findPreference(getString(R.string.p_rmd_quietEnd));
      if (index <= 0) {
        preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_desc_none));
        endPreference.setEnabled(false);
      } else {
        String setting = r.getStringArray(R.array.EPr_quiet_hours_start)[index];
        preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_start_desc, setting));
        endPreference.setEnabled(true);
      }
    } else if (r.getString(R.string.p_rmd_quietEnd).equals(preference.getKey())) {
      int index =
          AndroidUtilities.indexOf(
              r.getStringArray(R.array.EPr_quiet_hours_end_values), (String) value);
      int quietHoursStart = Preferences.getIntegerFromString(R.string.p_rmd_quietStart, -1);
      if (index == -1 || quietHoursStart == -1)
        preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_desc_none));
      else {
        String setting = r.getStringArray(R.array.EPr_quiet_hours_end)[index];
        preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_end_desc, setting));
      }
    } else if (r.getString(R.string.p_rmd_time).equals(preference.getKey())) {
      int index =
          AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_rmd_time_values), (String) value);
      String setting = r.getStringArray(R.array.EPr_rmd_time)[index];
      preference.setSummary(r.getString(R.string.rmd_EPr_rmd_time_desc, setting));
    } else if (r.getString(R.string.p_rmd_ringtone).equals(preference.getKey())) {
      if (value == null
          || "content://settings/system/notification_sound".equals(value)) // $NON-NLS-1$
      preference.setSummary(r.getString(R.string.rmd_EPr_ringtone_desc_default));
      else if ("".equals(value)) // $NON-NLS-1$
      preference.setSummary(r.getString(R.string.rmd_EPr_ringtone_desc_silent));
      else preference.setSummary(r.getString(R.string.rmd_EPr_ringtone_desc_custom));
    } else if (r.getString(R.string.p_rmd_persistent).equals(preference.getKey())) {
      if ((Boolean) value)
        preference.setSummary(r.getString(R.string.rmd_EPr_persistent_desc_true));
      else preference.setSummary(r.getString(R.string.rmd_EPr_persistent_desc_false));
    } else if (r.getString(R.string.p_rmd_maxvolume).equals(preference.getKey())) {
      if ((Boolean) value)
        preference.setSummary(r.getString(R.string.rmd_EPr_multiple_maxvolume_desc_true));
      else preference.setSummary(r.getString(R.string.rmd_EPr_multiple_maxvolume_desc_false));
    } else if (r.getString(R.string.p_rmd_vibrate).equals(preference.getKey())) {
      if ((Boolean) value) preference.setSummary(r.getString(R.string.rmd_EPr_vibrate_desc_true));
      else preference.setSummary(r.getString(R.string.rmd_EPr_vibrate_desc_false));
    } else if (r.getString(R.string.p_rmd_nagging).equals(preference.getKey())) {
      if ((Boolean) value) preference.setSummary(r.getString(R.string.rmd_EPr_nagging_desc_true));
      else preference.setSummary(r.getString(R.string.rmd_EPr_nagging_desc_false));
    } else if (r.getString(R.string.p_rmd_snooze_dialog).equals(preference.getKey())) {
      if (value == null || ((Boolean) value) == true)
        preference.setSummary(r.getString(R.string.rmd_EPr_snooze_dialog_desc_true));
      else preference.setSummary(r.getString(R.string.rmd_EPr_snooze_dialog_desc_false));
    }
  }
Esempio n. 19
0
 /**
  * Sets default reminders for the given task if reminders are not set
  *
  * @param item
  */
 public static void setDefaultReminders(Task item) {
   if (!item.containsValue(Task.REMINDER_PERIOD)) {
     item.setValue(
         Task.REMINDER_PERIOD,
         DateUtilities.ONE_HOUR
             * Preferences.getIntegerFromString(R.string.p_rmd_default_random_hours, 0));
   }
   if (!item.containsValue(Task.REMINDER_FLAGS)) {
     int reminder_flags =
         Preferences.getIntegerFromString(
                 R.string.p_default_reminders_key,
                 Task.NOTIFY_AT_DEADLINE | Task.NOTIFY_AFTER_DEADLINE)
             | Preferences.getIntegerFromString(R.string.p_default_reminders_mode_key, 0);
     item.setValue(Task.REMINDER_FLAGS, reminder_flags);
   }
 }
Esempio n. 20
0
  /**
   * Refresh the content of the responsibleSelector with the given userlist.
   *
   * @param newUsers the new userlist to show in the responsibleSelector
   * @param responsibleId the id of the responsible user to set in the spinner
   */
  private void refreshResponsibleSpinner(ArrayList<ProducteevUser> newUsers, long responsibleId) {
    // Fill the responsible-spinner and set the current responsible
    this.users = (newUsers == null ? new ArrayList<ProducteevUser>() : newUsers);

    ArrayAdapter<ProducteevUser> usersAdapter =
        new ArrayAdapter<ProducteevUser>(
            activity, android.R.layout.simple_spinner_item, this.users);
    usersAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    responsibleSelector.setAdapter(usersAdapter);

    int visibility = newUsers == null ? View.GONE : View.VISIBLE;

    view.findViewById(R.id.producteev_TEA_task_assign_label).setVisibility(visibility);
    responsibleSelector.setVisibility(visibility);

    int responsibleSpinnerIndex = 0;

    for (int i = 0; i < this.users.size(); i++) {
      if (this.users.get(i).getId() == responsibleId
          || (responsibleId == -1
              && this.users.get(i).getId()
                  == Preferences.getLong(ProducteevUtilities.PREF_USER_ID, -1))) {
        responsibleSpinnerIndex = i;
        break;
      }
    }
    responsibleSelector.setSelection(responsibleSpinnerIndex);
  }
Esempio n. 21
0
 public void showTaskEditHelpPopover() {
   if (!AstridPreferences.canShowPopover()) return;
   if (!Preferences.getBoolean(R.string.p_showed_tap_task_help, false)) {
     quickAddBar.hideKeyboard();
     getListView()
         .postDelayed(
             new Runnable() {
               public void run() {
                 try {
                   if (taskAdapter != null && taskAdapter.getCount() > 0) {
                     final View view = getListView().getChildAt(getListView().getChildCount() - 1);
                     if (view != null) {
                       Activity activity = getActivity();
                       if (activity != null) {
                         HelpInfoPopover.showPopover(
                             getActivity(), view, R.string.help_popover_tap_task, null);
                         Preferences.setBoolean(R.string.p_showed_tap_task_help, true);
                       }
                     }
                   }
                 } catch (IllegalStateException e) {
                   // Whoops, view is gone. Try again later
                 }
               }
             },
             1000L);
   }
 }
Esempio n. 22
0
 @Override
 public void signOut() {
   gtasksPreferenceService.clearLastSyncDate();
   gtasksPreferenceService.setToken(null);
   Preferences.setString(GtasksPreferenceService.PREF_USER_NAME, null);
   gtasksMetadataService.clearMetadata();
 }
 @SuppressWarnings("nls")
 private static synchronized JSONObject thisUser() {
   if (user == null) {
     user = new JSONObject();
     try {
       user.put("name", Preferences.getStringValue(PREF_NAME));
       user.put("email", Preferences.getStringValue(PREF_EMAIL));
       user.put("picture", Preferences.getStringValue(PREF_PICTURE));
       user.put("id", Preferences.getLong(PREF_USER_ID, 0));
       System.err.println(user);
     } catch (JSONException e) {
       throw new RuntimeException(e);
     }
   }
   return user;
 }
Esempio n. 24
0
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // We have a menu item to show in action bar.
    setHasOptionsMenu(true);
    syncActionHelper = new SyncActionHelper(getActivity(), this);
    setUpUiComponents();
    initializeData();
    setupQuickAddBar();

    Fragment filterlistFrame =
        getFragmentManager().findFragmentByTag(FilterListFragment.TAG_FILTERLIST_FRAGMENT);
    mDualFragments = (filterlistFrame != null) && filterlistFrame.isInLayout();

    if (mDualFragments) {
      // In dual-pane mode, the list view highlights the selected item.
      getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
      getListView().setItemsCanFocus(false);
    }

    if (Preferences.getInt(AstridPreferences.P_UPGRADE_FROM, -1) > -1)
      upgradeService.showChangeLog(
          getActivity(), Preferences.getInt(AstridPreferences.P_UPGRADE_FROM, -1));

    getActivity()
        .runOnUiThread(
            new Runnable() {
              public void run() {
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
              }
            });

    getListView()
        .setOnItemClickListener(
            new OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TodorooCursor<Task> cursor = (TodorooCursor<Task>) taskAdapter.getItem(position);
                Task task = new Task(cursor);
                if (task.isDeleted()) return;

                if (task.isEditable()) {
                  onTaskListItemClicked(id);
                }
              }
            });
  }
Esempio n. 25
0
  @Override
  public boolean persist(Metadata item) {
    if (!item.containsValue(Metadata.CREATION_DATE)) {
      item.setValue(Metadata.CREATION_DATE, DateUtilities.now());
    }

    boolean state = super.persist(item);
    if (Preferences.getBoolean(AstridPreferences.P_FIRST_LIST, true)) {
      if (state
          && item.containsNonNullValue(Metadata.KEY)
          && item.getValue(Metadata.KEY).equals(TaskToTagMetadata.KEY)) {
        Preferences.setBoolean(AstridPreferences.P_FIRST_LIST, false);
      }
    }
    Astrid2TaskProvider.notifyDatabaseModification();
    return state;
  }
Esempio n. 26
0
 private void showListsHelp() {
   if (!AstridPreferences.canShowPopover()) return;
   if (!Preferences.getBoolean(R.string.p_showed_lists_help, false)) {
     AstridActivity activity = (AstridActivity) getActivity();
     if (activity != null) {
       if (AstridPreferences.useTabletLayout(activity)) {
         FilterListFragment flf = activity.getFilterListFragment();
         if (flf != null) flf.showAddListPopover();
       } else {
         ActionBar ab = activity.getSupportActionBar();
         View anchor = ab.getCustomView().findViewById(R.id.lists_nav);
         HelpInfoPopover.showPopover(activity, anchor, R.string.help_popover_switch_lists, null);
       }
       Preferences.setBoolean(R.string.p_showed_lists_help, true);
     }
   }
 }
Esempio n. 27
0
  private Filter[] buildSavedFilters(Context context, Resources r) {
    int themeFlags = ThemeService.getFilterThemeFlags();

    StoreObjectDao dao = PluginServices.getStoreObjectDao();
    TodorooCursor<StoreObject> cursor =
        dao.query(
            Query.select(StoreObject.PROPERTIES)
                .where(StoreObject.TYPE.eq(SavedFilter.TYPE))
                .orderBy(Order.asc(SavedFilter.NAME)));
    try {
      ArrayList<Filter> list = new ArrayList<>();

      // stock filters
      if (Preferences.getBoolean(R.string.p_show_recently_modified_filter, true)) {
        Filter recent =
            new Filter(
                r.getString(R.string.BFE_Recent),
                r.getString(R.string.BFE_Recent),
                new QueryTemplate()
                    .where(TaskCriteria.ownedByMe())
                    .orderBy(Order.desc(Task.MODIFICATION_DATE))
                    .limit(15),
                null);
        recent.listingIcon =
            ((BitmapDrawable)
                    r.getDrawable(ThemeService.getDrawable(R.drawable.filter_pencil, themeFlags)))
                .getBitmap();

        list.add(recent);
      }

      if (cursor != null) {
        StoreObject savedFilter = new StoreObject();
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
          savedFilter.readFromCursor(cursor);
          Filter f = SavedFilter.load(savedFilter);

          Intent deleteIntent = new Intent(context, DeleteActivity.class);
          deleteIntent.putExtra(TOKEN_FILTER_ID, savedFilter.getId());
          deleteIntent.putExtra(TOKEN_FILTER_NAME, f.title);
          f.contextMenuLabels = new String[] {context.getString(R.string.BFE_Saved_delete)};
          f.contextMenuIntents = new Intent[] {deleteIntent};
          f.listingIcon =
              ((BitmapDrawable)
                      r.getDrawable(
                          ThemeService.getDrawable(R.drawable.filter_sliders, themeFlags)))
                  .getBitmap();
          list.add(f);
        }
      }

      return list.toArray(new Filter[list.size()]);
    } finally {
      if (cursor != null) {
        cursor.close();
      }
    }
  }
Esempio n. 28
0
  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    synchronized (this) {
      if (dataLoaded) return;
      dataLoaded = true;
    }

    String tag = getIntent().getStringExtra(EXTRA_TAG_NAME);
    long remoteId = getIntent().getLongExtra(EXTRA_TAG_REMOTE_ID, 0);

    if (tag == null && remoteId == 0) return;

    TodorooCursor<TagData> cursor =
        tagDataService.query(
            Query.select(TagData.PROPERTIES)
                .where(
                    Criterion.or(
                        TagData.NAME.eq(tag),
                        Criterion.and(TagData.REMOTE_ID.gt(0), TagData.REMOTE_ID.eq(remoteId)))));
    try {
      tagData = new TagData();
      if (cursor.getCount() == 0) {
        tagData.setValue(TagData.NAME, tag);
        tagData.setValue(TagData.REMOTE_ID, remoteId);
        tagDataService.save(tagData);
      } else {
        cursor.moveToFirst();
        tagData.readFromCursor(cursor);
      }
    } finally {
      cursor.close();
    }

    String fetchKey = LAST_FETCH_KEY + tagData.getId();
    long lastFetchDate = Preferences.getLong(fetchKey, 0);
    if (DateUtilities.now() > lastFetchDate + 300000L) {
      refreshData(false, false);
      Preferences.setLong(fetchKey, DateUtilities.now());
    }

    setUpUpdateList();
    setUpMemberPage();
  }
Esempio n. 29
0
 private ActFmSyncThread(List<ClientToServerMessage<?>> messageQueue, Object syncMonitor) {
   DependencyInjectionService.getInstance().inject(this);
   this.pendingMessages = messageQueue;
   this.pendingCallbacks =
       Collections.synchronizedMap(new HashMap<ClientToServerMessage<?>, SyncMessageCallback>());
   this.monitor = syncMonitor;
   this.syncMigration = Preferences.getBoolean(AstridNewSyncMigrator.PREF_SYNC_MIGRATION, false);
   this.notificationManager = new AndroidNotificationManager(ContextManager.getContext());
 }
Esempio n. 30
0
  protected void addMenuItems(Menu menu, Activity activity) {
    boolean isTablet = AstridPreferences.useTabletLayout(activity);
    TaskListActivity tla = null;
    if (activity instanceof TaskListActivity) {
      tla = (TaskListActivity) activity;
      tla.getMainMenuPopover().clear();
    }
    // --- sync
    if (tla == null || tla.getTaskEditFragment() == null)
      addSyncRefreshMenuItem(menu, isTablet ? ThemeService.FLAG_INVERT : 0);

    // --- sort
    if (allowResorting()) {
      addMenuItem(
          menu,
          R.string.TLA_menu_sort,
          ThemeService.getDrawable(
              R.drawable.icn_menu_sort_by_size, isTablet ? ThemeService.FLAG_FORCE_DARK : 0),
          MENU_SORT_ID,
          false);
    }

    // --- new filter
    if (Preferences.getBoolean(R.string.p_use_filters, true))
      addMenuItem(
          menu,
          R.string.FLA_new_filter,
          ThemeService.getDrawable(
              R.drawable.icn_menu_filters, isTablet ? ThemeService.FLAG_FORCE_DARK : 0),
          MENU_NEW_FILTER_ID,
          false);

    // --- addons
    if (Constants.MARKET_STRATEGY.showAddonMenu())
      addMenuItem(
          menu,
          R.string.TLA_menu_addons,
          ThemeService.getDrawable(
              R.drawable.icn_menu_plugins, isTablet ? ThemeService.FLAG_FORCE_DARK : 0),
          MENU_ADDONS_ID,
          false);

    // ask about plug-ins
    Intent queryIntent = new Intent(AstridApiConstants.ACTION_TASK_LIST_MENU);

    PackageManager pm = getActivity().getPackageManager();
    List<ResolveInfo> resolveInfoList = pm.queryIntentActivities(queryIntent, 0);
    int length = resolveInfoList.size();
    for (int i = 0; i < length; i++) {
      ResolveInfo resolveInfo = resolveInfoList.get(i);
      Intent intent = new Intent(AstridApiConstants.ACTION_TASK_LIST_MENU);
      intent.setClassName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name);
      addMenuItem(
          menu, resolveInfo.loadLabel(pm), resolveInfo.loadIcon(pm), intent, MENU_ADDON_INTENT_ID);
    }
  }