I've been working on an application in Automator that changes the desktop background to the album art of the current song playing in iTunes.
You can download my first version here.
The most annoying issue I have found is that when there is a full screen app open on the same display being updated, whenever the song changes the background flickers between the current song and the previous.
This is my current code (Updated from version 1.0 above):
You may need to scroll within the code to see all of it.
tell application "System Events"
set fileName to (((path to desktop) as text) & ".iTunesArt2-1.jpg")
set oldFile to open for access file fileName with write permission
write 0 to oldFile
close access oldFile
delete file fileName
if process "iTunes" exists then
tell application "iTunes"
if (player state is not stopped) then
-- get the raw bytes of the artwork into a var
tell application "iTunes" to tell artwork 1 of current track
set srcBytes to raw data
end tell
-- write to file
set outFile to open for access file fileName with write permission
-- truncate the file
set eof outFile to 0
-- write the image bytes to the file
write srcBytes to outFile
close access outFile
end if
end tell
tell desktop 2
set picture to fileName
end tell
end if
set fileName to (((path to desktop) as text) & ".iTunesArt2-2.jpg")
set oldFile to open for access file fileName with write permission
write 0 to oldFile
close access oldFile
delete file fileName
if process "iTunes" exists then
tell application "iTunes"
if (player state is not stopped) then
-- get the raw bytes of the artwork into a var
tell application "iTunes" to tell artwork 1 of current track
set srcBytes to raw data
end tell
-- write to file
set outFile to open for access file fileName with write permission
-- truncate the file
set eof outFile to 0
-- write the image bytes to the file
write srcBytes to outFile
close access outFile
end if
end tell
tell desktop 2
set picture to fileName
end tell
end if
end tell
I got the actual code that saves the artwork to a file from here.
The desktop will not update unless you give it a new file name to update, therefore I have duplicated the process with "iTunesArt2-1" and "iTunesArt2-1".
The first 2 in '2-1' or '2-2' simply means the second desktop, as I have two different applications to change each desktop, and use my 2nd desktop for testing.
The entire application is set to loop for 1000 years, using three separate Loop functions in Automator (720 minutes, 730 times & 1000 times).
When first trying to debug this issue, the process was duplicated into four separate scripts, one for saving the image, then setting as background, and two more scripts to repeat the process with a new file name.
Here's an example of my debugging:
I remove the opening period from ".iTunesArt##.jpg" so that I can see the files on my desktop.
I play a Coldplay song and run the application in Automator to set the background.
"iTunesArt2-1.jpg" and "iTunesArt2-2.jpg" are shown on my desktop with the correct album art.
I stop the application, and play a Paramore song.
I run the first script of the application (Saves the album art).
"iTunesArt2-1.jpg" is updated to the Paramore artwork.
I run the second script of the application (Sets background image).
Note, this script should be setting the background to the Paramore image.
The background remains set to the Coldplay image.
At first I think this is only because the background image was already set to "iTunesArt2-1.jpg", and therefore the system will not try to update it again, not knowing the data in the file has been changed.
So I run the next script which should force the background to update:
I run the third script in the application.
"iTunesArt2-2.jpg" is updated to the Paramore artwork.
I run the forth script in the application.
The desktop background is updated to the Paramore artwork.
So, we can confirm that scripts 3 & 4 worked correctly.
According to the code, when the application loops back to scripts 1 & 2, the desktop background should remain as the Paramore artwork.
BUT...
I run the first script in the application.
"iTunesArt2-1.jpg" remains the Paramore artwork (as it should).
I run the second script in the application.
This script should update the desktop background from ""iTunesArt2-2.jpg" (Paramore) to "iTunesArt2-1.jpg" (Paramore).
The desktop background changes to the Coldplay artwork.
Now that makes zero sense at all.
This will happen every time I loop through the scripts.
Script 4 will change the desktop to Paramore and script 2 will change it back to Coldplay.
Remember this issue only happens when there is a full screen app open on the same display being updated. ie. A full screen app open on my primary display doesn't matter.
I have found sometimes that sliding over to the full screen app and 'activating' it will stop the flickering, and the background will be set correctly.
There surely is nothing 'wrong' with my code is there? If not, I need a way to get around this issue.
Specifically, is there a way of 'activating' every full screen app in the background without moving to those spaces?
I would love anyone who wants it to have this program, but it needs to be able to run under all circumstances.
Any help would be greatly appreciated.
Found a work around which creates a random file name each time, meaning the desktop can't get confused as to which image it is supposed to display.
screenNum refers to which screen the desktop is being set to.
set randID to screenNum
set randLoop to 0
repeat while randLoop is not 9
set randNum to (random number from 0 to 9) as text
set randID to randID & randNum
set randLoop to randLoop + 1
end repeat
Then included randID in the file name upon its creation.
Have not noticed any flickering using this method.
Note: This solves my problem, but does not answer my initial question of how one can activate a full screen app in the background.
Related
I have a massive spreadsheet with a titanic number of rows/columns (e.g. ~250 columns, many thousands of rows) that I'm trying to convert into PDFs by looping through each row with AppleScript, copying that row's ~250 variables to TextEdit set to Rich Text (for bold formatting etc), and then using System Events to save the txt as a PDF. Here's a summary of the code:
on run
set initialRow to 1
tell application "System Events"
tell application process "TextEdit"
set frontmost to true
end tell
end tell
repeat
tell application "Microsoft Excel"
-- CLEAR MY ~250 VARIABLES FROM PREVIOUS ROW'S VALUES TO MAKE SURE NOTHING IS CARRIED OVER BY MISTAKE
-- THEN SET MY ~250 VARIABLES TO THE NEXT ROW'S VALUES
if exampleValue is "" then exit repeat
end tell
tell application "TextEdit"
set the text of the front document to ""
-- THEN SET FIRST PARAGRAPH TO MY FIRST VARIABLE PLUS A LINE BREAK SO THEN THERE'S A NEW PARAGRAPH FOR THE NEXT VARIABLE, ETC
-- THEN GO THROUGH ALL OF MY VARIABLES TO IMPORT THE IMPORTANT ONES INTO TEXTEDIT, SET SOME FORMATTING, ETC.
end tell
delay 1
tell application "System Events"
click menu item "Export as PDF…" of menu 1 of menu bar item "File" of menu bar 1 of application process "TextEdit"
delay 1
keystroke exampleValue -- SYSTEM EVENTS TYPES THE NAME OF THE PDF
delay 1
key code 36
delay 1
end tell
set myRow to (myRow + 1)
end repeat
end run
This all runs great, no bugs (seemingly!), no issues at all in small doses. The problem, however, is that something happens as the script runs where it seems to be tying up more and more memory somewhere; everything is fine for the first hundred or so rows, but at some point my Mac stops running anything at all, i.e. whether I let the script run until it starts producing super random errors (I could collect them if helpful, but it's like a random different error each time so not much help there) or even if I let the script run for a while and then stop it before it errors out - it will let me stop the script but then I can't actually quit out of Script Editor or TextEdit or Excel, my keyboard stops working, I can't Force Quit anything, can't Reset the computer, etc. It's just a complete meltdown of the machine unlike anything I've encountered, and the only way to get back to work is to force a hard boot with the power button.
I've never had this problem with my other scripts, but I also don't usually use System Events, so my hunch is that it's something to do with that. Do I need to be 'resetting' System Events somehow, or clearing out the memory for some reason, or...? Thanks for the help!!
Figured it out! After trying the script one more time with Activity Monitor running, I discovered that each time it iterates through, 3 new processes were popping up - Core Sync, Dropbox Finder Extension, and SnailSVNLite - and then never going away! So if I ran through the script 500 times, I'd end up with 1500 new processes running, which was almost certainly what was wrecking me though I have no idea why telling System Events anything was doing that. I looked around online, and it turns out those are all Finder Extensions that had been turned on at some point long ago, so just needed to go to System Preferences > Extensions > Added Extensions and then uncheck those 3 extensions - and then problem solved!!
I'm trying to write a script to correct the path to an original item of a file alias. I know what's wrong with the path (I moved a folder), so if I can get what the system thinks the path is, I can fix it.
The problem is that the script simply reports that the original can't be found and not where the original should be.
Is there a way to grab that from with AppleScript? It's there in the Get Info... box, so it's stored in the file. I suspect I could use some bash way to get it with a do shell script, but I'm curious about staying within AS.
Years ago, I also had issue with my alias, when changing folders. This is part of the script I made which looks into Get Info window. Since, may be the Get Info window has been changed on last OS version, therefore, some adjustments are required, but it gives you the direction to go:
on Origine_Alias(F_Alias)
set R to ""
tell application "Finder" to open information window of file (F_Alias as text)
tell application "System Events" to tell process "Finder" to set R to value of static text 18 of scroll area 1 of front window
tell application "Finder" to close front window
return R
end Origine_Alias
The returned string is in Unix format: /folder/my/file
I record a lot of videos, so I have a MacBook Pro with two monitors connected. One of those monitors has a resolution set to 1920x1080. I record all my videos from that specific monitor. Right now, I run Google Chrome and Visual Studio Code. Then, I resize the windows for the specific conditions of my recording (sometimes Chrome uses more space, sometimes VSC does), so this is not a matter of simply doing a side-by-side setup where each app takes up a certain percentage.
That manual process is tedious and I usually want them to be a very specific size based on what I am recording. That is why I want to use AppleScript to simply resize the currently running applications based on various recording scenarios.
To create a test case, I wrote the following code. While it does the trick of perfectly resizing the app, it moves Chrome from the monitor I am recording on to my MacBook Pro's connected display.
Here is what I wrote so far:
set theApp to "Google Chrome"
set xLocation to 0
set yLocation to 0
set appWidth to 750
set appHeight to 1080
tell application "Google Chrome"
set bounds of front window to {0, 0, appWidth, appHeight}
end tell
Unfortunately, I am very new to AppleScript and have not been able to figure out how to prevent the script from moving the app (Google Chrome in this case) from the current monitor to the MacBook Pro monitor. I suspect it is that front window code, but I am struggling to learn how that works as I cannot find the documentation.
How can I use AppleScript to resize an application that is currently running without moving the application's window to another monitor?
I suppose if the answer is to open a new copy of the application, that would work too, so long as I can open or move it to the proper monitor. Thanks!
Update
Close, but not quite there...
I was provided this link in the comments. The code looks like this:
set theScreens to paragraphs of (do shell script "system_profiler SPDisplaysDataType -detailLevel |grep \"Resolution:\" | awk -F\"Resolution: \" '{print $2}'")
set theMonitor to ""
log theScreens
set the counter to count of theScreens --- set to 1 if you want to test it on monitor 1
if (counter) > 1 then
-- we will do things for monitor 2
set thisDisplayWidthHeightMonitor_2 to {(word 1 of item 1 of theScreens) + 2, 0, ((word 1 of item 1 of theScreens) + (word 1 of item 2 of theScreens)), word 3 of item 2 of theScreens}
set theMonitor to thisDisplayWidthHeightMonitor_2
else
-- we will do things for monitor 1
set thisDisplayWidthHeightMonitor_1 to {0, 0, (word 1 of item 1 of theScreens), (word 3 of item 1 of theScreens)}
set theMonitor to thisDisplayWidthHeightMonitor_1
end if
tell application "Safari"
activate
make new document with properties {URL:"http://netflix.com"}
set bounds of window 1 to theMonitor
log theMonitor
end tell
tell application "System Events"
tell application process "Safari"
set value of attribute "AXFullScreen" of window 1 to true
end tell
end tell
If I log the variable theScreens, I get the following result:
(*3072 x 1920 Retina, 3840 x 2160 (2160p/4K UHD 1 - Ultra High Definition), 4608 x 2592*)
That code does not show me the correct x position I need for my window placement. It just shows the monitors I am using and their UHD resolution.
When the code opens Safari (in this case), it sets the bounds with the variable theMonitor, and it does indeed open in the monitor I want it to. The output is:
3074, 0, 6912, 2160
Since the code does display the application in the monitor I want, I assume that 3074 is the correct x position for my need, so here is my updated code:
tell application "Google Chrome"
set bounds of front window to {3074, 0, 750, 1080}
end tell
Unfortunately, Google Chrome completely disappears off the screen and is nowhere to be found on any monitors or desktops. I have to quit Chrome and restart so I can use it again (or do the change the change-the-screen-resolution trick).
I am still left with the following question: How do I open the app in the correct monitor I desire and in the x & y location I desire?
As you can see from my code below I am extremely new to this. My code just about works, but my major issue is that it hogs up Finder and sometimes it does not set the Desktop picture, but does most of the time!
The script just monitors a folder, and if an "***.jpg" is added then the Desktop picture set to it.
This is my very first script so I have a lot to learn,
set reset to ""
display notification "Alarm Front Active " & (current date) as string
tell application "Finder"
set path_to_sourceFull to ":photo:FRONT CAM 1:20190929:images" -- from nsa310 network drive
set path_to_source to ":photo:FRONT CAM 1:20190929:images" -- from nsa310 network drive
set directory1 to "/Volumes/photo/FRONT CAM 1/20190929/images" as text -- from nsa310 network drive
set path_to_destinationFull to "Macintosh HD:Users:rekordbox:Documents:temp folder 2"
set path_to_destination to ":Users:rekordbox:Documents:temp folder 2"
set directory2 to "/Users/rekordbox/Documents/temp folder 2" as text
repeat while reset = ""
set allok to ""
set filelist to name of every item in folder path_to_source --of startup disk
set listSizesaved to count of filelist
delay 1
repeat while allok = ""
set filelist to name of every item in folder path_to_source --of startup disk
set listSize to count of filelist
if listSize = listSizesaved then
else
set filelist to name of every item in folder path_to_source --of startup disk
set listSize to count of filelist
set LastAddedFile to item listSize of filelist
set allok to "ALARM"
set listSizesaved to listSize -- (save the updated) count
set activefile to (path_to_source & LastAddedFile)
set selectedpicture to (directory1 & "/" & LastAddedFile)
tell application "System Events" to tell every desktop to set picture to selectedpicture
delay 1
display notification "ALARM FRONT TRIGGERED...." & (current date) as string
delay 1
end if
end repeat
end repeat
end tell
The script you want, I think, is this:
on adding folder items to thisFolder after receiving filelist
set droppedFile to first item of filelist
tell application "System Events"
tell every desktop
set picture to droppedFile
end tell
end tell
end adding folder items to
(I've left out the 'Alarm' bit, since I wasn't sure what the point of it was.)
To use this script, copy it into Script Editor, save it in the folder ~/Library/Scripts/Folder Action Scripts/, then open the applet 'Folder Actions Setup'. Add the folder you want on the left-hand side, and choose the file you just saved on the right. It should look something like this:
...where the checkmark on the left shows that folder actions are enabled for the folder (which I called 'test folder') and the script (which I called 'FADtop.scpt') is attached.
Drop an image in the folder, and it should just work.
As a general rule, don't script the Finder unless you absolutely need to; always use System Events. The Finder is a busy app, and scripting it can gum up the system. And also try to avoid this design pattern:
(* Don't do this! *)
repeat
(* test for something *)
delay x
end
The delay command is not particularly resource-efficient. If you really want to use a polling system to test for some event, it's often better to create a stand-alone app with an on idle handler. That way you let the system wake and sleep the script, with significant performance improvements.
EDIT
Since folder actions don't seem to be working with ftp drops onto remote drives, here's a reasonably efficient folder-polling approach. Save the following script as a stay-open application (choose 'Application' as the file type, and click the 'stay open' checkbox). Then launch the application and leave it running in the background.
property dateOfLastFileChosen : missing value
property targetFolder : "/Volumes/photo/FRONT CAM 1/20190929/images"
property idleTime : 300 -- 300 seconds is five minutes
on run
end run
on idle
tell application "System Events"
if exists folder targetFolder then
if dateOfLastFileChosen is missing value then
set recentFiles to every file of folder targetFolder whose visible is true
else
set recentFiles to every file of folder targetFolder whose modification date > dateOfLastFileChosen and visible is true
end if
set newFile to my mostRecentFileOfList(recentFiles)
if newFile is not missing value then
set dateOfLastFileChosen to modification date of newFile
tell every desktop
set picture to (POSIX path of newFile)
end tell
end if
end if
end tell
return idleTime -- check every 5 minutes (300 seconds)
end idle
on mostRecentFileOfList(fileList)
set maxDateObj to missing value
repeat with thisFile in fileList
if maxDateObj is missing value then
set maxDateObj to contents of thisFile
else if modification date of thisFile is greater than modification date of maxDateObj then
set maxDateObj to thisFile
end if
end repeat
return maxDateObj
end mostRecentFileOfList
Without trying to steal the thunder from #Ted Wrigley, whose solution provided the AppleScript code for the folder action, I felt there were enough comments and items for me to add to post it as another answer to the OP's dilemma.
First I will address the tell every desktop set picture to droppedFile lines of code in the following AppleScript Folder Action. If the user has only one monitor/display attached to the computer, but has created several different "Spaces", the tell every desktop set picture to droppedFile lines of code will only change the Desktop Picture for the Desktop of the current active "Space" only. The other Desktop backgrounds will not be changed. However, if the user has several monitors/displays attached to the computer, the tell every desktop set picture to droppedFile lines of code will change the Desktop Pictures for the Desktops of the current active "Space" for each attached monitor/display. If the latter is not the desired result, then tell every desktop should be changed to tell current desktop.
After testing the AppleScript Folder Action code provided by #Ted Wrigley, I noticed the image file being downloaded from an FTP server, to the test folder where I have the folder action script attached to, looked like this before the image was actually finished transferring. Because the file was kind of there and not there, it did not trigger the Folder Action.
Next, I figured I would add a delay to be beginning of the Folder Action code to allow for the transfer of the image file from the FTP server, to complete. I added a delay of 180 seconds to allow for the transfer to complete and it worked. When the transfer was complete, the file look like this.
Depending on how many files you foresee being transferred at any given time along with factoring in for file sizes... It's possible you may need to significantly increase the Delay time.
on adding folder items to thisFolder after receiving theseFiles
delay 180
set newBackground to first item of theseFiles
tell application "System Events"
set picture of current desktop to newBackground -- Single Display Attached
--set picture of every desktop to newBackground -- Multiple Displays Attached
end tell
end adding folder items to
I have a bulk amount of images, of which i need to remove alpha from each. This is doable from Preview application, but the sheer amount of times i would need to repeat that is way too time consuming.
I have heard about AppleScript and made some feeble attempts at automating the process, currently to no avail.
i am using something like this and then starting a repeat, but it only allows me to loop through one direct folder (also i'm having troubles with menu bar items)
set fl to files of folder POSIX file "/Users/user/Documents/" as alias list
But i have multiple folders within folders which i wish to change an amount of images. the folder structure is like this:
Users/user/folder/ImagesRoot/
in inside ImagesRoot are 3 folders and one txt file. I want to specifically select 2 of the folders called "Icons" and "Screenshots". In "Icons" is 5 images. However "Screenshots" contains 3 subfolders, each with their own 5 images. (can be referred to as "Screensub 1,2,3")
Once receiving the list of images inside such folder, the process would be something like
tell application "Preview"
open the image file
open the file menu
open export...
untick alpha
press save
press replace
close window
end tell
Loop to next one
when looped through all in Icons folder, do all 5 images of each subfolder of screenshot folder
I am told that AppleScript is a good way to do this, but also that bash is a possibility?
However, i have 2% experience with applescript and maybe 4% of bash, and don't know how to approach it.
Any advice or help would be greatly appreciated.
Thanks
As far as I can tell, Preview doesn’t have the ability to change the alpha of a document, even if you enable AppleScripting. In an application that does support it, such as GraphicConverter, this is a fairly simple task:
on open imageFile
tell application "GraphicConverter 9"
open imageFile
tell window 1
set alpha to false
end tell
--save image as needed
end tell
end open
You may find it easier to use Automator. The combination of Get Folder Contents with Repeat for each subfolder found and Alpha Channel set to Remove may be all you need. If you need to exclude some files, Filter Finder Items would do it.
If you want to use Preview, however, you may be able to use System Events. Something like:
on open imageFile
tell application "Preview"
open imageFile
activate
set filename to name of window 1
tell application "System Events"
tell process "Preview"
click menu item "Export…" of menu "File" of menu bar 1
tell sheet 1 of window 1
--rename file
set value of text field 1 to filename & " Alpha Removed"
--uncheck alpha channel
tell checkbox 1 of group 1
click
end tell
--save
click button "Save"
end tell
end tell
end tell
end tell
end open
If you choose the assistive access route, you may find Apple’s help on signing applications useful: http://support.apple.com/kb/HT5914