コード例 #1
0
ファイル: BookmarksPanel.java プロジェクト: nikaiw/gecko-dev
 @Override
 public void onContentChanged() {
   // Invalidate the cached value that keeps track of whether or
   // not desktop bookmarks exist.
   BrowserDB.invalidateCachedState();
   super.onContentChanged();
 }
コード例 #2
0
    protected void onPostExecute(Pair<GroupList, List<ChildrenList>> result) {
      mCursorAdapter =
          new HistoryListAdapter(
              mContext,
              result.first,
              R.layout.awesomebar_header_row,
              new String[] {URLColumns.TITLE},
              new int[] {R.id.title},
              result.second);

      if (mContentObserver == null) {
        // Register an observer to update the history tab contents if they change.
        mContentObserver =
            new ContentObserver(GeckoAppShell.getHandler()) {
              public void onChange(boolean selfChange) {
                mQueryTask = new HistoryQueryTask();
                mQueryTask.execute();
              }
            };
        BrowserDB.registerHistoryObserver(getContentResolver(), mContentObserver);
      }

      final ExpandableListView historyList = (ExpandableListView) getView();

      // Hack: force this to the main thread, even though it should already be on it
      GeckoApp.mAppContext.mMainHandler.post(
          new Runnable() {
            public void run() {
              historyList.setAdapter(mCursorAdapter);
              expandAllGroups(historyList);
            }
          });

      mQueryTask = null;
    }
コード例 #3
0
    @Override
    public Cursor loadCursor() {
      final ContentResolver cr = getContext().getContentResolver();

      Cursor c = BrowserDB.getFaviconsForUrls(cr, mUrls);
      storeFaviconsInMemCache(c);

      return c;
    }
コード例 #4
0
  @Override
  public void onResume() {
    super.onResume();
    if (mText != null && mText.getText() != null) updateGoButton(mText.getText().toString());

    // Invlidate the cached value that keeps track of whether or
    // not desktop bookmarks exist
    BrowserDB.invalidateCachedState();
  }
コード例 #5
0
    protected Pair<GroupList, List<ChildrenList>> doInBackground(Void... arg0) {
      Cursor cursor = BrowserDB.getRecentHistory(getContentResolver(), MAX_RESULTS);

      Date now = new Date();
      now.setHours(0);
      now.setMinutes(0);
      now.setSeconds(0);

      long today = now.getTime();

      // Split the list of urls into separate date range groups
      // and show it in an expandable list view.
      List<ChildrenList> childrenLists = new LinkedList<ChildrenList>();
      ChildrenList children = null;
      GroupList groups = new GroupList();
      HistorySection section = null;

      // Move cursor before the first row in preparation
      // for the iteration.
      cursor.moveToPosition(-1);

      // Split the history query results into adapters per time
      // section (today, yesterday, week, older). Queries on content
      // Browser content provider don't support limitting the number
      // of returned rows so we limit it here.
      while (cursor.moveToNext()) {
        long time = cursor.getLong(cursor.getColumnIndexOrThrow(URLColumns.DATE_LAST_VISITED));
        HistorySection itemSection = getSectionForTime(time, today);

        if (section != itemSection) {
          if (section != null) {
            groups.add(createGroupItem(section));
            childrenLists.add(children);
          }

          section = itemSection;
          children = new ChildrenList();
        }

        children.add(createHistoryItem(cursor));
      }

      // Add any remaining section to the list if it hasn't
      // been added to the list after the loop.
      if (section != null && children != null) {
        groups.add(createGroupItem(section));
        childrenLists.add(children);
      }

      // Close the query cursor as we won't use it anymore
      cursor.close();

      // groups and childrenLists will be empty lists if there's no history
      return Pair.<GroupList, List<ChildrenList>>create(groups, childrenLists);
    }
コード例 #6
0
  private void openUserEnteredAndFinish(String url) {
    int index = url.indexOf(' ');
    if (index != -1) {
      String keywordUrl = BrowserDB.getUrlForKeyword(mResolver, url.substring(0, index));
      if (keywordUrl != null && keywordUrl.contains("%s")) {
        String search = URLEncoder.encode(url.substring(index + 1));
        url = keywordUrl.replace("%s", search);
      }
    }

    Intent resultIntent = new Intent();
    resultIntent.putExtra(URL_KEY, url);
    resultIntent.putExtra(TARGET_KEY, mTarget);
    resultIntent.putExtra(USER_ENTERED_KEY, true);
    finishWithResult(resultIntent);
  }
コード例 #7
0
  private void loadTopSites() {
    // The SyncAccounts.syncAccountsExist method should not be called on
    // UI thread as it touches disk to access a sqlite DB.
    final boolean syncIsSetup = SyncAccounts.syncAccountsExist(mActivity);

    final ContentResolver resolver = mActivity.getContentResolver();
    Cursor old = null;
    if (mTopSitesAdapter != null) {
      old = mTopSitesAdapter.getCursor();
    }
    // Swap in the new cursor.
    final Cursor oldCursor = old;
    final Cursor newCursor = BrowserDB.getTopSites(resolver, mNumberOfTopSites);

    post(
        new Runnable() {
          public void run() {
            if (mTopSitesAdapter == null) {
              mTopSitesAdapter =
                  new TopSitesCursorAdapter(
                      mActivity,
                      R.layout.abouthome_topsite_item,
                      newCursor,
                      new String[] {URLColumns.TITLE},
                      new int[] {R.id.title});

              mTopSitesGrid.setAdapter(mTopSitesAdapter);
            } else {
              mTopSitesAdapter.changeCursor(newCursor);
            }

            if (mTopSitesAdapter.getCount() > 0) loadTopSitesThumbnails(resolver);

            updateLayout(syncIsSetup);

            // Free the old Cursor in the right thread now.
            if (oldCursor != null && !oldCursor.isClosed()) oldCursor.close();

            // Even if AboutHome isn't necessarily entirely loaded if we
            // get here, for phones this is the part the user initially sees,
            // so it's the one we will care about for now.
            if (mLoadCompleteCallback != null) mLoadCompleteCallback.callback();
          }
        });
  }
コード例 #8
0
  /**
   * Show the Edit bookmark dialog for a particular url. If the url is bookmarked multiple times
   * this will just edit the first instance it finds.
   *
   * @param url The url of the bookmark to edit. The dialog will look up other information like the
   *     id, current title, or keywords associated with this url. If the url isn't bookmarked, the
   *     dialog will fail silently. If the url is bookmarked multiple times, this will only show
   *     information about the first it finds.
   */
  public void show(final String url) {
    final ContentResolver cr = mContext.getContentResolver();
    final BrowserDB db = BrowserDB.from(mContext);
    (new UIAsyncTask.WithoutParams<Bookmark>(ThreadUtils.getBackgroundHandler()) {
          @Override
          public Bookmark doInBackground() {
            final Cursor cursor = db.getBookmarkForUrl(cr, url);
            if (cursor == null) {
              return null;
            }

            Bookmark bookmark = null;
            try {
              cursor.moveToFirst();
              bookmark =
                  new Bookmark(
                      cursor.getInt(cursor.getColumnIndexOrThrow(Bookmarks._ID)),
                      cursor.getString(cursor.getColumnIndexOrThrow(Bookmarks.TITLE)),
                      cursor.getString(cursor.getColumnIndexOrThrow(Bookmarks.URL)),
                      cursor.getString(cursor.getColumnIndexOrThrow(Bookmarks.KEYWORD)));
            } finally {
              cursor.close();
            }
            return bookmark;
          }

          @Override
          public void onPostExecute(Bookmark bookmark) {
            if (bookmark == null) {
              return;
            }

            show(bookmark.id, bookmark.title, bookmark.url, bookmark.keyword);
          }
        })
        .execute();
  }
コード例 #9
0
ファイル: GeckoView.java プロジェクト: nikaiw/gecko-dev
  private void init(Context context, String url, boolean doInit) {
    // TODO: Fennec currently takes care of its own initialization, so this
    // flag is a hack used in Fennec to prevent GeckoView initialization.
    // This should go away once Fennec also uses GeckoView for
    // initialization.
    if (!doInit) return;

    // If running outside of a GeckoActivity (eg, from a library project),
    // load the native code and disable content providers
    boolean isGeckoActivity = false;
    try {
      isGeckoActivity = context instanceof GeckoActivity;
    } catch (NoClassDefFoundError ex) {
    }

    if (!isGeckoActivity) {
      // Set the GeckoInterface if the context is an activity and the GeckoInterface
      // has not already been set
      if (context instanceof Activity && getGeckoInterface() == null) {
        setGeckoInterface(new BaseGeckoInterface(context));
      }

      Clipboard.init(context);
      HardwareUtils.init(context);

      // If you want to use GeckoNetworkManager, start it.

      GeckoLoader.loadMozGlue();
      BrowserDB.setEnableContentProviders(false);
    }

    if (url != null) {
      GeckoThread.setUri(url);
      GeckoThread.setAction(Intent.ACTION_VIEW);
      GeckoAppShell.sendEventToGecko(GeckoEvent.createURILoadEvent(url));
    }
    GeckoAppShell.setContextGetter(this);
    if (context instanceof Activity) {
      Tabs tabs = Tabs.getInstance();
      tabs.attachToContext(context);
    }

    EventDispatcher.getInstance()
        .registerGeckoThreadListener(
            this,
            "Gecko:Ready",
            "Content:StateChange",
            "Content:LoadError",
            "Content:PageShow",
            "DOMTitleChanged",
            "Link:Favicon",
            "Prompt:Show",
            "Prompt:ShowTop");

    ThreadUtils.setUiThread(Thread.currentThread(), new Handler());
    initializeView(EventDispatcher.getInstance());

    if (GeckoThread.checkAndSetLaunchState(
        GeckoThread.LaunchState.Launching, GeckoThread.LaunchState.Launched)) {
      // This is the first launch, so finish initialization and go.
      GeckoProfile profile = GeckoProfile.get(context).forceCreate();
      BrowserDB.initialize(profile.getName());

      GeckoAppShell.setLayerView(this);
      GeckoThread.createAndStart();
    } else if (GeckoThread.checkLaunchState(GeckoThread.LaunchState.GeckoRunning)) {
      // If Gecko is already running, that means the Activity was
      // destroyed, so we need to re-attach Gecko to this GeckoView.
      connectToGecko();
    }
  }
コード例 #10
0
 public void destroy() {
   if (mContentObserver != null)
     BrowserDB.unregisterContentObserver(getContentResolver(), mContentObserver);
 }
コード例 #11
0
ファイル: BookmarksPanel.java プロジェクト: nikaiw/gecko-dev
 @Override
 public Cursor loadCursor() {
   return BrowserDB.getBookmarksInFolder(getContext().getContentResolver(), mFolderInfo.id);
 }
コード例 #12
0
  /**
   * Show the Edit bookmark dialog for a set of data. This will show the dialog whether a bookmark
   * with this url exists or not, but the results will NOT be saved if the id is not a valid
   * bookmark id.
   *
   * @param id The id of the bookmark to change. If there is no bookmark with this ID, the dialog
   *     will fail silently.
   * @param title The initial title to show in the dialog
   * @param url The initial url to show in the dialog
   * @param keyword The initial keyword to show in the dialog
   */
  public void show(final int id, final String title, final String url, final String keyword) {
    final Context context = mContext;

    AlertDialog.Builder editPrompt = new AlertDialog.Builder(context);
    final View editView = LayoutInflater.from(context).inflate(R.layout.bookmark_edit, null);
    editPrompt.setTitle(R.string.bookmark_edit_title);
    editPrompt.setView(editView);

    final EditText nameText = ((EditText) editView.findViewById(R.id.edit_bookmark_name));
    final EditText locationText = ((EditText) editView.findViewById(R.id.edit_bookmark_location));
    final EditText keywordText = ((EditText) editView.findViewById(R.id.edit_bookmark_keyword));
    nameText.setText(title);
    locationText.setText(url);
    keywordText.setText(keyword);

    final BrowserDB db = BrowserDB.from(mContext);
    editPrompt.setPositiveButton(
        R.string.button_ok,
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int whichButton) {
            (new UIAsyncTask.WithoutParams<Void>(ThreadUtils.getBackgroundHandler()) {
                  @Override
                  public Void doInBackground() {
                    String newUrl = locationText.getText().toString().trim();
                    String newKeyword = keywordText.getText().toString().trim();

                    db.updateBookmark(
                        context.getContentResolver(),
                        id,
                        newUrl,
                        nameText.getText().toString(),
                        newKeyword);
                    return null;
                  }

                  @Override
                  public void onPostExecute(Void result) {
                    SnackbarBuilder.builder((Activity) context)
                        .message(R.string.bookmark_updated)
                        .duration(Snackbar.LENGTH_LONG)
                        .buildAndShow();
                  }
                })
                .execute();
          }
        });

    editPrompt.setNegativeButton(
        R.string.button_cancel,
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int whichButton) {
            // do nothing
          }
        });

    final AlertDialog dialog = editPrompt.create();

    // Create our TextWatchers
    LocationTextWatcher locationTextWatcher = new LocationTextWatcher(dialog);
    KeywordTextWatcher keywordTextWatcher = new KeywordTextWatcher(dialog);

    // Cross reference the TextWatchers
    locationTextWatcher.setPairedTextWatcher(keywordTextWatcher);
    keywordTextWatcher.setPairedTextWatcher(locationTextWatcher);

    // Add the TextWatcher Listeners
    locationText.addTextChangedListener(locationTextWatcher);
    keywordText.addTextChangedListener(keywordTextWatcher);

    dialog.show();
  }
コード例 #13
0
 protected Cursor doInBackground(Void... arg0) {
   ContentResolver resolver = mContext.getContentResolver();
   return BrowserDB.getAllBookmarks(resolver);
 }
コード例 #14
0
 @Override
 public Cursor loadCursor() {
   final ContentResolver cr = getContext().getContentResolver();
   return BrowserDB.getRecentHistory(cr, HISTORY_LIMIT);
 }
コード例 #15
0
  @Override
  public void handleMessage(String event, JSONObject message) {
    try {
      if (event.equals("Menu:Add")) {
        MenuItemInfo info = new MenuItemInfo();
        info.label = message.getString("name");
        info.id = message.getInt("id") + ADDON_MENU_OFFSET;
        info.checkable = false;
        info.checked = false;
        info.enabled = true;
        info.visible = true;
        String iconRes = null;
        try { // icon is optional
          iconRes = message.getString("icon");
        } catch (Exception ex) {
        }
        info.icon = iconRes;
        info.checkable = false;
        try {
          info.checkable = message.getBoolean("checkable");
        } catch (Exception ex) {
        }
        try { // parent is optional
          info.parent = message.getInt("parent") + ADDON_MENU_OFFSET;
        } catch (Exception ex) {
        }
        final MenuItemInfo menuItemInfo = info;
        mMainHandler.post(
            new Runnable() {
              public void run() {
                addAddonMenuItem(menuItemInfo);
              }
            });
      } else if (event.equals("Menu:Remove")) {
        final int id = message.getInt("id") + ADDON_MENU_OFFSET;
        mMainHandler.post(
            new Runnable() {
              public void run() {
                removeAddonMenuItem(id);
              }
            });
      } else if (event.equals("Menu:Update")) {
        final int id = message.getInt("id") + ADDON_MENU_OFFSET;
        final JSONObject options = message.getJSONObject("options");
        mMainHandler.post(
            new Runnable() {
              public void run() {
                updateAddonMenuItem(id, options);
              }
            });
      } else if (event.equals("CharEncoding:Data")) {
        final JSONArray charsets = message.getJSONArray("charsets");
        int selected = message.getInt("selected");

        final int len = charsets.length();
        final String[] titleArray = new String[len];
        for (int i = 0; i < len; i++) {
          JSONObject charset = charsets.getJSONObject(i);
          titleArray[i] = charset.getString("title");
        }

        final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setSingleChoiceItems(
            titleArray,
            selected,
            new AlertDialog.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                try {
                  JSONObject charset = charsets.getJSONObject(which);
                  GeckoAppShell.sendEventToGecko(
                      GeckoEvent.createBroadcastEvent(
                          "CharEncoding:Set", charset.getString("code")));
                  dialog.dismiss();
                } catch (JSONException e) {
                  Log.e(LOGTAG, "error parsing json", e);
                }
              }
            });
        dialogBuilder.setNegativeButton(
            R.string.button_cancel,
            new AlertDialog.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            });
        mMainHandler.post(
            new Runnable() {
              public void run() {
                dialogBuilder.show();
              }
            });
      } else if (event.equals("CharEncoding:State")) {
        final boolean visible = message.getString("visible").equals("true");
        GeckoPreferences.setCharEncodingState(visible);
        final Menu menu = mMenu;
        mMainHandler.post(
            new Runnable() {
              public void run() {
                if (menu != null) menu.findItem(R.id.char_encoding).setVisible(visible);
              }
            });
      } else if (event.equals("Feedback:OpenPlayStore")) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("market://details?id=" + getPackageName()));
        startActivity(intent);
      } else if (event.equals("Feedback:MaybeLater")) {
        resetFeedbackLaunchCount();
      } else if (event.equals("Feedback:LastUrl")) {
        getLastUrl();
      } else if (event.equals("Gecko:Ready")) {
        // Handle this message in GeckoApp, but also enable the Settings
        // menuitem, which is specific to BrowserApp.
        super.handleMessage(event, message);
        final Menu menu = mMenu;
        mMainHandler.post(
            new Runnable() {
              public void run() {
                if (menu != null) menu.findItem(R.id.settings).setEnabled(true);
              }
            });
      } else if (event.equals("Telemetry:Gather")) {
        Telemetry.HistogramAdd(
            "PLACES_PAGES_COUNT", BrowserDB.getCount(getContentResolver(), "history"));
        Telemetry.HistogramAdd(
            "PLACES_BOOKMARKS_COUNT", BrowserDB.getCount(getContentResolver(), "bookmarks"));
        Telemetry.HistogramAdd(
            "FENNEC_FAVICONS_COUNT", BrowserDB.getCount(getContentResolver(), "favicons"));
        Telemetry.HistogramAdd(
            "FENNEC_THUMBNAILS_COUNT", BrowserDB.getCount(getContentResolver(), "thumbnails"));
      } else if (event.equals("Dex:Load")) {
        String zipFile = message.getString("zipfile");
        String implClass = message.getString("impl");
        Log.d(
            LOGTAG,
            "Attempting to load classes.dex file from "
                + zipFile
                + " and instantiate "
                + implClass);
        try {
          File tmpDir = getDir("dex", 0);
          DexClassLoader loader =
              new DexClassLoader(
                  zipFile, tmpDir.getAbsolutePath(), null, ClassLoader.getSystemClassLoader());
          Class<?> c = loader.loadClass(implClass);
          c.newInstance();
        } catch (Exception e) {
          Log.e(LOGTAG, "Unable to initialize addon", e);
        }
      } else {
        super.handleMessage(event, message);
      }
    } catch (Exception e) {
      Log.e(LOGTAG, "Exception handling message \"" + event + "\":", e);
    }
  }