InPageSearchManager.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * Copyright (C) 2012 Research In Motion Limited. All rights reserved.
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "config.h"
  19. #include "InPageSearchManager.h"
  20. #include "DOMSupport.h"
  21. #include "Document.h"
  22. #include "DocumentMarkerController.h"
  23. #include "Editor.h"
  24. #include "Frame.h"
  25. #include "Node.h"
  26. #include "Page.h"
  27. #include "Range.h"
  28. #include "ShadowRoot.h"
  29. #include "TextIterator.h"
  30. #include "Timer.h"
  31. #include "WebPage_p.h"
  32. static const double MaxScopingDuration = 0.1;
  33. using namespace WebCore;
  34. namespace BlackBerry {
  35. namespace WebKit {
  36. class InPageSearchManager::DeferredScopeStringMatches {
  37. public:
  38. DeferredScopeStringMatches(InPageSearchManager* ipsm, Frame* scopingFrame, const String& text, bool reset, bool locateActiveMatchOnly)
  39. : m_searchManager(ipsm)
  40. , m_scopingFrame(scopingFrame)
  41. , m_timer(this, &DeferredScopeStringMatches::doTimeout)
  42. , m_searchText(text)
  43. , m_reset(reset)
  44. , m_locateActiveMatchOnly(locateActiveMatchOnly)
  45. {
  46. m_timer.startOneShot(0.0);
  47. }
  48. private:
  49. friend class InPageSearchManager;
  50. void doTimeout(Timer<DeferredScopeStringMatches>*)
  51. {
  52. m_searchManager->callScopeStringMatches(this, m_scopingFrame, m_searchText, m_reset, m_locateActiveMatchOnly);
  53. }
  54. InPageSearchManager* m_searchManager;
  55. Frame* m_scopingFrame;
  56. Timer<DeferredScopeStringMatches> m_timer;
  57. String m_searchText;
  58. bool m_reset;
  59. bool m_locateActiveMatchOnly;
  60. };
  61. InPageSearchManager::InPageSearchManager(WebPagePrivate* page)
  62. : m_webPage(page)
  63. , m_activeMatch(0)
  64. , m_resumeScopingFromRange(0)
  65. , m_activeMatchCount(0)
  66. , m_scopingComplete(false)
  67. , m_scopingCaseInsensitive(false)
  68. , m_locatingActiveMatch(false)
  69. , m_highlightAllMatches(false)
  70. , m_activeMatchIndex(0)
  71. {
  72. }
  73. InPageSearchManager::~InPageSearchManager()
  74. {
  75. cancelPendingScopingEffort();
  76. }
  77. bool InPageSearchManager::findNextString(const String& text, FindOptions findOptions, bool wrap, bool highlightAllMatches, bool selectActiveMatchOnClear)
  78. {
  79. bool highlightAllMatchesStateChanged = m_highlightAllMatches != highlightAllMatches;
  80. m_highlightAllMatches = highlightAllMatches;
  81. if (!text.length()) {
  82. clearTextMatches(selectActiveMatchOnClear);
  83. cancelPendingScopingEffort();
  84. m_activeSearchString = String();
  85. m_webPage->m_client->updateFindStringResult(m_activeMatchCount, m_activeMatchIndex);
  86. return false;
  87. }
  88. if (!shouldSearchForText(text)) {
  89. m_activeSearchString = text;
  90. m_webPage->m_client->updateFindStringResult(m_activeMatchCount, m_activeMatchIndex);
  91. return false;
  92. }
  93. // Validate the range in case any node has been removed since last search.
  94. if (m_activeMatch && !m_activeMatch->boundaryPointsValid())
  95. m_activeMatch = 0;
  96. ExceptionCode ec = 0;
  97. RefPtr<Range> searchStartingPoint = m_activeMatch ? m_activeMatch->cloneRange(ec) : 0;
  98. bool newSearch = highlightAllMatchesStateChanged || (m_activeSearchString != text);
  99. bool forward = !(findOptions & WebCore::Backwards);
  100. if (newSearch) { // Start a new search.
  101. m_activeSearchString = text;
  102. cancelPendingScopingEffort();
  103. m_scopingCaseInsensitive = findOptions & CaseInsensitive;
  104. m_webPage->m_page->unmarkAllTextMatches();
  105. } else {
  106. // Searching for same string should start from the end of last match.
  107. if (m_activeMatch) {
  108. if (forward)
  109. searchStartingPoint->setStart(searchStartingPoint->endPosition());
  110. else
  111. searchStartingPoint->setEnd(searchStartingPoint->startPosition());
  112. }
  113. }
  114. // If there is any active selection, new search should start from the beginning of it.
  115. bool startFromSelection = false;
  116. VisibleSelection selection = m_webPage->focusedOrMainFrame()->selection()->selection();
  117. if (!selection.isNone()) {
  118. searchStartingPoint = selection.firstRange().get();
  119. m_webPage->focusedOrMainFrame()->selection()->clear();
  120. startFromSelection = true;
  121. }
  122. Frame* currentActiveMatchFrame = selection.isNone() && m_activeMatch ? m_activeMatch->ownerDocument()->frame() : m_webPage->focusedOrMainFrame();
  123. if (findAndMarkText(text, searchStartingPoint.get(), currentActiveMatchFrame, findOptions, newSearch, startFromSelection))
  124. return true;
  125. Frame* startFrame = currentActiveMatchFrame;
  126. do {
  127. currentActiveMatchFrame = DOMSupport::incrementFrame(currentActiveMatchFrame, forward, wrap);
  128. if (!currentActiveMatchFrame) {
  129. // We should only ever have a null frame if we haven't found any
  130. // matches and we're not wrapping. We have searched every frame.
  131. ASSERT(!wrap);
  132. m_webPage->m_client->updateFindStringResult(m_activeMatchCount, m_activeMatchIndex);
  133. return false;
  134. }
  135. if (findAndMarkText(text, 0, currentActiveMatchFrame, findOptions, newSearch, startFromSelection))
  136. return true;
  137. } while (startFrame != currentActiveMatchFrame);
  138. clearTextMatches();
  139. m_webPage->m_client->updateFindStringResult(m_activeMatchCount, m_activeMatchIndex);
  140. return false;
  141. }
  142. bool InPageSearchManager::shouldSearchForText(const String& text)
  143. {
  144. if (text == m_activeSearchString)
  145. return m_activeMatchCount;
  146. // If the previous search string is prefix of new search string,
  147. // don't search if the previous one has zero result.
  148. if (m_scopingComplete
  149. && !m_activeMatchCount
  150. && m_activeSearchString.length()
  151. && text.length() > m_activeSearchString.length()
  152. && m_activeSearchString == text.substring(0, m_activeSearchString.length()))
  153. return false;
  154. return true;
  155. }
  156. bool InPageSearchManager::findAndMarkText(const String& text, Range* range, Frame* frame, const FindOptions& options, bool isNewSearch, bool startFromSelection)
  157. {
  158. if (RefPtr<Range> match = frame->editor().findStringAndScrollToVisible(text, range, options)) {
  159. // Move the highlight to the new match.
  160. setActiveMatchAndMarker(match);
  161. if (isNewSearch) {
  162. scopeStringMatches(text, true /* reset */, false /* locateActiveMatchOnly */);
  163. if (!m_highlightAllMatches) {
  164. // Not highlighting all matches, we need to add the marker here,
  165. // because scopeStringMatches does not add any markers, it only counts the number.
  166. // No need to unmarkAllTextMatches, it is already done from the caller because of newSearch
  167. m_activeMatch->ownerDocument()->markers()->addTextMatchMarker(m_activeMatch.get(), true);
  168. frame->editor().setMarkedTextMatchesAreHighlighted(true /* highlight */);
  169. }
  170. return true;
  171. }
  172. if (startFromSelection || m_locatingActiveMatch) {
  173. // We are finding next, but
  174. // - starting from a new node, or
  175. // - last locating active match effort is not done yet
  176. if (!m_scopingComplete) {
  177. // Last scoping is not done yet, let's restart it.
  178. scopeStringMatches(text, true /* reset */, false /* locateActiveMatchOnly */);
  179. } else {
  180. // Last scoping is done, but we are jumping to somewhere instead of
  181. // searching one by one, or there is another locating active match effort,
  182. // let's start a scoping effort to locate active match only.
  183. scopeStringMatches(text, true /* reset */, true /* locateActiveMatchOnly */);
  184. }
  185. } else {
  186. // We are finding next one by one, let's calculate active match index
  187. // There is at least one match, because otherwise we won't get into this block,
  188. // so m_activeMatchIndex is at least one.
  189. ASSERT(m_activeMatchCount);
  190. if (!(options & WebCore::Backwards))
  191. m_activeMatchIndex = m_activeMatchIndex + 1 > m_activeMatchCount ? 1 : m_activeMatchIndex + 1;
  192. else
  193. m_activeMatchIndex = m_activeMatchIndex - 1 < 1 ? m_activeMatchCount : m_activeMatchIndex - 1;
  194. m_webPage->m_client->updateFindStringResult(m_activeMatchCount, m_activeMatchIndex);
  195. }
  196. if (!m_highlightAllMatches) {
  197. // When only showing single matches, the scoping effort won't highlight
  198. // all matches but count them.
  199. m_webPage->m_page->unmarkAllTextMatches();
  200. m_activeMatch->ownerDocument()->markers()->addTextMatchMarker(m_activeMatch.get(), true);
  201. frame->editor().setMarkedTextMatchesAreHighlighted(true /* highlight */);
  202. }
  203. return true;
  204. }
  205. return false;
  206. }
  207. void InPageSearchManager::clearTextMatches(bool selectActiveMatchOnClear)
  208. {
  209. if (selectActiveMatchOnClear && m_activeMatch.get()) {
  210. VisibleSelection selection(m_activeMatch.get());
  211. m_activeMatch->ownerDocument()->frame()->selection()->setSelection(selection);
  212. }
  213. m_webPage->m_page->unmarkAllTextMatches();
  214. m_activeMatch = 0;
  215. m_activeMatchCount = 0;
  216. m_activeMatchIndex = 0;
  217. }
  218. void InPageSearchManager::setActiveMatchAndMarker(PassRefPtr<Range> range)
  219. {
  220. // Clear the old marker, update our range, and highlight the new range.
  221. if (m_activeMatch.get()) {
  222. if (Document* doc = m_activeMatch->ownerDocument())
  223. doc->markers()->setMarkersActive(m_activeMatch.get(), false);
  224. }
  225. m_activeMatch = range;
  226. if (m_activeMatch.get()) {
  227. if (Document* doc = m_activeMatch->ownerDocument())
  228. doc->markers()->setMarkersActive(m_activeMatch.get(), true);
  229. }
  230. }
  231. void InPageSearchManager::frameUnloaded(const Frame* frame)
  232. {
  233. for (size_t i = 0; i < m_deferredScopingWork.size(); i++) {
  234. if (m_deferredScopingWork[i]->m_scopingFrame == frame) {
  235. // Clear pending scoping efforts in case of dangling pointer.
  236. cancelPendingScopingEffort();
  237. break;
  238. }
  239. }
  240. if (!m_activeMatch) {
  241. if (m_webPage->mainFrame() == frame && m_activeSearchString.length())
  242. m_activeSearchString = String();
  243. return;
  244. }
  245. Frame* currentActiveMatchFrame = m_activeMatch->ownerDocument()->frame();
  246. if (currentActiveMatchFrame == frame) {
  247. // FIXME: We need to re-scope this frame instead of cancelling all effort?
  248. cancelPendingScopingEffort();
  249. m_activeMatch = 0;
  250. m_activeSearchString = String();
  251. m_activeMatchCount = 0;
  252. // FIXME: We need to notify client here.
  253. if (frame == m_webPage->mainFrame()) // Don't need to unmark because the page will be destroyed.
  254. return;
  255. m_webPage->m_page->unmarkAllTextMatches();
  256. }
  257. }
  258. void InPageSearchManager::scopeStringMatches(const String& text, bool reset, bool locateActiveMatchOnly, Frame* scopingFrame)
  259. {
  260. if (reset) {
  261. if (!locateActiveMatchOnly) {
  262. m_activeMatchCount = 0;
  263. m_scopingComplete = false;
  264. }
  265. m_resumeScopingFromRange = 0;
  266. m_locatingActiveMatch = true;
  267. m_activeMatchIndex = 0;
  268. // New search should always start from mainFrame.
  269. scopeStringMatchesSoon(m_webPage->mainFrame(), text, false /* reset */, locateActiveMatchOnly);
  270. return;
  271. }
  272. if (m_resumeScopingFromRange && scopingFrame != m_resumeScopingFromRange->ownerDocument()->frame())
  273. m_resumeScopingFromRange = 0;
  274. RefPtr<Range> searchRange(rangeOfContents(scopingFrame->document()));
  275. Node* originalEndContainer = searchRange->endContainer();
  276. int originalEndOffset = searchRange->endOffset();
  277. ExceptionCode ec = 0, ec2 = 0;
  278. if (m_resumeScopingFromRange) {
  279. searchRange->setStart(m_resumeScopingFromRange->startContainer(), m_resumeScopingFromRange->startOffset(ec2) + 1, ec);
  280. if (ec || ec2) {
  281. m_scopingComplete = true; // We should stop scoping because of some stale data.
  282. return;
  283. }
  284. }
  285. int matchCount = 0;
  286. bool timeout = false;
  287. double startTime = currentTime();
  288. do {
  289. RefPtr<Range> resultRange(findPlainText(searchRange.get(), text, m_scopingCaseInsensitive ? CaseInsensitive : 0));
  290. if (resultRange->collapsed(ec)) {
  291. if (!resultRange->startContainer()->isInShadowTree())
  292. break;
  293. searchRange->setStartAfter(resultRange->startContainer()->deprecatedShadowAncestorNode(), ec);
  294. searchRange->setEnd(originalEndContainer, originalEndOffset, ec);
  295. continue;
  296. }
  297. ++matchCount;
  298. bool foundActiveMatch = false;
  299. if (m_locatingActiveMatch && areRangesEqual(resultRange.get(), m_activeMatch.get())) {
  300. foundActiveMatch = true;
  301. m_locatingActiveMatch = false;
  302. if (locateActiveMatchOnly) {
  303. m_activeMatchIndex += matchCount;
  304. m_webPage->m_client->updateFindStringResult(m_activeMatchCount, m_activeMatchIndex);
  305. return;
  306. }
  307. m_activeMatchIndex = m_activeMatchCount + matchCount;
  308. }
  309. if (!locateActiveMatchOnly && m_highlightAllMatches)
  310. resultRange->ownerDocument()->markers()->addTextMatchMarker(resultRange.get(), foundActiveMatch);
  311. searchRange->setStart(resultRange->endContainer(ec), resultRange->endOffset(ec), ec);
  312. ShadowRoot* shadowTreeRoot = searchRange->shadowRoot();
  313. if (searchRange->collapsed(ec) && shadowTreeRoot)
  314. searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), ec);
  315. m_resumeScopingFromRange = resultRange;
  316. timeout = (currentTime() - startTime) >= MaxScopingDuration;
  317. } while (!timeout);
  318. if (matchCount > 0) {
  319. if (locateActiveMatchOnly) {
  320. // We have not found it yet.
  321. // m_activeMatchIndex now temporarily remember where we left over in this time slot.
  322. m_activeMatchIndex += matchCount;
  323. } else {
  324. if (m_highlightAllMatches)
  325. scopingFrame->editor().setMarkedTextMatchesAreHighlighted(true /* highlight */);
  326. m_activeMatchCount += matchCount;
  327. m_webPage->m_client->updateFindStringResult(m_activeMatchCount, m_activeMatchIndex);
  328. }
  329. }
  330. if (timeout)
  331. scopeStringMatchesSoon(scopingFrame, text, false /* reset */, locateActiveMatchOnly);
  332. else {
  333. // Scoping is done for this frame.
  334. Frame* nextFrame = DOMSupport::incrementFrame(scopingFrame, true /* forward */, false /* wrapFlag */);
  335. if (!nextFrame) {
  336. m_scopingComplete = true;
  337. return; // Scoping is done for all frames;
  338. }
  339. scopeStringMatchesSoon(nextFrame, text, false /* reset */, locateActiveMatchOnly);
  340. }
  341. }
  342. void InPageSearchManager::scopeStringMatchesSoon(Frame* scopingFrame, const String& text, bool reset, bool locateActiveMatchOnly)
  343. {
  344. m_deferredScopingWork.append(new DeferredScopeStringMatches(this, scopingFrame, text, reset, locateActiveMatchOnly));
  345. }
  346. void InPageSearchManager::callScopeStringMatches(DeferredScopeStringMatches* caller, Frame* scopingFrame, const String& text, bool reset, bool locateActiveMatchOnly)
  347. {
  348. m_deferredScopingWork.remove(m_deferredScopingWork.find(caller));
  349. scopeStringMatches(text, reset, locateActiveMatchOnly, scopingFrame);
  350. delete caller;
  351. }
  352. void InPageSearchManager::cancelPendingScopingEffort()
  353. {
  354. deleteAllValues(m_deferredScopingWork);
  355. m_deferredScopingWork.clear();
  356. }
  357. }
  358. }