summaryrefslogtreecommitdiffstats
path: root/chrome/browser/history_model.cc
blob: 49102a7428f3d89149f47632570b18af06aa0f2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/history_model.h"

#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/profile.h"

using base::Time;

// The max number of results to retrieve when browsing user's history.
static const int kMaxBrowseResults = 800;

// The max number of search results to retrieve.
static const int kMaxSearchResults = 100;

HistoryModel::HistoryModel(Profile* profile, const std::wstring& search_text)
    : BaseHistoryModel(profile),
      search_text_(search_text),
      search_depth_(0) {
  // Register for notifications about URL starredness changing on this profile.
  NotificationService::current()->
      AddObserver(this, NOTIFY_URLS_STARRED,
                  Source<Profile>(profile->GetOriginalProfile()));
  NotificationService::current()->
      AddObserver(this, NOTIFY_HISTORY_URLS_DELETED,
                  Source<Profile>(profile->GetOriginalProfile()));
}

HistoryModel::~HistoryModel() {
  // Unregister for notifications about URL starredness.
  NotificationService::current()->
      RemoveObserver(this, NOTIFY_URLS_STARRED,
                     Source<Profile>(profile_->GetOriginalProfile()));
  NotificationService::current()->
      RemoveObserver(this, NOTIFY_HISTORY_URLS_DELETED,
                     Source<Profile>(profile_->GetOriginalProfile()));
}

int HistoryModel::GetItemCount() {
  return static_cast<int>(results_.size());
}

Time HistoryModel::GetVisitTime(int index) {
#ifndef NDEBUG
  DCHECK(IsValidIndex(index));
#endif
  return results_[index].visit_time();
}

const std::wstring& HistoryModel::GetTitle(int index) {
  return results_[index].title();
}

const GURL& HistoryModel::GetURL(int index) {
  return results_[index].url();
}

history::URLID HistoryModel::GetURLID(int index) {
  return results_[index].id();
}

bool HistoryModel::IsStarred(int index) {
  if (star_state_[index] == UNKNOWN) {
    bool is_starred = profile_->GetBookmarkModel()->IsBookmarked(GetURL(index));
    star_state_[index] = is_starred ? STARRED : NOT_STARRED;
  }
  return (star_state_[index] == STARRED);
}

const Snippet& HistoryModel::GetSnippet(int index) {
  return results_[index].snippet();
}

void HistoryModel::RemoveFromModel(int start, int length) {
  DCHECK(start >= 0 && start + length <= GetItemCount());
  results_.DeleteRange(start, start + length);
  if (observer_)
    observer_->ModelChanged(true);
}

void HistoryModel::SetSearchText(const std::wstring& search_text) {
  if (search_text == search_text_)
    return;

  search_text_ = search_text;
  search_depth_ = 0;
  Refresh();
}

void HistoryModel::InitVisitRequest(int depth) {
  HistoryService* history_service =
      profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
  if (!history_service)
    return;

  AboutToScheduleRequest();

  history::QueryOptions options;

  // Limit our search so that it doesn't return more than the maximum required
  // number of results.
  int max_total_results = search_text_.empty() ?
                          kMaxBrowseResults : kMaxSearchResults;

  if (depth == 0) {
    // Set the end time of this first search to null (which will
    // show results from the future, should the user's clock have
    // been set incorrectly).
    options.end_time = Time();

    search_start_ = Time::Now();

    // Configure the begin point of the search to the start of the
    // current month.
    Time::Exploded start_exploded;
    search_start_.LocalMidnight().LocalExplode(&start_exploded);
    start_exploded.day_of_month = 1;
    options.begin_time = Time::FromLocalExploded(start_exploded);

    options.max_count = max_total_results;
  } else {
    Time::Exploded exploded;
    search_start_.LocalMidnight().LocalExplode(&exploded);
    exploded.day_of_month = 1;

    // Set the end-time of this search to the end of the month that is
    // |depth| months before the search end point. The end time is not
    // inclusive, so we should feel free to set it to midnight on the
    // first day of the following month.
    exploded.month -= depth - 1;
    while (exploded.month < 1) {
      exploded.month += 12;
      exploded.year--;
    }
    options.end_time = Time::FromLocalExploded(exploded);

    // Set the begin-time of the search to the start of the month
    // that is |depth| months prior to search_start_.
    if (exploded.month > 1) {
      exploded.month--;
    } else {
      exploded.month = 12;
      exploded.year--;
    }
    options.begin_time = Time::FromLocalExploded(exploded);

    // Subtract off the number of pages we already got.
    options.max_count = max_total_results - static_cast<int>(results_.size());
  }

  // This will make us get only one entry for each page. This is definitely
  // correct for "starred only" queries, but more debatable for regular
  // history queries. We might want to get all of them but then remove adjacent
  // duplicates like Mozilla.
  //
  // We'll still get duplicates across month boundaries, which is probably fine.
  options.most_recent_visit_only = true;

  HistoryService::QueryHistoryCallback* callback =
      NewCallback(this, &HistoryModel::VisitedPagesQueryComplete);
  history_service->QueryHistory(search_text_, options,
                                 &cancelable_consumer_, callback);
}

void HistoryModel::SetPageStarred(int index, bool state) {
  const history::URLResult& result = results_[index];
  if (!UpdateStarredStateOfURL(result.url(), state))
    return;  // Nothing was changed.

  if (observer_)
    observer_->ModelChanged(false);

  BookmarkModel* bb_model = profile_->GetBookmarkModel();
  if (bb_model)
    bb_model->SetURLStarred(result.url(), result.title(), state);
}

void HistoryModel::Refresh() {
  cancelable_consumer_.CancelAllRequests();
  if (observer_)
    observer_->ModelEndWork();
  search_depth_ = 0;
  InitVisitRequest(search_depth_);

  if (results_.size() > 0) {
    // There are results and we've been asked to reload. If we don't swap out
    // the results now, the view is left holding indices that are going to
    // change as soon as the load completes, which poses problems for deletion.
    // In particular, if the user deletes a range, then clicks on delete again
    // a modal dialog is shown. If during the time the modal dialog is shown
    // and the user clicks ok the load completes, the index passed to delete is
    // no longer valid. To avoid this we empty out the results immediately.
    history::QueryResults empty_results;
    results_.Swap(&empty_results);
    if (observer_)
      observer_->ModelChanged(true);
  }
}

void HistoryModel::Observe(NotificationType type,
                           const NotificationSource& source,
                           const NotificationDetails& details) {
  switch (type) {
  case NOTIFY_URLS_STARRED: {  // Somewhere, a URL has been starred.
    Details<history::URLsStarredDetails> starred_state(details);

    // In the degenerate case when there are a lot of pages starred, this may
    // be unacceptably slow.
    std::set<GURL>::const_iterator i;
    bool changed = false;
    for (i = starred_state->changed_urls.begin();
         i != starred_state->changed_urls.end(); ++i) {
      changed |= UpdateStarredStateOfURL(*i, starred_state->starred);
    }
    if (changed && observer_)
      observer_->ModelChanged(false);
    break;
  }

  case NOTIFY_HISTORY_URLS_DELETED:
    // TODO(brettw) bug 1140015: This should actually update the current query
    // rather than re-querying. This should be much more efficient and
    // user-friendly.
    //
    // Note that we can special case when the "all_history" flag is set to just
    // clear the view.
    Refresh();
    break;

  // TODO(brettw) bug 1140015, 1140017, 1140020: Add a more observers to catch
  // title changes, new additions, etc.. Also, URLS_ADDED when that
  // notification exists.

  default:
    NOTREACHED();
    break;
  }
}

void HistoryModel::VisitedPagesQueryComplete(
    HistoryService::Handle request_handle,
    history::QueryResults* results) {
  bool changed = (results->size() > 0);
  if (search_depth_ == 0) {
    if (results_.size() > 0)
      changed = true;
    results_.Swap(results);
  } else {
    results_.AppendResultsBySwapping(results, true);
  }

  is_search_results_ = !search_text_.empty();

  if (changed) {
    star_state_.reset(new StarState[results_.size()]);
    memset(star_state_.get(), 0, sizeof(StarState) * results_.size());
    if (observer_)
      observer_->ModelChanged(true);
  }

  search_depth_++;

  int max_results = search_text_.empty() ?
                    kMaxBrowseResults : kMaxSearchResults;

  // TODO(glen/brettw): bug 1203052 - Need to detect if we've reached the
  // end of the user's history.
  if (search_depth_ < kHistoryScopeMonths &&
      static_cast<int>(results_.size()) < max_results) {
    InitVisitRequest(search_depth_);
  } else {
    RequestCompleted();
  }
}

bool HistoryModel::UpdateStarredStateOfURL(const GURL& url, bool is_starred) {
  bool changed = false;

  // See if we've got any of the changed URLs in our results. There may be
  // more than once instance of the URL, and we have to update them all.
  size_t num_matches;
  const size_t* match_indices = results_.MatchesForURL(url, &num_matches);
  for (size_t i = 0; i < num_matches; i++) {
    if (IsStarred(static_cast<int>(match_indices[i])) != is_starred) {
      star_state_[match_indices[i]] = is_starred ? STARRED : NOT_STARRED;
      changed = true;
    }
  }
  return changed;
}