Rotational $g$ factors and Lorentz forces of molecules and solids from density-functional perturbation theory