An AppleScript to to find IAdjusted Settings of Variants

Discussion regarding all scripting related questions
Please DO NOT post to this thread anything that is not directly related to scripting of Capture One.

An AppleScript to to find IAdjusted Settings of Variants

Postby Eric Nepean » Wed Sep 12, 2018 1:37 pm

I recently found that I had many variants with the CO "Adjusted" set, but where in fact the adjustments had been set back to default values.
Then I needed a script which would list all the a"modified" adjustments of variants - I put this data in the variant metadta as well as the log tso that I could use Filter Tool to select images based on adjsutment tags.

I think this may be generally useful, so I publish the script here.

Code: Select all
## Feel free to reuse even for commercial purposes but please give me credit where possible

## absolutely needed for reliable operation
use AppleScript version "2.4"
use scripting additions

set resultLogging to true -- log non default adjustments in thee script editor log
set runAllTests to true -- if false, stop checking for adjustments after the first no-defult setting is found
set resultsInCollections to false -- add adjusted and non-adjusted images to a collection
set AdjustmentLabelsInMetadata to true -- Information is added to the IPTC Getty Images fields - what and how many Adjustments are detected
set AdjustmentValuesInMetadata to true -- Information is added to the IPTC Contacts fields - adjustment values the user wants to search on
set logEveryAdjustment to false -- report every setting value in the script editor log -  very long listing - do this only for a few images

## FUNCTIONS
## if there are no selected variants, all variants in the current collection are processed
## !!! Progress updates are given at the very bottom line of the Script Editor window
## the script reports "Adjusted" or "Not_Adjusted" in "Getty Parent MEID" field
## The script finds adjustment values by getting the adjustments of the variant
## The script also finds adjustments by getting the crop, LCC Name, number of layers and number of styles of the variant
## the script reports the number of adjustments in the "Getty Original File Name" field
## the script lists the adjustment tags with non-default settings in the "Getty Personalities" field
## the script checks for adjustments by copying adjustments to the clipboard, and then checking if the "Apply Adjustments" button is enabled
## If the clipboard contains adjsutments, then "clipBoard contents" is listed as an adjsutmenet, and counted as one.
## The script either logs nothing, only non default adjustments, or every adjustment value
## The script may put some adjustment values in the IPTC Contact metadata fields.
## Typical speed - 0.8 to 3 seconds per variant, depending on the size of the album


## PURPOSE AND USE
## list all the adjustments of a variant, or a few variants
## Identify variants where all adjustments have been set to default but the variant still has the CO "Adjusted" tag
## survey adjustment values used in the catalog

## KEY USE CASES (Filter tool is a great help finding these)
#### 1) the script has reported "Not_Adjusted" in "Parent MEID", but the CO "Adjusted" tag is true (and "Personalities" is empty). --> reset adjustments
#### 2) the script reported "Adjusted" in "Parent MEID" but reports only 1 adjustment in "Original File Name", and "ClipBoard Contents" is listed in "Personalities"
######  There are either adjsustments presnt which cannot be obtained through the adjustment property (e.g. vignetting), or adjustments have been set to the default value without resetting the tool
###### The adjustments should be copied to the clipboard and individually checked. In some cases adjustments may be set to defaults, then a manual reset of adjustments is equired.
#### 3) The CO "Adjusted" tag is false, but the script has reported "Adjusted". The script is missing a default setting value for the camera type
###### The list of camera specific default values in the script needs to be updated with the setting value, and the script run again.

## CONFIGURATION
## Accessibility MUST be enabled for Script Editor
## The tool bar MUST be configured so that the "Copy Adjustments" and "Apply Adjustments" buttons are present
## For the script to find these buttons it depends on the buttons help text and English (USA) localization
## In other localisations the strings "helpTextCopy" and "helpTextApply" must be updated
## If localisation changes the name of adjsutment properties, then this must also be updated

## When running this with 1000's of variants, configure as follows:
## set script editor preferences so the scripts do not log if the log window is not visible
## close the script editor log window (capturing too much log info can cause crashes)

## For faster operation with 1000's variants:
#### close the Capture One Viewer window
#### copy the selected variants to a new album if possible
#### ensure that Filter tool or a Smart Album is not working on the IPTC data fields that the script changes
#### ensure that Filter tool is not visible when the script is running

##Version Notes
## Version September 11, 2018
## Replaced handler "recordLabelsAndValues4" by "recordLabelsAndValues3" to fix some strange crashes.

set adjustedCounter to 0
set notadjustedCounter to 0

set progress description to "Setting Up"
tell application "Capture One 11"
   set theSelectedVariantList to get selected variants
   if 0 = (count of theSelectedVariantList) then
      set theVariantList to every variant
   else
      set theVariantList to theSelectedVariantList as list
   end if
   set currentDocRef to get current document
   set currentDocName to (get name of current document)
   tell currentDocRef to set currentCollName to (get name of current collection)
end tell
set theVariantCount to get count of theVariantList

if resultLogging then
   tell application "Finder"
      set script_path to path to me
      set Script_Title to name of file script_path as text
   end tell
   log {"Script: " & Script_Title, "Document: " & currentDocName, "Collection: " & currentCollName, "Variants: " & theVariantCount}
end if

if resultsInCollections then
   set Result_ProjectName to "ScriptSearchResults"
   InitializeResultsCollection(Result_ProjectName, "NotAdjusted")
   tell application "Capture One 11" to copy ref2ResultAlbum to ref2NotAdjustedAlbum
   InitializeResultsCollection(Result_ProjectName, "IsAdjusted")
   tell application "Capture One 11" to copy ref2ResultAlbum to ref2IsAdjustedAlbum
end if

set helpTextCopy to "Copy adjustments from the primary variant"
set helpTextApply to "Apply adjustments to all selected variants"

tell application "System Events"
   repeat with theTbarGroup in (get groups of toolbar 1 of window "Main5M" of application process "Capture One 11")
      tell theTbarGroup
         set theHelpListOfTbarGroupButtons to (get help of buttons)
         if (theHelpListOfTbarGroupButtons contains helpTextCopy) and ¬
            (theHelpListOfTbarGroupButtons contains helpTextApply) then
            set theCopyButton to button (get my getIndexOf2(helpTextCopy, theHelpListOfTbarGroupButtons))
            set theApplyButton to button (get my getIndexOf2(helpTextApply, theHelpListOfTbarGroupButtons))
            exit repeat
         end if
      end tell
   end repeat
   try
      {theCopyButton, theApplyButton}
   on error
      error "Couldn't find the \"Copy\" and \"Apply\" buttons on Capture Ones Main Toolbar"
   end try
end tell

set progress description to "Evaluating "
set progress total steps to theVariantCount
set variantCounter to 0
set lastClipBoardState to false
set Mark_Start to GetTick_Now()

repeat with theVariant in theVariantList
   tell application "Capture One 11" to select currentDocRef variant theVariant -- Step 1/3 do this early to give C1 time to react
   
   set variantCounter to variantCounter + 1
   set progress completed steps to variantCounter
   set Mark1 to GetTick_Now()
   set variantIsAdjusted to false
   set adjustmentList to ""
   set adjustmentListTag to ""
   set hasWBpresetAuto to false
   set hasDistCrop to false
   set countAdjustments to 0
   set theProperties to {} as list
   set therecordLabels to {} as list
   set therecordValues to {} as list
   
   set theVariantName to my getVariantNameNum(theVariant)
   set theImageType to getVariantsImageType(theVariant)
   tell application "Capture One 11" to tell parent image of theVariant to set {theCameraModel, theEXIFISO_T} to get {EXIF camera model, EXIF ISO}
   
   tell application "System Events" to click theCopyButton -- Step 2/3
   
   if 1 < variantCounter then
      set remainingTime to " " & roundDecimals(((Mark2 - Mark_Start) / variantCounter * (theVariantCount - variantCounter + 1)) / 60, 1) & " minutes remaining " & (round ((Mark2 - Mark_Start) / variantCounter * 1000) rounding to nearest) & "ms per variant" & " Last: " & lastTime
   else
      set remainingTime to ""
   end if
   set progress additional description to ("#" & variantCounter & " " & theVariantName & remainingTime)
   
   ## These are the default default adjustment values before image file format and camera version is considered
   ## Mostly these are the defaults for a JPG file
   
   set DistortedPixelMarginPercent to 0.5
   set defaultSharpeningAmount to 0.0
   set enableSharpeningAmount to true
   set defaultSharpeningRadius to 0.800000011921
   set enableSharpeningRadius to true
   set defaultNoiseReductionLuminance to 0.0
   set enableNoiseReductionLuminance to true
   set defaultNoiseReductionColor to 0.0
   set enableNoiseReductionColor to true
   set defaultNoiseReductionSinglePixel to 0.0
   set enableNoiseReductionSinglePixel to true
   set defaultColorProfile to ""
   set enableColorProfile to false
   set defaultFilmGrainImpact to 0.0
   set enableFilmGrainImpact to true
   set defaultFilmCurve to "Auto"
   set enableFilmCurve to false
   set defaultSharpeningThreshold to 1.0
   set enableSharpeningThreshold to true
   set defaultWhiteBalancePreset to "Shot"
   set enableWhiteBalancePreset to true
   
   
   if "JPG" = theImageType then
      ## Default settings for a JPG file
      set defaultColorProfile to {"Jpeg File neutral", "From File"}
      set enableColorProfile to true
      
   else if {"TIF", "TIFF"} contains theImageType then
      ## Default settings for a TIFF file
      set defaultFilmCurve to {"Tiff File neutral", "Auto"}
      
   else if "RW2" = theImageType then
      ## Default settings for a Panasonic RAW file
      set DistortedPixelMarginPercent to 8.34 -- 1/12 of the image -  15% of the image worst case
      set defaultSharpeningAmount to {120.0, 140.0, 160.0, 180.0, 200.0, 240.0, 280.0}
      set defaultSharpeningRadius to 1.0
      set defaultSharpeningThreshold to {1.0, 1.5}
      set defaultNoiseReductionLuminance to 50.0
      set defaultNoiseReductionColor to 50.0
      set defaultNoiseReductionSinglePixel to {0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0}
      set defaultFilmCurve to {"Film Standard", "Auto"}
      set enableFilmCurve to true
      set defaultFilmGrainImpact to {0.0, 5.0, 10.0, 15.0, 20.0, 25.0}
      set defaultColorProfile to {"Panasonic DMC-GM5 Generic", "Panasonic DMC-G5 Generic", "Panasonic DMC-GX7 Generic", "Panasonic DMC-GX1 Generic", "Panasonic DMC-GX8 Generic", "Panasonic DMC-GM1 Generic", "Panasonic DMC-G1 Generic"}
      set enableColorProfile to true
      if theCameraModel contains "GX1" then
         set defaultSharpeningRadius to {1.0, 1.299999952316}
      end if
      
   else if "ORF" = theImageType then
      ## Default settings for an Olympus RAW file
      set DistortedPixelMarginPercent to 8.34 -- 1/12 of the image -  15% of the image worst case
      set defaultSharpeningAmount to {120.0, 140.0, 180.0, 200.0}
      set defaultSharpeningRadius to 1.0
      set defaultNoiseReductionLuminance to 50.0
      set defaultNoiseReductionColor to 50.0
      set defaultNoiseReductionSinglePixel to {0.0, 10.0, 20.0, 40.0, 50.0}
      set defaultColorProfile to "Olympus E-M1 Generic"
      set enableColorProfile to true
      set defaultFilmGrainImpact to {0.0, 7.0}
      set defaultFilmCurve to "Auto"
      set enableFilmCurve to true
      
   else if "CR2" = theImageType then
      ## Default settings for an Canon RAW file
      set defaultNoiseReductionLuminance to 50.0
      set defaultNoiseReductionColor to 50.0
      set defaultFilmCurve to "Auto"
      set defaultSharpeningAmount to {150.0, 160.0}
      set defaultWhiteBalancePreset to {"Auto", "Shot"}
      if theCameraModel contains "G9" then
         set defaultSharpeningRadius to 0.800000011921
      else if theCameraModel contains "G11" then
         set defaultSharpeningRadius to 1.299999952316
      end if
      
   else if "ARW" = theImageType then
      ## Default settings for a Sony RAW file
      set DistortedPixelMarginPercent to 8.34 -- 1/12 of the image -  15% of the image worst case
      set defaultSharpeningAmount to 180.0
      set defaultSharpeningRadius to 0.800000011921
      set defaultNoiseReductionLuminance to 50.0
      set defaultNoiseReductionColor to 50.0
      set defaultColorProfile to "Sony A7S Generic"
      set enableColorProfile to true
      
      ## else if    add some other camera here
   end if
   
   tell application "Capture One 11" to set {{theCropHorCenter, theCropVerCenter, theCropWidth, theCropHeight}, theLCCName, countStyles, countLayers, {theImageWidth, theImageHeight}} to ¬
      get {crop, applied LCC name, (count of styles), (count of layers), (dimensions of parent image)} of theVariant
   
   
   if not (0 = countStyles) then
      set variantIsAdjusted to true
      set countAdjustments to countAdjustments + 1
      set adjustmentListTag to adjustmentListTag & "Styles Applied;"
      if logEveryAdjustment then
         tell application "Capture One 11" to set theStyleList to get styles of theVariant
         set adjustmentList to adjustmentList & "Styles applied: " & joinListToString(theStyleList, "; ") & return
      else if resultLogging then
         set adjustmentList to adjustmentList & "Has " & countStyles & " Styles applied" & return
      end if
   else if logEveryAdjustment then
      set adjustmentList to adjustmentList & "No Styles applied" & return
   end if
   
   if (1 < countLayers) then
      set variantIsAdjusted to true
      set countAdjustments to countAdjustments + 1
      set adjustmentListTag to adjustmentListTag & "Adjustment Layers Applied;"
      if logEveryAdjustment then
         tell application "Capture One 11"
            set theLayerList to get kind of layers of theVariant
            set theLayerList_T to ""
            repeat with theLayer in theLayerList
               set theLayerList_T to theLayerList_T & (get theLayer as text) & "; "
            end repeat
            set theLayerList_T to text 1 thru -3 of theLayerList_T
         end tell
         set adjustmentList to adjustmentList & "Layer types: " & theLayerList_T
      else if resultLogging then
         set adjustmentList to adjustmentList & "Has " & (countLayers - 1) & " Layers applied" & return
      end if
   else if logEveryAdjustment then
      set adjustmentList to adjustmentList & "No Layers applied" & return
   end if
   
   if not ("missing value" = (get theLCCName as text)) then
      set variantIsAdjusted to true
      set countAdjustments to countAdjustments + 1
      set adjustmentListTag to adjustmentListTag & "LCC Applied;"
      if logEveryAdjustment then
         set adjustmentList to adjustmentList & "LCC applied: " & theLCCName & return
      else if resultLogging then
         set adjustmentList to adjustmentList & "An LCC is applied" & return
      end if
   else if logEveryAdjustment then
      set adjustmentList to adjustmentList & "No LCC is applied" & return
   end if
   
   ## There is an addiotnal impact due to rotation which is not considered yet
   set HorizontalCrop to theImageWidth - theCropWidth
   set VerticalCrop to theImageHeight - theCropHeight
   if not ((0 = HorizontalCrop) and (0 = VerticalCrop)) then
      if (HorizontalCrop ≤ (get DistortedPixelMarginPercent / 100 * theImageWidth)) and (VerticalCrop ≤ (get DistortedPixelMarginPercent / 100 * theImageHeight)) and ¬
         (2 > AbsValue((theImageWidth / 2) - theCropHorCenter)) and ¬
         (2 > AbsValue((theImageHeight / 2) - theCropVerCenter)) ¬
            then
         if resultLogging or logEveryAdjustment then set adjustmentList to adjustmentList & "Border Distortion Cropped " & HorizontalCrop & "x" & VerticalCrop & return
         set hasDistCrop to true
      else
         set adjustmentListTag to adjustmentListTag & "Crop Applied;"
         set countAdjustments to countAdjustments + 1
         set variantIsAdjusted to true
         if logEveryAdjustment then
            set adjustmentList to adjustmentList & "Image Width: " & theImageWidth & "  Crop Width: " & theCropWidth & "   Image Height: " & theImageHeight & "   Crop Height: " & theCropHeight & return
         else if resultLogging then
            set adjustmentList to adjustmentList & "A Crop is applied" & return
         end if
      end if
   else if logEveryAdjustment then
      set adjustmentList to adjustmentList & "No Crop is applied" & return
   end if
   
   
   ## Very Fast way to get all the adjustment values with one Applescript exchange
   tell application "Capture One 11" to tell adjustments of theVariant to set theProperties to get properties
   tell my recordLabelsAndValues3(theProperties)
      set therecordLabels to its recordLabels
      set therecordValues to its its recordValues
   end tell
   ## run these to get the adjustmentlabel values for some other localisation
   --log therecordLabels
   --log therecordValues
   
   checkAdjustmentParams(false, "orientation", 0.0)
   checkAdjustmentParams(enableColorProfile, "color profile", defaultColorProfile)
   checkAdjustmentParams(false, "temperature", 0.0)
   checkAdjustmentParams(false, "tint", 0.0)
   checkAdjustmentParams(true, "rotation", 0.0)
   checkAdjustmentParams(true, "flip", "none")
   checkAdjustmentParams(enableFilmCurve, "film curve", defaultFilmCurve)
   checkAdjustmentParams(enableWhiteBalancePreset, "white balance preset", defaultWhiteBalancePreset)
   checkAdjustmentParams(true, "exposure", 0.0)
   checkAdjustmentParams(true, "brightness", 0.0)
   checkAdjustmentParams(true, "contrast", 0.0)
   checkAdjustmentParams(true, "saturation", 0.0)
   checkAdjustmentParams(true, "color balance master hue", 0.0)
   checkAdjustmentParams(true, "color balance master saturation", 0.0)
   checkAdjustmentParams(true, "color balance shadow hue", 0.0)
   checkAdjustmentParams(true, "color balance shadow saturation", 0.0)
   checkAdjustmentParams(true, "color balance shadow lightness", 0.0)
   checkAdjustmentParams(true, "color balance midtone hue", 0.0)
   checkAdjustmentParams(true, "color balance midtone saturation", 0.0)
   checkAdjustmentParams(true, "color balance midtone lightness", 0.0)
   checkAdjustmentParams(true, "color balance highlight hue", 0.0)
   checkAdjustmentParams(true, "color balance highlight saturation", 0.0)
   checkAdjustmentParams(true, "color balance highlight lightness", 0.0)
   checkAdjustmentParams(true, "level highlight rgb", 255.0)
   checkAdjustmentParams(true, "level highlight red", 255.0)
   checkAdjustmentParams(true, "level highlight green", 255.0)
   checkAdjustmentParams(true, "level highlight blue", 255.0)
   checkAdjustmentParams(true, "level shadow red", 0.0)
   checkAdjustmentParams(true, "level shadow green", 0.0)
   checkAdjustmentParams(true, "level shadow blue", 0.0)
   checkAdjustmentParams(true, "level target highlight rgb", 255.0)
   checkAdjustmentParams(true, "level target shadow rgb", 0.0)
   checkAdjustmentParams(true, "level midtone rgb", 0.0)
   checkAdjustmentParams(true, "level midtone red", 0.0)
   checkAdjustmentParams(true, "level midtone green", 0.0)
   checkAdjustmentParams(true, "level midtone blue", 0.0)
   checkAdjustmentParams(true, "highlight recovery", 0.0)
   checkAdjustmentParams(true, "shadow recovery", 0.0)
   checkAdjustmentParams(true, "clarity method", "natural")
   checkAdjustmentParams(true, "clarity amount", 0.0)
   checkAdjustmentParams(true, "clarity structure", 0.0)
   checkAdjustmentParams(enableSharpeningAmount, "sharpening amount", defaultSharpeningAmount)
   checkAdjustmentParams(enableSharpeningRadius, "sharpening radius", defaultSharpeningRadius)
   checkAdjustmentParams(enableSharpeningThreshold, "sharpening threshold", defaultSharpeningThreshold)
   checkAdjustmentParams(true, "sharpening halo suppression", 0.0)
   checkAdjustmentParams(enableNoiseReductionLuminance, "noise reduction luminance", defaultNoiseReductionLuminance)
   checkAdjustmentParams(true, "noise reduction details", 50.0)
   checkAdjustmentParams(enableNoiseReductionColor, "noise reduction color", defaultNoiseReductionColor)
   checkAdjustmentParams(enableNoiseReductionSinglePixel, "noise reduction single pixel", defaultNoiseReductionSinglePixel)
   checkAdjustmentParams(true, "film grain type", "fine")
   checkAdjustmentParams(enableFilmGrainImpact, "film grain impact", defaultFilmGrainImpact)
   checkAdjustmentParams(true, "film grain granularity", 50.0)
   checkAdjustmentParams(true, "moire amount", 0.0)
   checkAdjustmentParams(true, "moire pattern", 8)
   
   if runAllTests or (not variantIsAdjusted) then
      ## Sometimes C1 reacts slowly if the browser window has to bring up a new row of images
      ## So the first part of this proceedure is done much earlier (Step 1/3 and Step 2/3)
      
      tell application "System Events" to set clipBoardHasAdjustments to (get enabled of theApplyButton) -- Step 3/3
      if clipBoardHasAdjustments then
         set variantIsAdjusted to true
         set countAdjustments to countAdjustments + 1
         set adjustmentList to adjustmentList & "ClipBoard has content" & return
         set adjustmentListTag to adjustmentListTag & "ClipBoard Contents;"
      end if
   end if
   tell application "Capture One 11" to deselect currentDocRef variants (every variant) -- faster than deselecting one variant
   
   ## Now we are done. Do something with the results
   if not variantIsAdjusted then
      set theAdjustmentTag to "Not_Adjusted"
      if resultLogging then
         log theVariantName & " has no Adjustments"
         if 0 < length of adjustmentList then log adjustmentList
      end if
      if resultsInCollections then tell application "Capture One 11" to tell currentDocRef to add inside ref2NotAdjustedAlbum variants {theVariant}
      set notadjustedCounter to notadjustedCounter + 1
   else
      set theAdjustmentTag to "Adjusted"
      if resultLogging then
         log theVariantName & " has Adjustments"
         log adjustmentList
      end if
      if resultsInCollections then tell application "Capture One 11" to tell currentDocRef to add inside ref2IsAdjustedAlbum variants {theVariant}
      set adjustedCounter to adjustedCounter + 1
   end if
   
   if AdjustmentValuesInMetadata then
      set theSharpeningAmount to roundDecimals((get item (get my getIndexOf2("sharpening amount", therecordLabels) as integer) of therecordValues), 1) as text
      set theSharpeningThreshold to roundDecimals((get item (get my getIndexOf2("sharpening threshold", therecordLabels) as integer) of therecordValues), 1) as text
      set theNoiseReductionSinglePixel to roundDecimals((get item (get my getIndexOf2("noise reduction single pixel", therecordLabels) as integer) of therecordValues), 1) as text
      set theFilmGrainImpact to roundDecimals((get item (get my getIndexOf2("film grain impact", therecordLabels) as integer) of therecordValues), 1) as text
      set theFilmCurve to (get item (get my getIndexOf2("film curve", therecordLabels) as integer) of therecordValues) as text
      set theColorProfile to (get item (get my getIndexOf2("color profile", therecordLabels) as integer) of therecordValues) as text
      --set theWBpreset to (get item (get my getIndexOf2("white balance preset", therecordLabels) as integer) of therecordValues)as text
      tell application "Capture One 11" to tell theVariant to ¬
         set {contact website, contact email, contact phone, contact country, contact postal code, contact state} to ¬
            {theSharpeningAmount, theSharpeningThreshold, theNoiseReductionSinglePixel, theFilmGrainImpact, theFilmCurve, theColorProfile}
   end if
   
   if AdjustmentLabelsInMetadata then
      set theVariantsCountTag to (get (get theParentsVariantCount as integer) as text)
      if runAllTests then
         set theAdjustmentCountTag to (get (get countAdjustments as integer) as text)
         if 4 < length of adjustmentListTag then set adjustmentListTag to text 1 thru -2 of adjustmentListTag
      else
         set theAdjustmentCountTag to ""
         set adjustmentListTag to ""
      end if
      tell application "Capture One 11" to tell theVariant to ¬
         set {Getty parent MEID, Getty original filename, Getty personalities, contact city} to ¬
            {theAdjustmentTag, theAdjustmentCountTag, adjustmentListTag, theVariantsCountTag}
   end if
   
   set Mark2 to GetTick_Now()
   set lastTime to (get MSduration(Mark1, Mark2) as text) & "ms"
   if resultLogging then log lastTime
   
end repeat
set theVariantList to {}
if resultLogging then log {"Adjusted: " & adjustedCounter, "Not Adjusted: " & notadjustedCounter}
tell application "Capture One 11" to select currentDocRef variants theSelectedVariantList
set theSelectedVariantList to {}

#####################   Handlers

on checkAdjustmentParams(theFlag, theName, theTest)
   global variantIsAdjusted, therecordLabels, therecordValues, adjustmentList, resultLogging, runAllTests, countAdjustments, logEveryAdjustment, adjustmentListTag
   
   if (not runAllTests) and variantIsAdjusted then return
   
   set theClass to get class of theTest as text
   
   try
      set theValue to (get item (get getIndexOf2(theName, therecordLabels) as integer) of therecordValues)
   on error
      log "can't find: " & theName
      return missing value
   end try
   set thisParamAdjusted to false
   
   if ("integer" = theClass) then
      if not (theTest = (get theValue as integer)) then set thisParamAdjusted to true
   else if ("real" = theClass) then
      if not ((get (get theTest as real) as text) = (get (get theValue as real) as text)) then set thisParamAdjusted to true
   else if ("text" = theClass) then
      if not (theTest = (get theValue as text)) then set thisParamAdjusted to true
   else if ("list" = theClass) then
      set theTestList to {}
      repeat with theItem in theTest
         set theTestList to theTestList & (get theItem as text)
      end repeat
      if not ((get theTestList as list) contains (get theValue as text)) then set thisParamAdjusted to true
   else
      log "Unexpected class " & theClass
      return missing value
   end if
   
   if theFlag then
      if thisParamAdjusted then
         if resultLogging then set adjustmentList to adjustmentList & theName & " has been adjusted to: " & theValue & return
         set adjustmentListTag to adjustmentListTag & theName & " Applied;"
         set variantIsAdjusted to true
         set countAdjustments to countAdjustments + 1
      end if
      --if logEveryAdjustment then log {theName, theValue, theFlag, (not thisParamAdjusted), variantIsAdjusted, countAdjustments}
      if logEveryAdjustment then log {theName, theValue, (not thisParamAdjusted)}
   else
      if resultLogging and thisParamAdjusted then set adjustmentList to adjustmentList & "***" & theName & " is set to: " & theValue & return
   end if
   
   return (not thisParamAdjusted)
end checkAdjustmentParams

#####################   Capture One Utility Handlers

on getVariantNameNum(theVariant)
   global theParentsVariantCount
   tell application "Capture One 11" to tell (get parent image of theVariant) to ¬
      set {theBaseName, theParentsVariantCount} to {name, (count of variants)}
   if (1 = theParentsVariantCount) then return theBaseName
   
   tell application "Capture One 11" to tell theVariant to set {theVariantID, variantIDList} to {id, (id of variants of parent image)}
   repeat with variantCounter from 1 to theParentsVariantCount
      if (get theVariantID as text) = (get item variantCounter of variantIDList as text) then return theBaseName & "-" & variantCounter
   end repeat
end getVariantNameNum

on getVariantsImageType(theVariant)
   tell application "Capture One 11" to tell theVariant to set theFileName to name of parent image
   set theFileExt to ""
   set UC_string to "JPGRWOFTINECABDHKLMQSUVXYZ" -- order optimised for common file extensions
   set LC_string to "jpgrwoftinecabdhklmqsuvxyz"
   repeat with dctr from -1 to (-(get length of theFileName)) by -1
      set this_char to (get text dctr of theFileName) as text
      if "." = this_char then exit repeat
      if LC_string does not contain this_char then
         set the theFileExt to (this_char & theFileExt) as string
      else
         repeat with Tindx from 1 to (get length of LC_string)
            if this_char = text Tindx of LC_string then
               set the theFileExt to ((character Tindx of the UC_string) & theFileExt) as string
               exit repeat
            end if
         end repeat
      end if
   end repeat
   return theFileExt
end getVariantsImageType

on InitializeResultsCollection(nameResultProject, nameResultAlbumRoot)
   ## General Purpose Handler for scripts using Capture One Pro
   ## Sets up a project and albums for collecting images
   
   global ref2ResultAlbum, enableNotifications, currentDocRef
   
   tell application "Capture One 11" to tell currentDocRef
      if not (exists collection named (get nameResultProject)) then
         set ref2ResultProject to make new collection with properties {kind:project, name:nameResultProject}
      else
         if ("project" = (kind of (get collection named nameResultProject)) as text) then
            set ref2ResultProject to collection named nameResultProject
         else
            error ("A collection named \"" & nameResultProject & "\" already exists, and it is not a project.")
         end if
      end if
   end tell
   
   set coll_ctr to 1
   set nameResultAlbum to nameResultAlbumRoot & "_" & (get short date string of (get current date)) & "_"
   repeat
      tell application "Capture One 11" to tell ref2ResultProject
         if not (exists collection named (get nameResultAlbum & coll_ctr)) then
            set nameResultAlbum to (get nameResultAlbum & coll_ctr)
            set ref2ResultAlbum to make new collection with properties {kind:album, name:nameResultAlbum}
            exit repeat
         else
            set coll_ctr to coll_ctr + 1
         end if
      end tell
   end repeat
   
end InitializeResultsCollection

#####################   General Utility Handlers

on splitStringToList(theString, theDelim)
   ## Public Domain
   set astid to AppleScript's text item delimiters
   try
      set AppleScript's text item delimiters to theDelim
      set theList to text items of theString
   on error
      set AppleScript's text item delimiters to astid
   end try
   set AppleScript's text item delimiters to astid
   return theList
end splitStringToList

to joinListToString(theList, theDelim)
   ## Public Domain
   set theString to ""
   set astid to AppleScript's text item delimiters
   try
      set AppleScript's text item delimiters to theDelim
      set theString to theList as string
   on error
      set AppleScript's text item delimiters to astid
   end try
   set AppleScript's text item delimiters to astid
   return theString
end joinListToString

on removeLeadingTrailingSpaces(theString)
   ## Public Domain, modified
   repeat while theString begins with space
      -- When the string is only 1 character long, then it is exactly 1 space, and the next operation willl crash. So return ""
      if 1 ≥ (count of theString) then return ""
      set theString to text 2 thru -1 of theString
   end repeat
   repeat while theString ends with space
      set theString to text 1 thru -2 of theString
   end repeat
   return theString
end removeLeadingTrailingSpaces

on getIndexOf2(theItem, theList)
   set theCount to 0
   set theItem_T to get theItem as text
   repeat with anItem in theList
      set theCount to theCount + 1
      if (get anItem as text) = theItem_T then return theCount
   end repeat
   return 0
end getIndexOf2

on AbsValue(theValue)
   if theValue < 0 then return (get -theValue)
   return theValue
end AbsValue

on roundToQuantum(thisValue, quantum)
   ## Public domain author unknown
   return (round (thisValue / quantum) rounding to nearest) * quantum
end roundToQuantum

on roundDecimals(n, numDecimals)
   ## Nigel Garvey, Macscripter
   set x to 10 ^ numDecimals
   tell n * x to return (it div 0.5 - it div 1) / x
end roundDecimals

on GetTick_Now()
   ## From MacScripter Author "Jean.O.matiC"
   ## returns duration in seconds since since 00:00 January 2nd, 2000 GMT, calculated using computer ticks
   script GetTick
      property parent : a reference to current application
      use framework "Foundation" --> for more precise timing calculations
      on Now()
         return (current application's NSDate's timeIntervalSinceReferenceDate) as real
      end Now
   end script
   return GetTick's Now()
end GetTick_Now

on MSduration(firstTicks, lastTicks)
   ## Public domain
   ## returns duration in ms
   ## inputs are durations, in seconds, from GetTick's Now()
   return (round (10000 * (lastTicks - firstTicks)) rounding to nearest) / 10
end MSduration

## Don't screw with this handler code. Harum Scarum sophisticated
on recordLabelsAndValues3(theRecord)
   -- obtained from http://macscripter.net/viewtopic.php?id=45430
   -- the 2017 final version, very sophisticated script, From "bmose"
   -- Depends on using the clipboard
   -- Returns the unpiped and piped forms of a record's labels and the text and value forms of a record's values
   -- Utility properties and handlers
   
   script util
      property tokenChar : character id 60000 -- obscure character chosen for the low likelihood of its appearance in an input record's text representation; this may be substituted by any character or character string that does not appear in the text representation of the input record
      property tokenizedStrings : {}
      on detokenizeString(tokenizedString)
         -- Convert any tokens of the form "[token char][token index number][token char]" to their original values; handle nested tokens with recursive handler calls
         set tid to AppleScript's text item delimiters
         try
            set AppleScript's text item delimiters to my tokenChar
            tell (get tokenizedString's text items)
               if length < 3 then
                  set originalString to tokenizedString
               else
                  set originalString to (item 1) & my detokenizeString((my tokenizedStrings's item ((item 2) as integer)) & (items 3 thru -1))
               end if
            end tell
         end try
         set AppleScript's text item delimiters to tid
         return originalString
      end detokenizeString
      on representValueAsText(theValue)
         -- Parse a forced error message for the text representation of the input value
         try
            || of {theValue}
         on error m
            try
               if m does not contain "{" then error
               repeat while m does not start with "{"
                  set m to m's text 2 thru -1
               end repeat
               if m does not contain "}" then error
               repeat while m does not end with "}"
                  set m to m's text 1 thru -2
               end repeat
               if m = "{}" then error
               set valueAsText to m's text 2 thru -2
            on error
               try
                  -- Try an alternative method of generating a text representation from a forced error message if the first method fails
                  {||:{theValue}} as null
               on error m
                  try
                     if m does not contain "{" then error
                     repeat while m does not start with "{"
                        set m to m's text 2 thru -1
                     end repeat
                     set m to m's text 2 thru -1
                     repeat while m does not start with "{"
                        set m to m's text 2 thru -1
                     end repeat
                     if m does not contain "}" then error
                     repeat while m does not end with "}"
                        set m to m's text 1 thru -2
                     end repeat
                     set m to m's text 1 thru -2
                     repeat while m does not end with "}"
                        set m to m's text 1 thru -2
                     end repeat
                     if m = "{}" then error
                     set valueAsText to m's text 2 thru -2
                  on error
                     error "Can't get a text representation of the value."
                  end try
               end try
            end try
         end try
         return valueAsText
      end representValueAsText
   end script
   -- Perform the handler's actions inside a try block to capture any errors; if an error is encountered, restore AppleScript's text item delimiters to their baseline value
   set tid to AppleScript's text item delimiters
   try
      -- Handle the special case of an empty record
      if theRecord = {} then return {recordLabels:{}, recordLabelsPiped:{}, recordValuesAsText:{}, recordValues:{}}
      -- Get the text representation of the input record
      set textValue to util's representValueAsText(theRecord)
      -- Partially validate the text representation, and remove the leading and trailing curly braces
      tell textValue
         -- This test does not exclude an input argument in the form of an Applescript list; however, a list will result in a parsing error in the code below
         if (it does not start with "{") or (it does not end with "}") then error "The input value is not a record."
         set textValue to text 2 thru -2
      end tell
      -- Initialize return values and the token counter
      set {recordLabels, recordLabelsPiped, recordValuesAsText, recordValues, iToken} to {{}, {}, {}, {}, 0}
      -- Tokenize text elements that could potentially contain record property (", ") or label/value (":") delimiter characters in order to avoid errors while parsing record properties
      -- Tokens are of the form "[token char][token index number][token char]", where the index numbers increase sequentially 1, 2, 3, ... with each new token
      -- Tokenize escaped double-quote characters (to facilitate tokenizing double-quoted items)
      set AppleScript's text item delimiters to "\\\""
      tell (get textValue's text items)
         if length > 1 then
            set iToken to iToken + 1
            set AppleScript's text item delimiters to (util's tokenChar) & iToken & (util's tokenChar)
            set {textValue, end of util's tokenizedStrings} to {it as text, "\\\""}
         end if
      end tell
      -- Tokenize double-quoted items
      set AppleScript's text item delimiters to "\""
      tell (get textValue's text items)
         if length > 2 then
            set textValue to ""
            repeat with i from 1 to (length - 2) by 2
               set iToken to iToken + 1
               set {textValue, end of util's tokenizedStrings} to {textValue & (item i) & (util's tokenChar) & iToken & (util's tokenChar), "\"" & item (i + 1) & "\""}
            end repeat
            set textValue to textValue & item -1
         end if
      end tell
      -- Tokenize piped items
      set AppleScript's text item delimiters to "|"
      tell (get textValue's text items)
         if length > 2 then
            set textValue to ""
            repeat with i from 1 to (length - 2) by 2
               set iToken to iToken + 1
               set {textValue, end of util's tokenizedStrings} to {textValue & (item i) & (util's tokenChar) & iToken & (util's tokenChar), "|" & item (i + 1) & "|"}
            end repeat
            set textValue to textValue & item -1
         end if
      end tell
      -- Tokenize curly-braced items
      set AppleScript's text item delimiters to "{"
      tell (get textValue's text items)
         if length > 1 then
            set {AppleScript's text item delimiters, textValue, iNestedLevel, currBracedString} to {"}", item 1, 1, ""}
            repeat with s in rest
               tell (get s's text items) to if length > 1 then set {t, iNestedLevel} to {it, iNestedLevel + 1 - length}
               if iNestedLevel > 0 then
                  set {iNestedLevel, currBracedString} to {iNestedLevel + 1, currBracedString & s & "{"}
               else
                  set iToken to iToken + 1
                  set {textValue, iNestedLevel, currBracedString, end of util's tokenizedStrings} to {textValue & (util's tokenChar) & iToken & (util's tokenChar) & t's item -1, 1, "", "{" & currBracedString & (t's items 1 thru -2) & "}"}
               end if
            end repeat
         end if
      end tell
      -- Get the unpiped and piped record labels and text representations of the record values
      set AppleScript's text item delimiters to ", " -- delimits record properties
      tell (get textValue's text items)
         set AppleScript's text item delimiters to ":" -- delimits the label and value for a given record property
         repeat with s in it
            -- Extract and detokenize the current record label and value
            tell (get s's text items) to set {end of recordLabelsPiped, end of recordValuesAsText} to {util's detokenizeString(item 1), util's detokenizeString(item 2)}
            -- Create an unpiped version of the current record label
            tell recordLabelsPiped's item -1
               if it = "||" then
                  set end of recordLabels to ""
               else if (it starts with "|") and (it ends with "|") then
                  set end of recordLabels to text 2 thru -2
               else
                  set end of recordLabels to it
               end if
            end tell
         end repeat
      end tell
      -- Get the record values
      set recordValues to theRecord as list
   on error m number n
      set AppleScript's text item delimiters to tid
      if n = -128 then error number -128
      if n ≠ -2700 then set m to "(" & n & ") " & m -- -2700 = purposely thrown error
      error "Handler recordLabelsAndValues error:" & return & return & m
   end try
   set AppleScript's text item delimiters to tid
   -- Return the results
   return {recordLabels:recordLabels, recordLabelsPiped:recordLabelsPiped, recordValuesAsText:recordValuesAsText, recordValues:recordValues}
end recordLabelsAndValues3
Cheers, Eric
[late 2015 iMac, 4GHz i7, 24GB RAM, external SSDs. GX8, E-M1, GX7, GM5, GM1 ....]
Eric Nepean
 
Posts: 272
Joined: Sat Oct 25, 2014 8:02 am

Return to Scripting



Who is online

Users browsing this forum: No registered users and 2 guests