Reputation: 453
I am currently using Applescript to calculate the size and position of a window from left to right which works great. Here is an example where I am trying to position of a window as "Left half of the screen"
tell application "System Events"
tell application process "Xcode"
activate
tell window 1 to set size to {(1600) / 2, 814}
tell window 1 to set position to {0, 0}
end tell
end tell
I am trying to work on positioning of the window "Right half of the screen" (technically I can calculate this by setting the X = screenWidth/2 but the issue is, the window of Xcode app some part of the screen is not visible the user where as if I calculate it from right I can ensure the entire window is on the screen visible to the user.
Actual result: https://share.cleanshot.com/COYgKD
Expected result: https://share.cleanshot.com/BIELCA
Goal: Show right half of the window that ensure the entire window is on the screen visible to the user
Any help is appreciated
Upvotes: 1
Views: 309
Reputation: 6092
To obtain your your screen's dimensions:
tell application id "com.apple.finder" to set ¬
[null, null, screenW, screenH] to the ¬
bounds of the desktop's window
XCode is scriptable, I believe, so there's no need to invoke System Events to get or set its size and position. However, scriptable application windows offer this by way of the bounds
property just like the desktop's window
above:
tell application id "com.apple.Xcode" to tell ¬
window 1 to tell (a reference to its bounds)
set [X, Y, W, H] to its contents
set |𝚫𝓍| to W - screenW
set its contents to [X - |𝚫𝓍|, Y, W - |𝚫𝓍|, H]
end tell
This will right-align the window flush with the right edge of the screen, even if it's already fully visible on your screen. To have it only effect the move if it's required, then insert a condition such that |𝚫𝓍| > 0
.
The following is a functionally identical version of the last code block, but utilising statements that are formulated in a more explicit manner:
tell application id "com.apple.Xcode" to tell ¬
the front window to if (it exists) then
set [X, Y, W, H] to the bounds
set |𝚫𝓍| to W - screenW
set the bounds to [X - |𝚫𝓍|, Y, W - |𝚫𝓍|, H]
end tell
I added a check to make sure the front window
(which is identical to and equivalent terminology for window 1
) exists, so in cases where there are no windows, the script won't throw an error.
Here, the bounds
property is explicitly accessed by value whenever we need to retrieve or set its value, compared to the version above where the property was being accessed by reference. In this situation, there's no tangible difference between the two methods.
Upvotes: 2