A little more info: when there are multiple selections, they are ordered by the order that they appear in the document, so, if you have the numbers of the top & bottom lines visible in the viewport (which I think you can get with `cm.visibleLines()`),  it's easy to determine "first selection in viewport" and "last selection in viewport".

Note that the "primary" selection can be in any position.