Rewrote PR #1303 and added a test

Changed width and height calculations according to @chriseppstein's comments and added a test that specifically tests the total width and height smart layout in a case with spacing.

(And also removed whitespace and pushed on master instead of stable)

This does not fix the "spacing on the edges" issue, but IMO is still better than having the smart layout not consider spacing.