+namespace {
+
+ bool
+ positionable(DocIterator const & cursor, DocIterator const & anchor)
+ {
+ // avoid deeper nested insets when selecting
+ if (cursor.depth() > anchor.depth())
+ return false;
+
+ // anchor might be deeper, should have same path then
+ for (size_t i = 0; i < cursor.depth(); ++i)
+ if (&cursor[i].inset() != &anchor[i].inset())
+ return false;
+
+ // position should be ok.
+ return true;
+ }
+
+
+ // Find position closest to (x, y) in cell given by iter.
+ // Used only in mathed
+ DocIterator bruteFind2(LCursor const & c, int x, int y)
+ {
+ double best_dist = std::numeric_limits<double>::max();
+
+ DocIterator result;
+
+ DocIterator it = c;
+ it.top().pos() = 0;
+ DocIterator et = c;
+ et.top().pos() = et.top().asMathInset()->cell(et.top().idx()).size();
+ for (int i = 0; ; ++i) {
+ int xo;
+ int yo;
+ LCursor cur = c;
+ cur.setCursor(it);
+ cur.inset().getCursorPos(cur.top(), xo, yo);
+ double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
+ // '<=' in order to take the last possible position
+ // this is important for clicking behind \sum in e.g. '\sum_i a'
+ lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
+ << " best: " << best_dist << endl;
+ if (d <= best_dist) {
+ best_dist = d;
+ result = it;
+ }
+ if (it == et)
+ break;
+ it.forwardPos();
+ }
+ return result;
+ }
+
+
+ /// moves position closest to (x, y) in given box
+ bool bruteFind(LCursor & cursor,
+ int x, int y, int xlow, int xhigh, int ylow, int yhigh)
+ {
+ BOOST_ASSERT(!cursor.empty());
+ CursorSlice bottom = cursor[0];
+
+ DocIterator it = doc_iterator_begin(bottom.inset());
+ DocIterator const et = doc_iterator_end(bottom.inset());
+
+ double best_dist = std::numeric_limits<double>::max();;
+ DocIterator best_cursor = et;
+
+ for ( ; it != et; it.forwardPos()) {
+ // avoid invalid nesting when selecting
+ if (bv_funcs::status(&cursor.bv(), it) == bv_funcs::CUR_INSIDE
+ && (!cursor.selection() || positionable(it, cursor.anchor_))) {
+ Point p = bv_funcs::getPos(it);
+ int xo = p.x_;
+ int yo = p.y_;
+ if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
+ double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
+ //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
+ // '<=' in order to take the last possible position
+ // this is important for clicking behind \sum in e.g. '\sum_i a'
+ if (d <= best_dist) {
+ //lyxerr << "*" << endl;
+ best_dist = d;
+ best_cursor = it;
+ }
+ }
+ }
+ }
+
+ //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
+ if (best_cursor != et) {
+ cursor.setCursor(best_cursor);
+ return true;
+ }
+
+ return false;
+ }
+
+} // namespace anon