-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFreshFramesMain.lua
More file actions
744 lines (632 loc) · 32.2 KB
/
Copy pathFreshFramesMain.lua
File metadata and controls
744 lines (632 loc) · 32.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
--[[----------------------------------------------------------------------------
FreshFramesMain.lua
Main logic for Film Preview Collection Creator
This file contains the core functionality to:
1. Analyze the currently selected folder in Lightroom
2. Find all photos in that folder
3. For each base filename (e.g., "raw001"), determine if there's an -Edit version
4. Create a collection with only the "freshest" version of each photo
5. The collection is named "[FolderName] Previews" inside a "35mm" collection set
Key Lightroom SDK concepts used here:
- LrApplication: Access to the active Lightroom catalog
- LrTasks: Asynchronous task execution (required for catalog modifications)
- LrFunctionContext: Context management for async operations and dialogs
- LrDialogs: User interface elements (messages, progress dialogs)
- LrFileUtils: File operations for plain text logging
- LrCatalog: Catalog operations (reading photos, creating collections)
IMPORTANT FIX:
Modal dialogs MUST be created within an LrFunctionContext. This is why
we wrap the entire operation in LrFunctionContext.callWithContext().
--------------------------------------------------------------------------------]]
-- Import required Lightroom SDK modules
-- The 'import' function is provided by Lightroom's Lua environment
local LrApplication = import 'LrApplication'
local LrTasks = import 'LrTasks'
local LrDialogs = import 'LrDialogs'
local LrFunctionContext = import 'LrFunctionContext'
local LrProgressScope = import 'LrProgressScope'
local LrPathUtils = import 'LrPathUtils'
local LrFileUtils = import 'LrFileUtils'
local LrDate = import 'LrDate'
local LrPrefs = import 'LrPrefs'
--[[----------------------------------------------------------------------------
PLUGIN SETTINGS
Load user-configurable settings from preferences.
These are set in the Plugin Manager (File > Plug-in Manager > Film Preview)
--------------------------------------------------------------------------------]]
local prefs = LrPrefs.prefsForPlugin()
-- Get settings with defaults if not set
local COLLECTION_SET_NAME = prefs.collectionSetName or '35mm'
local COLLECTION_SUFFIX = prefs.collectionSuffix or ' Previews'
local FILENAME_SUFFIX = prefs.filenameSuffix or '-Edit'
local LOG_LEVEL = prefs.logLevel or 'info'
-- Diagnostic: Log raw preference values
-- This runs before log level filtering, so it always writes
local function writeRawLog(message)
local timestamp = LrDate.timeToUserFormat(LrDate.currentTime(), '%Y-%m-%d %H:%M:%S')
local logLine = '[' .. timestamp .. '] [STARTUP] ' .. message .. '\n'
local docsPath = LrPathUtils.getStandardFilePath('documents')
local logPath = docsPath and LrPathUtils.child(docsPath, 'FreshFrames.log') or 'FreshFrames.log'
pcall(function()
local file = io.open(logPath, 'a')
if file then
file:write(logLine)
file:close()
end
end)
end
writeRawLog('========================================')
writeRawLog('PREFERENCE LOADING DIAGNOSTICS')
writeRawLog('Raw pref values from Lightroom:')
writeRawLog(' collectionSetName = ' .. tostring(prefs.collectionSetName))
writeRawLog(' collectionSuffix = ' .. tostring(prefs.collectionSuffix))
writeRawLog(' filenameSuffix = ' .. tostring(prefs.filenameSuffix))
writeRawLog(' logLevel = ' .. tostring(prefs.logLevel))
writeRawLog('Final values being used:')
writeRawLog(' COLLECTION_SET_NAME = ' .. tostring(COLLECTION_SET_NAME))
writeRawLog(' COLLECTION_SUFFIX = ' .. tostring(COLLECTION_SUFFIX))
writeRawLog(' FILENAME_SUFFIX = ' .. tostring(FILENAME_SUFFIX))
writeRawLog(' LOG_LEVEL = ' .. tostring(LOG_LEVEL))
writeRawLog('========================================')
-- Log level hierarchy: off < error < warn < info < trace
local LOG_LEVELS = {
off = 0,
error = 1,
warn = 2,
info = 3,
trace = 4,
}
local currentLogLevel = LOG_LEVELS[LOG_LEVEL] or LOG_LEVELS.info
--[[----------------------------------------------------------------------------
PLAIN TEXT LOGGING SETUP
We use plain text logging instead of LrLogger because:
1. LrLogger creates binary files that can't be read in a text editor
2. Plain text files are easier to debug
3. We have full control over the format
The log file will be created at:
- Windows: C:\Users\[username]\Documents\FreshFrames.log (or C:\Users\...)
- macOS: ~/Documents/FreshFrames.log
--------------------------------------------------------------------------------]]
-- Determine log file location
local docsPath = LrPathUtils.getStandardFilePath('documents')
local logFilePath = nil
if docsPath then
logFilePath = LrPathUtils.child(docsPath, 'FreshFrames.log')
else
-- Fallback if we can't get documents folder
logFilePath = 'FreshFrames.log'
end
-- Simple logging functions that write to a plain text file
local function writeLog(level, levelNum, message)
-- Only log if the message level is at or above the configured log level
if currentLogLevel < levelNum then
return
end
-- Format: [TIMESTAMP] [LEVEL] Message
local timestamp = LrDate.timeToUserFormat(LrDate.currentTime(), '%Y-%m-%d %H:%M:%S')
local logLine = '[' .. timestamp .. '] [' .. level .. '] ' .. message .. '\n'
-- Append to log file
-- We use pcall to catch any file I/O errors
local success, err = pcall(function()
local file = io.open(logFilePath, 'a')
if file then
file:write(logLine)
file:close()
end
end)
-- If logging fails, we can't really do anything about it
-- (we don't want to show an error dialog every time we try to log)
end
-- Convenience functions for different log levels
-- Each checks if that level should be logged based on current settings
local function logTrace(msg) writeLog('TRACE', LOG_LEVELS.trace, msg) end
local function logInfo(msg) writeLog('INFO', LOG_LEVELS.info, msg) end
local function logWarn(msg) writeLog('WARN', LOG_LEVELS.warn, msg) end
local function logError(msg) writeLog('ERROR', LOG_LEVELS.error, msg) end
-- Log startup
logInfo('========================================')
logInfo('Fresh Frames v1.4.0 - Starting')
logInfo('Log file location: ' .. tostring(logFilePath))
logInfo('Log level: ' .. LOG_LEVEL)
logInfo('Settings: Set="' ..
COLLECTION_SET_NAME .. '", Suffix="' .. COLLECTION_SUFFIX .. '", Edit suffix="' .. FILENAME_SUFFIX .. '"')
logInfo('========================================')
--[[----------------------------------------------------------------------------
HELPER FUNCTION: Extract base filename
This function extracts the base name from a filename, removing the -Edit suffix
and file extension.
Examples:
"raw001.dng" -> "raw001"
"raw001-Edit.tif" -> "raw001"
"scan_001-Edit.psd" -> "scan_001"
Parameters:
filename - String containing the filename with extension
Returns:
baseName - String containing the base name without -Edit or extension
--------------------------------------------------------------------------------]]
local function getBaseName(filename)
logTrace(' getBaseName() called with: ' .. tostring(filename))
-- First, remove the file extension
-- LrPathUtils.removeExtension() is a Lightroom utility function
local nameWithoutExt = LrPathUtils.removeExtension(filename)
logTrace(' After removing extension: ' .. tostring(nameWithoutExt))
-- Remove the edit suffix (case-insensitive)
-- Escape special pattern characters in the suffix
local escapedSuffix = string.gsub(FILENAME_SUFFIX, '([%^%$%(%)%%%.%[%]%*%+%-%?])', '%%%1')
-- Build case-insensitive pattern
local pattern = ''
for i = 1, #escapedSuffix do
local char = string.sub(escapedSuffix, i, i)
if string.match(char, '%a') then
pattern = pattern .. '[' .. string.upper(char) .. string.lower(char) .. ']'
else
pattern = pattern .. char
end
end
pattern = pattern .. '$'
local baseName = string.gsub(nameWithoutExt, pattern, '')
logTrace(' Base name result: ' .. tostring(baseName))
return baseName
end
--[[----------------------------------------------------------------------------
HELPER FUNCTION: Determine if a photo is an Edit version
Checks if the filename ends with -Edit (before the extension)
Parameters:
filename - String containing the filename with extension
Returns:
Boolean - true if this is an -Edit file, false otherwise
--------------------------------------------------------------------------------]]
local function isEditVersion(filename)
local nameWithoutExt = LrPathUtils.removeExtension(filename)
-- Escape special pattern characters in the suffix
local escapedSuffix = string.gsub(FILENAME_SUFFIX, '([%^%$%(%)%%%.%[%]%*%+%-%?])', '%%%1')
-- Build case-insensitive pattern
-- Convert each letter to [Aa] pattern for case insensitivity
local pattern = ''
for i = 1, #escapedSuffix do
local char = string.sub(escapedSuffix, i, i)
if string.match(char, '%a') then
pattern = pattern .. '[' .. string.upper(char) .. string.lower(char) .. ']'
else
pattern = pattern .. char
end
end
pattern = pattern .. '$'
local isEdit = string.match(nameWithoutExt, pattern) ~= nil
logTrace(' isEditVersion(' .. tostring(filename) .. ') = ' .. tostring(isEdit))
return isEdit
end
--[[----------------------------------------------------------------------------
MAIN FUNCTION: Create Preview Collection
This is the main entry point that gets called when the user selects the menu item.
It must run in an async task because it modifies the catalog, which requires
write access.
Lightroom's threading model:
- Main thread: UI operations
- Async tasks: Catalog modifications (using LrTasks.startAsyncTask)
- Function contexts: Required for modal dialogs (using LrFunctionContext)
- You MUST use catalog:withWriteAccessDo() to modify the catalog
CRITICAL: All modal dialogs must be created within an LrFunctionContext!
This is why we wrap everything in LrFunctionContext.callWithContext().
--------------------------------------------------------------------------------]]
local function createPreviewCollection()
logInfo('createPreviewCollection() - Function started')
-- Start an asynchronous task
-- This is REQUIRED for any operation that modifies the catalog
-- The function passed to startAsyncTask runs in a background thread
LrTasks.startAsyncTask(function()
logInfo('Async task started')
-- The catalog is Lightroom's database containing all photos, collections, etc.
local catalog = LrApplication.activeCatalog()
if not catalog then
logError('ERROR: Could not get active catalog')
LrDialogs.message('Error', 'Could not access Lightroom catalog.')
return
end
logInfo('Got active catalog')
-- Active sources are what's selected in the folder/collection panel
-- This could be folders, collections, or smart collections
local activeSources = catalog:getActiveSources()
if not activeSources or #activeSources == 0 then
logWarn('No active sources found')
LrDialogs.message('No Folder Selected',
'Please select a folder in the Folders panel before running this plugin.')
return
end
logInfo('Found ' .. #activeSources .. ' active source(s)')
-- Get the first active source (usually the selected folder)
local source = activeSources[1]
local sourceType = source:type()
logInfo('Source type: ' .. tostring(sourceType))
-- Verify that the source is a folder
-- The type() method returns 'LrFolder' for folders
if sourceType ~= 'LrFolder' then
logWarn('Source is not a folder, type is: ' .. tostring(sourceType))
LrDialogs.message('Not a Folder',
'Please select a folder (not a collection) in the Folders panel.')
return
end
-- Get the folder name for the collection name
local folderName = source:getName()
logInfo('Folder name: ' .. tostring(folderName))
-- Get all photos in this folder
-- getPhotos() returns an array of LrPhoto objects
-- By default, this includes photos in the folder but not subfolders
local photos = source:getPhotos()
logInfo('Found ' .. #photos .. ' photo(s) in folder')
if #photos == 0 then
logWarn('No photos found in folder')
LrDialogs.message('Empty Folder',
'The selected folder contains no photos.')
return
end
--[[----------------------------------------------------------------
DRY RUN OPTION
Ask the user if they want to do a dry run (analyze only) or
actually create the collection.
------------------------------------------------------------------]]
-- First, ask if they want dry run or real run
-- Using a simple 2-button dialog for testing
logInfo('About to show confirmation dialog')
local dryRunAction = LrDialogs.confirm(
'Dry Run Mode?',
'Folder: ' .. folderName .. '\n' ..
'Photos found: ' .. #photos .. '\n\n' ..
'Choose DRY RUN to analyze without making changes.\n' ..
'Choose CREATE COLLECTION to actually create the collection.',
'Dry Run (analyze only)', -- First button (returns 'ok')
'Create Collection' -- Second button (returns 'cancel')
)
logInfo('Dialog returned: "' .. tostring(dryRunAction) .. '"')
logInfo('Type of return value: ' .. type(dryRunAction))
-- With a 2-button confirm dialog:
-- First button returns 'ok'
-- Second button (or X) returns 'cancel'
local isDryRun = (dryRunAction == 'ok')
logInfo('Interpreted as isDryRun: ' .. tostring(isDryRun))
-- If user clicked X or something unexpected happened
if dryRunAction ~= 'ok' and dryRunAction ~= 'cancel' then
logWarn('Unexpected dialog result: ' .. tostring(dryRunAction) .. ', treating as cancel')
logInfo('User cancelled operation')
return
end
-- Variables to store results from the progress dialog section
local photoGroups = {}
local freshestPhotos = {}
local editCount = 0
local rawCount = 0
local dryRunDetails = {}
local uniqueCount = 0
-- Wrap ONLY the progress dialog operations in a function context
-- This is required for showModalProgressDialog to work
LrFunctionContext.callWithContext('progressDialog', function(context)
logInfo('Function context established for progress dialog')
-- Create a progress dialog
-- This MUST be within a function context
local progressScope = LrDialogs.showModalProgressDialog({
title = isDryRun and 'Analyzing Photos (Dry Run)' or 'Creating Preview Collection',
caption = 'Analyzing photos...',
cannotCancel = false, -- Allow user to cancel
functionContext = context, -- Pass the function context
})
--[[----------------------------------------------------------------
STEP 1: Analyze all photos and group them by base name
We'll create a table (Lua's equivalent of a dictionary/hash map) where:
- Key: base filename (e.g., "raw001")
- Value: table containing {rawPhoto, editPhoto}
After processing all photos, we'll have a complete map of which photos
have Edit versions and which don't.
------------------------------------------------------------------]]
logInfo('STEP 1: Analyzing photos and grouping by base name')
-- Iterate through all photos in the folder
for i, photo in ipairs(photos) do
-- Update progress dialog
if progressScope:isCanceled() then
logInfo('User canceled operation')
return
end
progressScope:setPortionComplete(i * 0.5, #photos) -- First 50% of progress
progressScope:setCaption('Analyzing photo ' .. i .. ' of ' .. #photos)
-- Get the filename of this photo
local filename = photo:getFormattedMetadata('fileName')
logTrace('Processing photo ' .. i .. ': ' .. tostring(filename))
-- Extract the base name (without -Edit and extension)
local baseName = getBaseName(filename)
logTrace(' Base name: ' .. tostring(baseName))
-- Initialize this base name's group if it doesn't exist yet
if not photoGroups[baseName] then
photoGroups[baseName] = { raw = nil, edit = nil }
logTrace(' Created new photo group for: ' .. tostring(baseName))
end
-- Determine if this is an Edit version and store accordingly
if isEditVersion(filename) then
logTrace(' This is an Edit version')
photoGroups[baseName].edit = photo
else
logTrace(' This is a raw/original version')
photoGroups[baseName].raw = photo
end
end
-- Count unique base names
for _ in pairs(photoGroups) do
uniqueCount = uniqueCount + 1
end
logInfo('Found ' .. uniqueCount .. ' unique base names')
--[[----------------------------------------------------------------
STEP 2: Select the "freshest" version of each photo
For each base name:
- If there's an Edit version, use it (it's fresher)
- Otherwise, use the raw/original version
------------------------------------------------------------------]]
logInfo('STEP 2: Selecting freshest versions')
-- Iterate through our grouped photos
for baseName, group in pairs(photoGroups) do
logTrace('Evaluating group: ' .. tostring(baseName))
if group.edit then
-- Edit version exists - use it
logTrace(' Using Edit version')
table.insert(freshestPhotos, group.edit)
editCount = editCount + 1
-- For dry run, collect details
if isDryRun then
local editFilename = group.edit:getFormattedMetadata('fileName')
local rawFilename = group.raw and group.raw:getFormattedMetadata('fileName') or 'none'
table.insert(dryRunDetails, {
baseName = baseName,
selected = editFilename,
skipped = rawFilename ~= 'none' and rawFilename or nil
})
end
elseif group.raw then
-- No edit version - use raw
logTrace(' Using raw version (no Edit found)')
table.insert(freshestPhotos, group.raw)
rawCount = rawCount + 1
-- For dry run, collect details
if isDryRun then
local rawFilename = group.raw:getFormattedMetadata('fileName')
table.insert(dryRunDetails, {
baseName = baseName,
selected = rawFilename,
skipped = nil
})
end
else
-- This shouldn't happen, but log it if it does
logWarn(' WARNING: No raw or edit found for ' .. tostring(baseName))
end
end
logInfo('Selected ' .. #freshestPhotos .. ' photos (' .. editCount ..
' Edit versions, ' .. rawCount .. ' raw versions)')
--[[----------------------------------------------------------------
Handle dry run vs real run
------------------------------------------------------------------]]
if isDryRun then
-- DRY RUN: Just show what would happen
logInfo('DRY RUN: Showing results without creating collection')
progressScope:done()
else
-- REAL RUN: Close progress dialog before we exit function context
logInfo('Analysis complete, closing progress dialog')
progressScope:setCaption('Preparing to create collection...')
progressScope:done()
-- Wait a moment for the dialog to fully close and release any locks
logInfo('Waiting 2 seconds for UI to settle...')
LrTasks.sleep(2)
logInfo('Wait complete, proceeding with collection creation')
end
end) -- End of function context for progress dialog
-- Now handle the results OUTSIDE the function context
if isDryRun then
-- Build a detailed report
local report = 'DRY RUN RESULTS\n' ..
'================\n\n' ..
'Folder: ' .. folderName .. '\n' ..
'Total photos in folder: ' .. #photos .. '\n' ..
'Unique base names: ' .. uniqueCount .. '\n\n' ..
'Would create collection: "' .. folderName .. COLLECTION_SUFFIX .. '"\n' ..
'Inside collection set: "' .. COLLECTION_SET_NAME .. '"\n' ..
'Would include ' .. #freshestPhotos .. ' photos:\n' ..
' - ' .. editCount .. ' Edit versions\n' ..
' - ' .. rawCount .. ' original versions\n\n'
-- Add first few examples
if #dryRunDetails > 0 then
report = report .. 'First 10 examples:\n'
for i = 1, math.min(10, #dryRunDetails) do
local detail = dryRunDetails[i]
report = report .. i .. '. KEEP: ' .. detail.selected
if detail.skipped then
report = report .. '\n (has -Edit, skipping: ' .. detail.skipped .. ')'
end
report = report .. '\n'
end
end
report = report .. '\n' ..
'Would create/update collection inside "' .. COLLECTION_SET_NAME .. '" collection set\n' ..
'(creating the set if it doesn\'t exist)\n' ..
'(updating collection if it already exists)\n\n' ..
'No collection was created (dry run mode).\n' ..
'Run again and choose "Create Collection" to proceed.\n\n' ..
'Log file: ' .. logFilePath
logInfo('Dry run report:\n' .. report)
-- Show report in a scrollable text dialog
LrDialogs.message('Dry Run Complete', report, 'info')
else
-- REAL RUN: Create the collection
-- This is now OUTSIDE the function context but still INSIDE the async task
logInfo('STEP 3: Creating collection')
-- Build the collection name using configured suffix
local collectionName = folderName .. COLLECTION_SUFFIX
logInfo('Collection name will be: ' .. tostring(collectionName))
-- Use configured collection set name
local parentSetName = COLLECTION_SET_NAME
logInfo('Will create collection in set: ' .. parentSetName)
--[[----------------------------------------------------------------
CRITICAL: Query catalog BEFORE entering withWriteAccessDo
We CANNOT query collections inside withWriteAccessDo - it causes errors
So we do ALL queries here first
------------------------------------------------------------------]]
-- Find the parent collection set "35mm" if it exists
local parentSet = nil
local parentSetExists = false
local allCollectionSets = catalog:getChildCollectionSets()
logInfo('Searching through ' .. #allCollectionSets .. ' existing collection sets')
for _, collSet in ipairs(allCollectionSets) do
local setName = collSet:getName()
logInfo(' Checking collection set: ' .. tostring(setName))
if setName == parentSetName then
parentSet = collSet
parentSetExists = true
logInfo(' Found existing collection set: ' .. parentSetName)
break
end
end
if not parentSetExists then
logInfo('Collection set "' .. parentSetName .. '" does not exist, will create it')
end
-- Check if collection already exists - if so, we'll update it
local existingCollection = nil
if parentSetExists then
local existingCollections = parentSet:getChildCollections()
logInfo('Checking ' .. #existingCollections .. ' existing collections in parent set')
for _, coll in ipairs(existingCollections) do
if coll:getName() == collectionName then
existingCollection = coll
logInfo('Found existing collection: ' .. collectionName .. ' - will update it')
break
end
end
if not existingCollection then
logInfo('No existing collection found in set')
end
else
-- Set doesn't exist, so our collection definitely doesn't exist
logInfo('Set doesn\'t exist, so no duplicate possible')
end
-- Modify the catalog to create the collection
-- withWriteAccessDo() MUST be called directly from the async task
-- NOT from within a nested function context
-- withWriteAccessDo() parameters:
-- 1. Operation name (for undo history)
-- 2. Function that performs the modifications
-- 3. Optional parameters table
-- Flag to detect if withWriteAccessDo actually executes
local didExecute = false
-- Variable to store the created collection so we can use it outside withWriteAccessDo
local newCollection = nil
logInfo('Calling withWriteAccessDo...')
catalog:withWriteAccessDo(
'Create Preview Collection',
function(writeContext)
-- Set flag to indicate we're executing
didExecute = true
logInfo('Inside withWriteAccessDo block')
-- Create the parent collection set if it doesn't exist
-- We determined this BEFORE entering withWriteAccessDo
if not parentSetExists then
logInfo('Creating collection set: ' .. parentSetName)
parentSet = catalog:createCollectionSet(parentSetName, nil, true)
logInfo('Created collection set: ' .. parentSetName)
end
if existingCollection then
-- Update existing collection
logInfo('Updating existing collection: ' .. collectionName)
newCollection = existingCollection
-- Remove all photos from existing collection, then add fresh ones
-- This handles cases where Edit files were deleted or new ones added
logInfo('Clearing existing collection contents')
newCollection:removeAllPhotos()
logInfo('Adding ' .. #freshestPhotos .. ' fresh photos to existing collection')
newCollection:addPhotos(freshestPhotos)
logInfo('Collection updated successfully')
else
-- Create the new collection inside the parent set
-- createCollection() creates a regular (not smart) collection
-- Parameters:
-- 1. Collection name
-- 2. Parent (the collection set)
-- 3. Whether to add to top level (false, we have a parent)
logInfo('Creating new collection: ' .. collectionName .. ' in set: ' .. parentSetName)
newCollection = catalog:createCollection(collectionName, parentSet, false)
logInfo('Collection created successfully')
-- Add the freshest photos to the collection
-- addPhotos() accepts an array of photo objects
logInfo('Adding ' .. #freshestPhotos .. ' photos to new collection')
newCollection:addPhotos(freshestPhotos)
logInfo('Photos added successfully')
end
end,
{
timeout = 30, -- Wait up to 30 seconds for write access
}
)
logInfo('withWriteAccessDo returned')
-- Make the new collection the active source
-- IMPORTANT: This must be OUTSIDE withWriteAccessDo to avoid querying issues
if newCollection then
logInfo('Setting new collection as active source')
catalog:setActiveSources({ newCollection })
logInfo('Set new collection as active source')
end
-- Check if the function actually executed
if not didExecute then
logError('ERROR: withWriteAccessDo timed out - function never executed')
logError('The catalog may be busy, locked, or syncing')
LrDialogs.message('Catalog Timeout',
'Could not access the Lightroom catalog to create the collection.\n\n' ..
'The catalog timed out after 30 seconds. This usually means:\n' ..
'• Lightroom is syncing with Creative Cloud\n' ..
'• Another operation is in progress\n' ..
'• The catalog file is on a slow/busy drive\n\n' ..
'Please wait a moment and try again.\n\n' ..
'Log file: ' .. logFilePath,
'critical')
return
end
logInfo('withWriteAccessDo completed successfully')
-- Show success message
local actionWord = existingCollection and 'updated' or 'created'
local message = string.format(
'Successfully %s collection "%s"\n' ..
'in collection set "%s"\n' ..
'with %d photos:\n\n' ..
'- %d Edit versions\n' ..
'- %d Original versions\n\n' ..
'The collection is now active in the Collections panel.\n\n' ..
'Log file: %s',
actionWord,
collectionName,
parentSetName,
#freshestPhotos,
editCount,
rawCount,
logFilePath
)
logInfo('SUCCESS: ' .. message)
local operationWord = existingCollection and 'update' or 'creation'
logInfo('Collection ' .. operationWord .. ' completed successfully')
local dialogTitle = existingCollection and 'Collection Updated' or 'Collection Created'
LrDialogs.message(dialogTitle, message, 'info')
end
end) -- End of async task
logInfo('createPreviewCollection() - Function completed (async task dispatched)')
end
--[[----------------------------------------------------------------------------
ENTRY POINT
When the user clicks the menu item, Lightroom executes this file.
We wrap the main function call in error handling to catch and display any errors.
--------------------------------------------------------------------------------]]
-- Wrap the main function call in error handling
-- This catches any errors and shows them to the user
local success, err = pcall(createPreviewCollection)
if not success then
logError('FATAL ERROR: ' .. tostring(err))
logError('Stack trace: ' .. debug.traceback())
-- Show error to user
LrDialogs.message('Plugin Error',
'An error occurred in the Fresh Frames plugin:\n\n' ..
tostring(err) .. '\n\n' ..
'Check the log file for details:\n' ..
logFilePath,
'critical')
end