Welcome to mirror list, hosted at ThFree Co, Russian Federation.

search_engine.cpp « search - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b0e78991cb670807f44e94bf11eb20e80a0b797c (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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#include "search_engine.hpp"
#include "result.hpp"
#include "search_query.hpp"

#include "../storage/country_info.hpp"

#include "../indexer/categories_holder.hpp"
#include "../indexer/search_string_utils.hpp"
#include "../indexer/mercator.hpp"
#include "../indexer/scales.hpp"

#include "../platform/platform.hpp"

#include "../geometry/distance_on_sphere.hpp"

#include "../base/logging.hpp"
#include "../base/stl_add.hpp"

#include "../std/map.hpp"
#include "../std/vector.hpp"
#include "../std/bind.hpp"


namespace search
{

typedef vector<Query::SuggestT> SuggestsContainerT;

class EngineData
{
public:
  EngineData(Reader * pCategoriesR, ModelReaderPtr polyR, ModelReaderPtr countryR)
    : m_categories(pCategoriesR), m_infoGetter(polyR, countryR)
  {
  }

  CategoriesHolder m_categories;
  SuggestsContainerT m_stringsToSuggest;
  storage::CountryInfoGetter m_infoGetter;
};

namespace
{

class InitSuggestions
{
  // Key - is a string with language.
  typedef map<pair<strings::UniString, int8_t>, uint8_t> SuggestMapT;
  SuggestMapT m_suggests;

public:
  void operator() (CategoriesHolder::Category::Name const & name)
  {
    if (name.m_prefixLengthToSuggest != CategoriesHolder::Category::EMPTY_PREFIX_LENGTH)
    {
      strings::UniString const uniName = NormalizeAndSimplifyString(name.m_name);

      uint8_t & score = m_suggests[make_pair(uniName, name.m_lang)];
      if (score == 0 || score > name.m_prefixLengthToSuggest)
        score = name.m_prefixLengthToSuggest;
    }
  }

  void GetSuggests(SuggestsContainerT & cont) const
  {
    cont.reserve(m_suggests.size());
    for (SuggestMapT::const_iterator i = m_suggests.begin(); i != m_suggests.end(); ++i)
      cont.push_back(Query::SuggestT(i->first.first, i->second, i->first.second));
  }
};

}


Engine::Engine(IndexType const * pIndex, Reader * pCategoriesR,
               ModelReaderPtr polyR, ModelReaderPtr countryR,
               string const & lang)
  : m_readyThread(false),
    m_pIndex(pIndex),
    m_pData(new EngineData(pCategoriesR, polyR, countryR))
{
  InitSuggestions doInit;
  m_pData->m_categories.ForEachName(bind<void>(ref(doInit), _1));
  doInit.GetSuggests(m_pData->m_stringsToSuggest);

  m_pQuery.reset(new Query(pIndex,
                           &m_pData->m_categories,
                           &m_pData->m_stringsToSuggest,
                           &m_pData->m_infoGetter,
                           RESULTS_COUNT));
  m_pQuery->SetPreferredLanguage(lang);
}

Engine::~Engine()
{
}

namespace
{
  m2::PointD GetViewportXY(double lat, double lon)
  {
    return m2::PointD(MercatorBounds::LonToX(lon), MercatorBounds::LatToY(lat));
  }
  m2::RectD GetViewportRect(double lat, double lon, double radius = 20000)
  {
    return MercatorBounds::MetresToXY(lon, lat, radius);
  }

  enum { VIEWPORT_RECT = 0, NEARME_RECT = 1 };

  // X metres in mercator (lon, lat) units.
  double const epsEqualRects = 100.0 * MercatorBounds::degreeInMetres;

  /// Check rects for optimal search (avoid duplicating).
  void AnalyzeRects(m2::RectD arrRects[2])
  {
    if (arrRects[NEARME_RECT].IsRectInside(arrRects[VIEWPORT_RECT]) &&
        arrRects[NEARME_RECT].Center().EqualDxDy(arrRects[VIEWPORT_RECT].Center(), epsEqualRects))
    {
      arrRects[VIEWPORT_RECT].MakeEmpty();
    }
    else
    {
      if (arrRects[VIEWPORT_RECT].IsRectInside(arrRects[NEARME_RECT]) &&
          (scales::GetScaleLevel(arrRects[VIEWPORT_RECT]) + Query::SCALE_SEARCH_DEPTH >= scales::GetUpperScale()))
      {
        arrRects[NEARME_RECT].MakeEmpty();
      }
    }
  }
}

void Engine::PrepareSearch(m2::RectD const & viewport,
                           bool hasPt, double lat, double lon)
{
  m2::RectD const nearby = (hasPt ? GetViewportRect(lat, lon) : m2::RectD());

  // bind does copy of all rects
  GetPlatform().RunAsync(bind(&Engine::SetViewportAsync, this, viewport, nearby));
}

bool Engine::Search(SearchParams const & params, m2::RectD const & viewport)
{
  // Check for equal query.
  // There is no need to put synch here for reading m_params,
  // because this function is always called from main thread (one-by-one for queries).

  if (!params.IsForceSearch() &&
      m_params.IsEqualCommon(params) &&
      m2::IsEqual(m_viewport, viewport, epsEqualRects, epsEqualRects))
  {
    if (!m_params.IsValidPosition())
      return false;

    // Check distance between previous and current user's position.
    if (ms::DistanceOnEarth(m_params.m_lat, m_params.m_lon, params.m_lat, params.m_lon) < 500.0)
      return false;
  }

  {
    // Assign new search params.
    // Put the synch here, because this params are reading in search threads.
    threads::MutexGuard guard(m_updateMutex);
    m_params = params;
    m_viewport = viewport;
  }

  // Run task.
  GetPlatform().RunAsync(bind(&Engine::SearchAsync, this));

  return true;
}

void Engine::SetViewportAsync(m2::RectD const & viewport, m2::RectD const & nearby)
{
  // First of all - cancel previous query.
  m_pQuery->DoCancel();

  // Enter to run new search.
  threads::MutexGuard searchGuard(m_searchMutex);

  m2::RectD arrRects[] = { viewport, nearby };
  AnalyzeRects(arrRects);

  m_pQuery->SetViewport(arrRects, ARRAY_SIZE(arrRects));
}

namespace
{
  bool LessByDistance(Result const & r1, Result const & r2)
  {
    Result::ResultType const t1 = r1.GetResultType();

    if (t1 == r2.GetResultType() && t1 == Result::RESULT_FEATURE)
      return (r1.GetDistanceFromCenter() < r2.GetDistanceFromCenter());
    else if (t1 == Result::RESULT_SUGGESTION)
      return true;
    else
      return false;
  }

  /// @todo Temporary solution to ensure that results are sorted by distance only for AROUND_POSITION mode.
  void EmitResults(SearchParams const & params, Results & res)
  {
    if (params.IsValidPosition() &&
        params.NeedSearch(SearchParams::AROUND_POSITION) &&
        !params.NeedSearch(SearchParams::IN_VIEWPORT) &&
        !params.NeedSearch(SearchParams::SEARCH_WORLD))
    {
      res.Sort(&LessByDistance);
    }

    params.m_callback(res);
  }
}

void Engine::SearchAsync()
{
  {
    // Avoid many threads waiting in search mutex. One is enough.
    threads::MutexGuard readyGuard(m_readyMutex);
    if (m_readyThread)
      return;
    m_readyThread = true;
  }

  // First of all - cancel previous query.
  m_pQuery->DoCancel();

  // Enter to run new search.
  threads::MutexGuard searchGuard(m_searchMutex);

  {
    threads::MutexGuard readyGuard(m_readyMutex);
    m_readyThread = false;
  }

  // Get current search params.
  SearchParams params;
  m2::RectD arrRects[2];

  {
    threads::MutexGuard updateGuard(m_updateMutex);
    params = m_params;
    arrRects[VIEWPORT_RECT] = m_viewport;
  }

  // Initialize query.
  m_pQuery->Init();

  // Set search viewports according to search params.
  if (params.IsValidPosition())
  {
    if (params.NeedSearch(SearchParams::AROUND_POSITION))
    {
      m_pQuery->SetPosition(GetViewportXY(params.m_lat, params.m_lon));
      arrRects[NEARME_RECT] = GetViewportRect(params.m_lat, params.m_lon);
    }
  }
  else
    m_pQuery->NullPosition();

  if (!params.NeedSearch(SearchParams::IN_VIEWPORT))
    arrRects[VIEWPORT_RECT].MakeEmpty();

  if (arrRects[NEARME_RECT].IsValid() && arrRects[VIEWPORT_RECT].IsValid())
    AnalyzeRects(arrRects);

  m_pQuery->SetViewport(arrRects, 2);

  m_pQuery->SetSearchInWorld(params.NeedSearch(SearchParams::SEARCH_WORLD));

  if (params.IsLanguageValid())
    m_pQuery->SetInputLanguage(params.m_inputLanguageCode);

  m_pQuery->SetQuery(params.m_query);
  bool const emptyQuery = m_pQuery->IsEmptyQuery();

  Results res;

  // Call m_pQuery->IsCanceled() everywhere it needed without storing return value.
  // This flag can be changed from another thread.

  m_pQuery->SearchCoordinates(params.m_query, res);

  try
  {
    if (emptyQuery)
    {
      // Search for empty query only around viewport.
      if (params.IsValidPosition())
      {
        double arrR[] = { 500, 1000, 2000 };
        for (size_t i = 0; i < ARRAY_SIZE(arrR); ++i)
        {
          res.Clear();
          m_pQuery->SearchAllInViewport(GetViewportRect(params.m_lat, params.m_lon, arrR[i]),
                                        res, 3*RESULTS_COUNT);

          if (m_pQuery->IsCanceled() || res.GetCount() >= 2*RESULTS_COUNT)
            break;
        }
      }
    }
    else
    {
      // Do search for address in all modes.
      // params.NeedSearch(SearchParams::SEARCH_ADDRESS)
      m_pQuery->Search(res, true);
    }
  }
  catch (Query::CancelException const &)
  {
  }

  // Emit results even if search was canceled and we have something.
  size_t const count = res.GetCount();
  if (!m_pQuery->IsCanceled() || count > 0)
    EmitResults(params, res);

  // Make additional search in whole mwm when not enough results (only for non-empty query).
  if (!emptyQuery && !m_pQuery->IsCanceled() && count < RESULTS_COUNT)
  {
    try
    {
      m_pQuery->SearchAdditional(res,
                                 params.NeedSearch(SearchParams::AROUND_POSITION),
                                 params.NeedSearch(SearchParams::IN_VIEWPORT));
    }
    catch (Query::CancelException const &)
    {
    }

    // Emit if we have more results.
    if (res.GetCount() > count)
      EmitResults(params, res);
  }

  // Emit finish marker to client.
  params.m_callback(Results::GetEndMarker(m_pQuery->IsCanceled()));
}

string Engine::GetCountryFile(m2::PointD const & pt)
{
  threads::MutexGuard searchGuard(m_searchMutex);

  return m_pData->m_infoGetter.GetRegionFile(pt);
}

string Engine::GetCountryCode(m2::PointD const & pt)
{
  threads::MutexGuard searchGuard(m_searchMutex);

  storage::CountryInfo info;
  m_pData->m_infoGetter.GetRegionInfo(pt, info);
  return info.m_flag;
}

template <class T> string Engine::GetCountryNameT(T const & t)
{
  threads::MutexGuard searchGuard(m_searchMutex);

  storage::CountryInfo info;
  m_pData->m_infoGetter.GetRegionInfo(t, info);
  return info.m_name;
}

string Engine::GetCountryName(m2::PointD const & pt)
{
  return GetCountryNameT(pt);
}

string Engine::GetCountryName(string const & id)
{
  return GetCountryNameT(id);
}

bool Engine::GetNameByType(uint32_t type, int8_t lang, string & name) const
{
  return m_pData->m_categories.GetNameByType(type, lang, name);
}

m2::RectD Engine::GetCountryBounds(string const & file) const
{
  return m_pData->m_infoGetter.CalcLimitRect(file);
}

int8_t Engine::GetCurrentLanguage() const
{
  return m_pQuery->GetPrefferedLanguage();
}

void Engine::ClearViewportsCache()
{
  threads::MutexGuard guard(m_searchMutex);

  m_pQuery->ClearCaches();
}

void Engine::ClearAllCaches()
{
  threads::MutexGuard guard(m_searchMutex);

  m_pQuery->ClearCaches();
  m_pData->m_infoGetter.ClearCaches();
}

}  // namespace search