Пример #1
0
  @Override
  public void onSortSelected(boolean always, int flags, int sort) {
    boolean manualSettingChanged =
        SortHelper.isManualSort(sortFlags) != SortHelper.isManualSort(flags);

    sortFlags = flags;
    sortSort = sort;

    if (always) {
      SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(ContextManager.getContext());
      if (publicPrefs != null) {
        Editor editor = publicPrefs.edit();
        if (editor != null) {
          editor.putInt(SortHelper.PREF_SORT_FLAGS, flags);
          editor.putInt(SortHelper.PREF_SORT_SORT, sort);
          editor.commit();
          TasksWidget.updateWidgets(ContextManager.getContext());
        }
      }
    }

    try {
      if (manualSettingChanged) toggleDragDrop(SortHelper.isManualSort(sortFlags));
      else setUpTaskList();
    } catch (IllegalStateException e) {
      // TODO: Fragment got detached somehow (rare)
    }
  }
Пример #2
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);
   }
 }
Пример #3
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();
 }
Пример #4
0
  @SuppressWarnings("nls")
  private void doTasksExport(String output) throws IOException {
    File xmlFile = new File(output);
    xmlFile.createNewFile();
    FileOutputStream fos = new FileOutputStream(xmlFile);
    xml = Xml.newSerializer();
    xml.setOutput(fos, BackupConstants.XML_ENCODING);

    xml.startDocument(null, null);
    xml.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

    xml.startTag(null, BackupConstants.ASTRID_TAG);
    xml.attribute(
        null,
        BackupConstants.ASTRID_ATTR_VERSION,
        Integer.toString(AstridPreferences.getCurrentVersion()));
    xml.attribute(null, BackupConstants.ASTRID_ATTR_FORMAT, Integer.toString(FORMAT));

    serializeTasks();

    xml.endTag(null, BackupConstants.ASTRID_TAG);
    xml.endDocument();
    xml.flush();
    fos.close();
  }
Пример #5
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);
     }
   }
 }
Пример #6
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);
   }
 }
Пример #7
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);
    }
  }
Пример #8
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();
  }
Пример #9
0
  protected void setUpUiComponents() {
    // set listener for quick-changing task priority
    getListView()
        .setOnKeyListener(
            new OnKeyListener() {
              @Override
              public boolean onKey(View view, int keyCode, KeyEvent event) {
                if (event.getAction() != KeyEvent.ACTION_UP || view == null) return false;

                boolean filterOn = getListView().isTextFilterEnabled();
                View selected = getListView().getSelectedView();

                // hot-key to set task priority - 1-4 or ALT + Q-R
                if (!filterOn
                    && event.getUnicodeChar() >= '1'
                    && event.getUnicodeChar() <= '4'
                    && selected != null) {
                  int importance = event.getNumber() - '1';
                  Task task = ((ViewHolder) selected.getTag()).task;
                  task.setValue(Task.IMPORTANCE, importance);
                  taskService.save(task);
                  taskAdapter.setFieldContentsAndVisibility(selected);
                }
                // filter
                else if (!filterOn && event.getUnicodeChar() != 0) {
                  getListView().setTextFilterEnabled(true);
                  getListView().setFilterText(Character.toString((char) event.getUnicodeChar()));
                }
                // turn off filter if nothing is selected
                else if (filterOn && TextUtils.isEmpty(getListView().getTextFilter())) {
                  getListView().setTextFilterEnabled(false);
                }

                return false;
              }
            });

    SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(getActivity());
    sortFlags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0);
    sortSort = publicPrefs.getInt(SortHelper.PREF_SORT_SORT, 0);
    sortFlags = SortHelper.setManualSort(sortFlags, isDraggable());

    getView().findViewById(R.id.progressBar).setVisibility(View.GONE);
  }
Пример #10
0
 /** If database exists, no tasks but metadata, and a backup file exists, restore it */
 private void databaseRestoreIfEmpty(Context context) {
   try {
     if (AstridPreferences.getCurrentVersion() >= UpgradeService.V3_0_0
         && !context.getDatabasePath(database.getName()).exists()) {
       // we didn't have a database! restore latest file
       File directory = BackupConstants.defaultExportDirectory();
       if (!directory.exists()) {
         return;
       }
       File[] children = directory.listFiles();
       AndroidUtilities.sortFilesByDateDesc(children);
       if (children.length > 0) {
         TasksXmlImporter.importTasks(context, children[0].getAbsolutePath(), null);
       }
     }
   } catch (Exception e) {
     Log.w("astrid-database-restore", e); // $NON-NLS-1$
   }
 }
Пример #11
0
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (quickAddBar.onActivityResult(requestCode, resultCode, data)) return;

    if (requestCode == ACTIVITY_SETTINGS) {
      if (resultCode == EditPreferences.RESULT_CODE_THEME_CHANGED
          || resultCode == EditPreferences.RESULT_CODE_PERFORMANCE_PREF_CHANGED) {
        getActivity().finish();
        getActivity().startActivity(getActivity().getIntent());
        TasksWidget.updateWidgets(getActivity());
        return;
      } else if (resultCode == SyncProviderPreferences.RESULT_CODE_SYNCHRONIZE) {
        Preferences.setLong(
            SyncActionHelper.PREF_LAST_AUTO_SYNC, 0); // Forces autosync to occur after login
      }
    }

    super.onActivityResult(requestCode, resultCode, data);

    if (!Preferences.getBoolean(R.string.p_showed_add_task_help, false)) {
      if (!AstridPreferences.canShowPopover()) return;
      quickAddBar
          .getQuickAddBox()
          .postDelayed(
              new Runnable() {
                @Override
                public void run() {
                  Activity activity = getActivity();
                  if (activity != null) {
                    HelpInfoPopover.showPopover(
                        getActivity(),
                        quickAddBar.getQuickAddBox(),
                        R.string.help_popover_add_task,
                        null);
                    Preferences.setBoolean(R.string.p_showed_add_task_help, true);
                  }
                }
              },
              1000);
    }
  }
Пример #12
0
  private String getQuery(Context context) {
    if (SubtasksHelper.isTagFilter(filter)) {
      ((FilterWithCustomIntent) filter).customTaskList =
          new ComponentName(
              context,
              TagViewFragment.class); // In case legacy widget was created with subtasks fragment
    }

    SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(context);
    int flags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0);
    flags |= SortHelper.FLAG_SHOW_RECENTLY_COMPLETED;
    int sort = publicPrefs.getInt(SortHelper.PREF_SORT_SORT, 0);
    if (sort == 0) {
      sort = SortHelper.SORT_WIDGET;
    }

    String query =
        SortHelper.adjustQueryForFlagsAndSort(filter.getSqlQuery(), flags, sort)
            .replaceAll("LIMIT \\d+", "");

    String tagName = Preferences.getStringValue(WidgetConfigActivity.PREF_TITLE + widgetId);

    return SubtasksHelper.applySubtasksToWidgetFilter(filter, query, tagName, 0);
  }
Пример #13
0
    @SuppressWarnings("nls")
    public RemoteViews buildUpdate(Context context, int widgetId) {
      DependencyInjectionService.getInstance().inject(this);

      RemoteViews views = null;

      views = new RemoteViews(context.getPackageName(), R.layout.widget_initialized);

      int[] textIDs = TEXT_IDS;
      int[] separatorIDs = SEPARATOR_IDS;
      int numberOfTasks = 5;

      for (int i = 0; i < textIDs.length; i++) views.setTextViewText(textIDs[i], "");

      TodorooCursor<Task> cursor = null;
      Filter filter = null;
      try {
        filter = getFilter(widgetId);
        views.setTextViewText(R.id.widget_title, filter.title);

        SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(this);
        int flags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0);
        int sort = publicPrefs.getInt(SortHelper.PREF_SORT_SORT, 0);
        String query =
            SortHelper.adjustQueryForFlagsAndSort(filter.sqlQuery, flags, sort)
                    .replaceAll("LIMIT \\d+", "")
                + " LIMIT "
                + numberOfTasks;

        database.openForReading();
        cursor =
            taskService.fetchFiltered(
                query, null, Task.ID, Task.TITLE, Task.DUE_DATE, Task.COMPLETION_DATE);
        Task task = new Task();
        for (int i = 0; i < cursor.getCount() && i < numberOfTasks; i++) {
          cursor.moveToPosition(i);
          task.readFromCursor(cursor);

          String textContent = "";
          int textColor = Color.WHITE;

          textContent = task.getValue(Task.TITLE);

          if (task.isCompleted())
            textColor = context.getResources().getColor(R.color.task_list_done);
          else if (task.hasDueDate() && task.getValue(Task.DUE_DATE) < DateUtilities.now())
            textColor = context.getResources().getColor(R.color.task_list_overdue);

          if (i > 0) views.setViewVisibility(separatorIDs[i - 1], View.VISIBLE);
          views.setTextViewText(textIDs[i], textContent);
          views.setTextColor(textIDs[i], textColor);
        }

        for (int i = cursor.getCount() - 1; i < separatorIDs.length; i++) {
          if (i >= 0) views.setViewVisibility(separatorIDs[i], View.INVISIBLE);
        }
      } catch (Exception e) {
        // can happen if database is not ready
        Log.e("WIDGET-UPDATE", "Error updating widget", e);
      } finally {
        if (cursor != null) cursor.close();
      }

      updateForScreenSize(views);

      Intent listIntent = new Intent(context, TaskListActivity.class);
      String customIntent =
          Preferences.getStringValue(WidgetConfigActivity.PREF_CUSTOM_INTENT + widgetId);
      if (customIntent != null) {
        listIntent.setComponent(ComponentName.unflattenFromString(customIntent));
        String serializedExtras =
            Preferences.getStringValue(WidgetConfigActivity.PREF_CUSTOM_EXTRAS + widgetId);
        Bundle extras = AndroidUtilities.bundleFromSerializedString(serializedExtras);
        listIntent.putExtras(extras);
      }
      listIntent.putExtra(TaskListActivity.TOKEN_SOURCE, Constants.SOURCE_WIDGET);
      listIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
      if (filter != null) {
        listIntent.putExtra(TaskListActivity.TOKEN_FILTER, filter);
        listIntent.setAction("L" + widgetId + filter.sqlQuery);
      }
      PendingIntent pendingIntent =
          PendingIntent.getActivity(
              context, widgetId, listIntent, PendingIntent.FLAG_CANCEL_CURRENT);
      views.setOnClickPendingIntent(R.id.taskbody, pendingIntent);

      Intent editIntent = new Intent(context, TaskEditActivity.class);
      editIntent.setFlags(
          Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
      if (filter != null && filter.valuesForNewTasks != null) {
        String values = AndroidUtilities.contentValuesToSerializedString(filter.valuesForNewTasks);
        editIntent.putExtra(TaskEditActivity.TOKEN_VALUES, values);
        editIntent.setType(values);
      }
      pendingIntent = PendingIntent.getActivity(context, 0, editIntent, 0);
      views.setOnClickPendingIntent(R.id.widget_button, pendingIntent);

      return views;
    }
Пример #14
0
  /** Called when this application is started up */
  public synchronized void onStartupApplication(final Activity context) {
    if (hasStartedUp || context == null) {
      return;
    }

    // sets up context manager
    ContextManager.setContext(context);

    try {
      database.openForWriting();
      checkForMissingColumns();
    } catch (SQLiteException e) {
      handleSQLiteError(context, e);
      return;
    }

    // show notification if reminders are silenced
    if (context instanceof Activity) {
      AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
      if (!Preferences.getBoolean(R.string.p_rmd_enabled, true)) {
        Toast.makeText(context, R.string.TLA_notification_disabled, Toast.LENGTH_LONG).show();
      } else if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) == 0) {
        Toast.makeText(context, R.string.TLA_notification_volume_low, Toast.LENGTH_LONG).show();
      }
    }

    // read current version
    int latestSetVersion = 0;
    try {
      latestSetVersion = AstridPreferences.getCurrentVersion();
    } catch (Exception e) {
      exceptionService.reportError("astrid-startup-version-read", e); // $NON-NLS-1$
    }

    if (latestSetVersion == 0) {
      if (Preferences.getLong(AstridPreferences.P_FIRST_LAUNCH, -1) < 0) {
        Preferences.setLong(AstridPreferences.P_FIRST_LAUNCH, DateUtilities.now());
      }
    }

    BeastModePreferences.assertHideUntilSectionExists(context, latestSetVersion);

    int version = 0;
    String versionName = "0"; // $NON-NLS-1$
    try {
      PackageManager pm = context.getPackageManager();
      PackageInfo pi = pm.getPackageInfo(Constants.PACKAGE, PackageManager.GET_META_DATA);
      version = pi.versionCode;
      versionName = pi.versionName;
    } catch (Exception e) {
      exceptionService.reportError("astrid-startup-package-read", e); // $NON-NLS-1$
    }

    Log.i(
        "astrid",
        "Astrid Startup. "
            + latestSetVersion
            + //$NON-NLS-1$ //$NON-NLS-2$
            " => "
            + version); //$NON-NLS-1$

    databaseRestoreIfEmpty(context);

    // invoke upgrade service
    boolean justUpgraded = latestSetVersion != version;
    if (justUpgraded && version > 0) {
      if (latestSetVersion > 0) {
        upgradeService.performUpgrade(context, latestSetVersion);
      }
      AstridPreferences.setCurrentVersion(version);
      AstridPreferences.setCurrentVersionName(versionName);
    }

    final int finalLatestVersion = latestSetVersion;

    initializeDatabaseListeners();

    // perform startup activities in a background thread
    new Thread(
            new Runnable() {
              @Override
              public void run() {
                taskService.cleanup();

                // if sync ongoing flag was set, clear it
                gtasksPreferenceService.stopOngoing();

                // perform initialization
                ReminderStartupReceiver.startReminderSchedulingService(context);
                BackupService.scheduleService(context);

                gtasksSyncService.initialize();

                // get and display update messages
                if (finalLatestVersion != 0) {
                  //                    new UpdateMessageService(context).processUpdates();
                }
              }
            })
        .start();

    AstridPreferences.setPreferenceDefaults();
    CalendarStartupReceiver.scheduleCalendarAlarms(
        context,
        false); // This needs to be after set preference defaults for the purposes of ab testing

    showTaskKillerHelp(context);

    hasStartedUp = true;
  }