Macro/Script: Choose File Given Optional Parameters

Continuing the discussion from Default folder location for Prompt for File action?:

Use Case

  • KM provides the Action Prompt for File.
  • Unfortunately, it does not allow the user to specify either the default folder nor the prompt text
  • This Macro provides both.
KM VARIABALES USED (optionally):
	• Local__ParentFolder 		[default]: defaults to last file open folder
	• Local__ChooseFilePrompt	[default]: "Choose FILE for KM Macro"
	• Local__FileType			[default]: ['public.item']

Example Output

image

Output only for Demo


MACRO:   Choose File using JXA @TEST

~~~ VER: 1.0    2019-05-05 ~~~

DOWNLOAD:

Choose File using JXA @TEST.kmmacros (25 KB)
Note: This Macro was uploaded in a DISABLED state. You must enable before it can be triggered.


ReleaseNotes

Author.@JMichaelTX

PURPOSE:

  • Provide KM Action/Script to Choose File
    • Provide Options for:
      • Default Folder
      • Prompt for Choose Dialog
      • Restriction of File Types Allowed

HOW TO USE

  1. First, make sure you have followed instructions in the Macro Setup below.
  2. Copy the Yellow Group Action "GRP: Actions to Choose File" into your Macro
  3. Change Each of the Three Parameters as needed for your Macro
  4. You can run this Macro as a demo if desired

MACRO SETUP

  • Carefully review the Release Notes and the Macro Actions
    • Make sure you understand what the Macro will do.
    • You are responsible for running the Macro, not me. ??
      .
  1. Assign a Trigger to this maro.
  2. Move this macro to a Macro Group that is only Active when you need this Macro.
  3. ENABLE this Macro.
    .
  • REVIEW/CHANGE THE FOLLOWING MACRO ACTIONS:
    (all shown in the magenta color)
    • Set OPTIONAL Parameters for Choose File Script

REQUIRES:

  1. KM 8.2+
  2. macOS 10.11.6 (El Capitan)

TAGS: @ChooseFile @Files @JXA @Scripting

USER SETTINGS:

  • Any Action in magenta color is designed to be changed by end-user

ACTION COLOR CODES

  • To facilitate the reading, customizing, and maintenance of this macro,
    key Actions are colored as follows:
  • GREEN -- Key Comments designed to highlight main sections of macro
  • MAGENTA -- Actions designed to be customized by user
  • YELLOW -- Primary Actions (usually the main purpose of the macro)
  • ORANGE -- Actions that permanently destroy Variables or Clipboards,
    OR IF/THEN and PAUSE Actions

USE AT YOUR OWN RISK

  • While I have given this a modest amout of testing, and to the best of my knowledge will do no harm, I cannot guarantee it.
  • If you have any doubts or questions:
    • Ask first
    • Turn on the KM Debugger from the KM Status Menu, and step through the macro, making sure you understand what it is doing with each Action.

image

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

JXA Script to Choose file

'use strict';
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

(function chooseFileKM() {    // ~~~ automatically executed when this script is executed ~~~
  
var ptyScriptName   = "Choose File Return POSIX Path"
var ptyScriptVer     = "2.3"  //  CHG to use KM Local Variables
var ptyScriptDate   = "2019-05-05"
var ptyScriptAuthor = "JMichaelTX"
/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PURPOSE:  Allow User to Choose File from Popup Window

RETURNS:  One of these, as text:
  • Actual Results of script if all goes well
    • POSIX path to selected file
    
  • "[USER_CANCELED]" at start of results if the user canceled something
  • "[ERROR]" at start of results if a script error occurred.
  
AUTHOR:  @JMichaelTX

KM VARIABALES REQUIRED:
  • Local__ParentFolder       [optional]: defaults to last file open folder
  • Local__ChooseFilePrompt  [optional]: "Choose FILE for KM Macro"
  • Local__FileType            [optional]: ['public.item']
  
  
TAGS:  @File @Prompt @Choose @Script @KM @JXA

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

var scriptResults = "TBD"  // Set your results to this var


try {
  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  
  // --- SET CURRENT APP VARIABLE NEEDED FOR DIALOGS & StandardAdditions.osax ---
  var app = Application.currentApplication()
  app.includeStandardAdditions = true
  
  //--- SET SYSTEM UI SERVER FOR USE WITH DIALOGS IN KM ---
  var susApp = Application('SystemUIServer');
  susApp.includeStandardAdditions = true;

  
  // --- SET KME APP VARIABLE NEEDED TO GET/SET KM VARIABLES ---
  //      (remove if not needed)
  var kme = Application("Keyboard Maestro Engine");  
  var kmInst = app.systemAttribute("KMINSTANCE");

  
  //--- GET KM VARIABLES ---  
  var defaultFolderPath   = kme.getvariable("Local__ParentFolder",  {instance: kmInst})       //|| "~/Documents";
  var choosePrompt         = kme.getvariable("Local__ChooseFilePrompt",  {instance: kmInst})   || "Choose FILE for KM Macro";
  var fileTypeStr         = kme.getvariable("Local__FileType",  {instance: kmInst})           || "public.item";

  fileTypeStr  = fileTypeStr.replace(/[\[\]"']/g, '');
  var  fileTypeList = fileTypeStr.split(/, |,/g)
    
  susApp.activate();
  
  if (defaultFolderPath === "") {
    
    var myFile = susApp.chooseFile({ 
      withPrompt:       choosePrompt,
      ofType:           fileTypeList
      })
      
  }
  else {
  
    defaultFolderPath = defaultFolderPath.replace("~", app.pathTo("home folder").toString())
  
    var myFile = susApp.chooseFile({ 
      withPrompt:       choosePrompt,
      defaultLocation:   defaultFolderPath,
      ofType:           fileTypeList
      })
    
  }
    
    /*
      Other File Types:
        • All File Types: ['public.item']
        • File Extension:  Use ext without period, like ["aup"]
        • Images:   ['public.jpeg', 'public.png']
        • Text:    ["public.text", "text", "public.html", "public.xml", "public.script"]
        • MS Word Documents:
            ["com.microsoft.word.doc", "com.microsoft.word.docx", "org.openxmlformats.wordprocessingml.document", "org.openxmlformats.wordprocessingml.document.macroenabled"]
        • see Apple System-Declared Uniform Type Identifiers for other "type" values
          https://developer.apple.com/library/ios/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
    */
    
  scriptResults = myFile.toString();
  
  //~~~~ END TRY ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

} catch (oError) {
  
  var msgLog;
  
  if (oError.errorNumber === -128) {  // User Canceled
  
    scriptResults =  "[USER_CANCELED]\n\n"
      + "SCRIPT: " + ptyScriptName + "   Ver: " + ptyScriptVer;
      
    msgLog = "User Canceled";
  }
  
  else {
    scriptResults = "[ERROR]\n\n"
      + "SCRIPT: " + ptyScriptName + "   Ver: " + ptyScriptVer + "\n"
      + "Error Number: " + oError.errorNumber + "\n"
      + oError.message
      
    msgLog = oError.message;
    
  } // END if/else
  
  
} // END catch
//~~~~ END TRY/CATCH BLOCK ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

return scriptResults

//======================== END OF MAIN SCRIPT =============================================



})();  // ~~~ function is automatically executed when this script is executed ~~~
1 Like