macOS: How to open the "Open with" menue from code? - macos

on macOS in Finder there is the option "Open with >" in the context menu of files, which shows a menu with all available apps being able to open the file. So the user can choose, with which app the file must be opened.
I would like to open this menu from code for a specific file.
In Windows it goes like this
Process.Start("rundll32.exe", "shell32.dll, OpenAs_RunDLL " + file);
but I can't figure out, how this goes in macOS.

Maybe you can adjust this following AppleScript code to suit your needs.
If you have a file selected in Finder, and you run this following code in Script Editor.app, it will open a dialog for you to choose a new application to open your selected Finder file with, then will open that file with your chosen app.
activate
set chosenApp to (choose application with prompt ¬
"Choose Your Preferred Default Application" as alias)
tell application "Finder"
set thisFile to selection -- The Selected File In Front Finder Window
set appID to id of chosenApp
try
open thisFile as text using application file id appID
on error errMsg number errNum
display dialog "Please Go Back And Select A File In Finder To Be Opened." & linefeed & ¬
"Then Come Back And Run This Code Again" buttons {"Cancel", "OK"} default button "OK"
end try
end tell

Steps:
Start the terminal by pressing command-space --> type in: terminal
when the terminal is running you switch to the applications folder:
'cd Applications'
You can run the apps like this: open -a GIMP-2.10.app
more info:
https://osxdaily.com/2007/02/01/how-to-launch-gui-applications-from-the-terminal/

Related

MacOS Terminal: Is it possible to create a "drag-and-drop" action via script?

There are many posts that explain how to drag-and-drop things into an open Terminal window. But what I would like to do is to tell Terminal to drag-and-drop a previously selected directory onto another application like VSCode or Renamer. I have not found any documentation for that. Is it at all possible? And if so, would somebody please point me to a documentation?
UPDATE:
I'd like to clarify my question with what I intend to do:
Pre requisites:
a "work folder" contains folders and files that shall be renamed
the renaming is done by an application called "A better finder renamer" (which allows presets)
An "Automator" (MacOS app) action shall imitate these steps:
the "work folder" is right clicked
the folder is drag-and-dropped onto the ABFR, which initiates the currently active preset
other actions via bash (like 'mv .//.* ./') ...
It is the "drag-and-drop" part of the Automator action that presents a riddle for me.
The "drag-and-drop" operation is manual operation. In AppleScript, instead the command to open the file or folder is given to the destination application itself.
Second thing to keep in mind. Getting Terminal's current working directory is easy with its do script "pwd" command. But the result of the do script Terminal command returned to the script is always the window tab, not the result of the pwd shell command. One solution is to redirect (remember) the result of pwd in a temporary text file.
set tempFolder to (path to temporary items folder from user domain)
set temp to POSIX path of tempFolder & "workingDirectory.txt"
tell application "Terminal" to do script ("pwd > " & temp) in selected tab of window 1
set curDirPosixPath to paragraph 1 of (read file ((tempFolder as text) & "workingDirectory.txt"))
set curDirHFSPath to curDirPosixPath as POSIX file as Unicode text
tell application "Visual Studio Code" to open curDirHFSPath
.
NOTE: other possible solution (I don't like) is parsing the text contents of Terminal window after pwd command execution. You can get contents using property contents (of selected tab of front window).
Open Automator, choose create New Document.
Choose create new Quick Action (service).
Set workflow receives current folders in any application.
From library Add Run AppleScript action. Edit it contents:
on run {input, parameters}
set curDirHFSPath to (item 1 of input) as text
tell application "Visual Studio Code" to open curDirHFSPath
end run
Save this Quick Action as service. Now when right-clicking the folder, opens the context menu, where you can choose and run this service.

Alfred Workflow to open a file in vim in the terminal

How can we write an alfred workflow to open a file from finder to a vim editor?
This is my first attempt to create a workflow in Alfred.
I am still learning and wanted to start with a simple workflow.
Here, I first created Hotkey and Keyword.
Open the Alfred3
Go to Workflows
Click + sign at the bottom left sidebar
Choose Blak Workflow
Name: Vim Launcher
Description: Opens a file in the terminal inside vim editor
1. Right-click > Trigger > press cmd-alt-v
2. Right-click > Inputs > Keyword > open in vim and title also open in vim
3. Right-click > Actions > Run NSAppleScipt
The copy and paste following contents inside Run NSAppleScipt
on alfred_script(q)
tell application "Terminal"
activate
do script "vim '" & q & "'"
end tell
end alfred_script
This workflow works but opens two terminals instead of one.
How can we fix this make so that it opens only one window?
The workflow summary is given below.
You want a Terminal Command action.
Just connect this object to your triggers and use vim "{query}" on it.
EDIT:
I'm editing the answer to reply a comment asking a follow-up question:
The workflow now create new termnial for each file, can we make it open in the same terminal if a terminal is already running?
In this case the Run NSAppleScript object could be used with the difference that we have to specify a location where do script should run, since it always open a new window if no location is specified:
on alfred_script(q)
tell application "Terminal"
if not (exists window 1) then reopen
activate
do script "vim '" & q & "'" in window 1
end tell
end alfred_script

How to delete the preview icon of a PNG file with AppleScript or the Terminal?

I am trying to automatically delete the preview icon of a PNG file (or many files) that I have generated with Photoshop.
I know how to manually do this: I can select the files, hit command+shift+i, select the icon on that window and hit the delete key to delete the files; but I would prefer to do this automatically with an AppleScript (or a Terminal command that I will then embed in my AppleScript with a do shell command)... I have searched the web for days but I have found nothing that helps me.
So, does anyone know of an AppleScript or Terminal command that could be used to delete the preview icon of a PNG (or JPEG) file?
You can use the setIcon method from the NSWorkspace class to delete icon of the file. https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace_Class/
A Cocoa-AppleScript Applet
use framework "AppKit"
use scripting additions
set myFiles to choose file with prompt "Select PNG files" with multiple selections allowed
set sharedWk to current application's NSWorkspace's sharedWorkspace()
repeat with tFile in myFiles
(sharedWk's setIcon:(missing value) forFile:(POSIX path of tFile) options:0)
end repeat
Or an AppleScript using a do shell script
set pyScript to quoted form of "from AppKit import NSWorkspace; import sys; NSWorkspace.sharedWorkspace().setIcon_forFile_options_(None, sys.argv[1].decode('utf-8'), 0)"
set myFiles to choose file with prompt "Select PNG files" with multiple selections allowed
repeat with tFile in myFiles
do shell script "/usr/bin/python -c " & pyScript & " " & (quoted form of POSIX path of tFile)
end repeat
Here's some links:
https://en.wikipedia.org/wiki/Cocoa_(API)
https://developer.apple.com/library/mac/releasenotes/ScriptingAutomation/RN-AppleScriptObjC/
https://en.wikipedia.org/wiki/PyObjC
JavaScript with Objective-C Bridge --> https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/Articles/OSX10-10.html

Applescript to ask for input, verify folder exists, and then open folder

I want to write a script using Automator that opens a folder in a particular location, after receiving user input. Doesn't have to be Applescript.
So the steps would be:
Dialog asking for Folder name
Verifying the folder exists
If exists, open folder in new finder window
if not exist, display message
Any help would be greatly appreciated.
instead of asking user to type folder name into a dialog box, why not use the standard "choose folder" which provide usual file/folder selection graphic interface ? on top of that, it will also make sure the folder selected exists !
Also it is possible to user instruction "if My_Folder exists then ..." to check if folder (or file) exists
Example of direct user selection : 5 first lines are asking folder selection in folder Documents and detect user cancellation. Next lines are just example to display result
try
set SelectFolder to choose folder with prompt "choose folder" default location "/Users/My_User/Documents"
on error number -128
set SelectFolder to ""
end try
if SelectFolder is "" then
display alert "user did not select a folder"
else
display alert "User selection is " & SelectFolder
end if
The following script does exactly what you're asking for.
on run
set thisFolder to (choose folder with prompt "Choose a folder...")
if folderExists(thisFolder) then
-- display dialog "The folder exists." buttons {"OK"} default button 1
tell application "Finder" to open thisFolder
else
display dialog "The folder has been deleted" buttons {"OK"} default button 1
end if
end run
on folderExists(theFolder)
tell application "Finder"
try
set thisFolder to the POSIX path of theFolder
set thisFolder to (POSIX file thisFolder) as text
--set thisFolder to theFolder as alias
return true
on error err
return false
end try
end tell
end folderExists
That said, note that a folder that has been selected using AppleScript's Choose Folder command must always exist. It can't be selected if it doesn't exist. Therefore, my first thought is that you don't need this, but if you need to check whether a folder exist for a different reason, then the folderExists function will do the job.
You could use the following script to do what you're asking for (no choose folder, this script uses a dialog like you asked for):
set folderChosen to text returned of (display dialog "Enter the path to the folder you want to open:" default answer "")
try
do shell script "ls " & folderChosen
do shell script "open " & folderChosen
on error
display alert "Folder Doesn't Exist" message "The folder path you entered doesn't exist. Make sure to enter a path, e.x. /Users/USERNAME/MyFolder." as critical
end try
This AppleScript uses do shell script "ls " & folderChosen to verify if the folder exists, and then opens the folder if ls successfully runs, indicating the folder path exists. Otherwise, it displays an alert with a warning sign explaining the path they entered doesn't exist.
If you want this to run in automator, you could use Automator's Run AppleScript feature.
I hope this solution helps you solve your problem!

Is there a way to trigger Finder's "quick look" window with Applescript?

I am using Applescript to automate some tasks in the OSX Finder. The script opens up a folder and selects the first image in that folder. I would like it to also bring up the "quick look" window (exactly as if the user had pressed the space bar).
I did find a way to fire up quick look from the command line using qlmanage, but that brings up a static quick look window, which is no longer tied to the finder selection.
Code so far:
property folderPath : "/Volumes/Media/Images"
on run {}
tell application "Finder"
activate
set imageFolder to folder (folderPath as POSIX file)
set imageFile to first item of imageFolder
select imageFile
-- show quick look?
end tell
end run
If you don't want to do it by scripting the Finder you can run the following shell command
qlmanage -p thefile
In an Applescript you might do this like
do shell script "qlmanage -p " & "thepath/thefile"
Depending upon what you are doing this might be much easier. Especially if you primarily just have a set of paths.
If you have an existing Applescript path you can send it like this
set p to POSIX path of mypath
do shell script "qlmanage -pr " & quoted form of p
Updated (with thanks to Kevin Ballard):
tell application "System Events" to keystroke "y" using command down
Note: this requires that "enable access for assistive devices" is selected in the "Universal Access" control panel.

Resources