BatchImport.vala 75.3 KB
Newer Older
Eric Gregory's avatar
Eric Gregory committed
1
/* Copyright 2009-2011 Yorba Foundation
2 3 4 5
 *
 * This software is licensed under the GNU LGPL (version 2.1 or later).
 * See the COPYING file in this distribution. 
 */
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
public enum ImportResult {
    SUCCESS,
    FILE_ERROR,
    DECODE_ERROR,
    DATABASE_ERROR,
    USER_ABORT,
    NOT_A_FILE,
    PHOTO_EXISTS,
    UNSUPPORTED_FORMAT,
    NOT_AN_IMAGE,
    DISK_FAILURE,
    DISK_FULL,
    CAMERA_ERROR,
    FILE_WRITE_ERROR;
    
    public string to_string() {
        switch (this) {
            case SUCCESS:
                return _("Success");
            
            case FILE_ERROR:
                return _("File error");
            
            case DECODE_ERROR:
                return _("Unable to decode file");
            
            case DATABASE_ERROR:
                return _("Database error");
            
            case USER_ABORT:
                return _("User aborted import");
            
            case NOT_A_FILE:
                return _("Not a file");
            
            case PHOTO_EXISTS:
                return _("File already exists in database");
            
            case UNSUPPORTED_FORMAT:
                return _("Unsupported file format");

            case NOT_AN_IMAGE:
                return _("Not an image file");
            
            case DISK_FAILURE:
                return _("Disk failure");
            
            case DISK_FULL:
                return _("Disk full");
            
            case CAMERA_ERROR:
                return _("Camera error");
            
            case FILE_WRITE_ERROR:
                return _("File write error");
            
            default:
                return _("Imported failed (%d)").printf((int) this);
        }
    }
    
    public bool is_abort() {
        switch (this) {
            case ImportResult.DISK_FULL:
            case ImportResult.DISK_FAILURE:
            case ImportResult.USER_ABORT:
                return true;
            
            default:
                return false;
        }
    }
    
    public bool is_nonuser_abort() {
        switch (this) {
            case ImportResult.DISK_FULL:
            case ImportResult.DISK_FAILURE:
                return true;
            
            default:
                return false;
        }
    }
    
    public static ImportResult convert_error(Error err, ImportResult default_result) {
        if (err is FileError) {
            FileError ferr = (FileError) err;
            
            if (ferr is FileError.NOSPC)
                return ImportResult.DISK_FULL;
            else if (ferr is FileError.IO)
                return ImportResult.DISK_FAILURE;
            else if (ferr is FileError.ISDIR)
                return ImportResult.NOT_A_FILE;
101
            else if (ferr is FileError.ACCES)
102 103 104 105 106 107 108 109 110 111 112 113 114 115
                return ImportResult.FILE_WRITE_ERROR;
            else
                return ImportResult.FILE_ERROR;
        } else if (err is IOError) {
            IOError ioerr = (IOError) err;
            
            if (ioerr is IOError.NO_SPACE)
                return ImportResult.DISK_FULL;
            else if (ioerr is IOError.FAILED)
                return ImportResult.DISK_FAILURE;
            else if (ioerr is IOError.IS_DIRECTORY)
                return ImportResult.NOT_A_FILE;
            else if (ioerr is IOError.CANCELLED)
                return ImportResult.USER_ABORT;
116
            else if (ioerr is IOError.READ_ONLY)
117 118 119 120 121 122 123 124 125 126 127
                return ImportResult.FILE_WRITE_ERROR;
            else
                return ImportResult.FILE_ERROR;
        } else if (err is GPhotoError) {
            return ImportResult.CAMERA_ERROR;
        }
        
        return default_result;
    }
}

128 129 130
// A BatchImportJob describes a unit of work the BatchImport object should perform.  It returns
// a file to be imported.  If the file is a directory, it is automatically recursed by BatchImport
// to find all files that need to be imported into the library.
131
//
132
// NOTE: All methods may be called from the context of a background thread or the main GTK thread.
133 134
// Implementations should be able to handle either situation.  The prepare method will always be
// called by the same thread context.
135
public abstract class BatchImportJob {
136 137 138
    public abstract string get_dest_identifier();
    
    public abstract string get_source_identifier();
139
    
140 141
    public abstract bool is_directory();
    
Eric Gregory's avatar
Eric Gregory committed
142 143 144 145 146 147 148
    public abstract string get_basename();
    
    public abstract string get_path();
    
    // Attaches a sibling job (for RAW+JPEG)
    public abstract void set_associated(BatchImportJob associated);
    
149 150 151 152 153 154 155
    // Returns the file size of the BatchImportJob or returns a file/directory which can be queried
    // by BatchImportJob to determine it.  Returns true if the size is return, false if the File is
    // specified.
    // 
    // filesize should only be returned if BatchImportJob represents a single file.
    public abstract bool determine_file_size(out uint64 filesize, out File file_or_dir);
    
156
    // NOTE: prepare( ) is called from a background thread in the worker pool
157
    public abstract bool prepare(out File file_to_import, out bool copy_to_library) throws Error;
158 159 160 161 162 163 164
    
    // Completes the import for the new library photo once it's been imported.
    // If the job is directory based, this method will be called for each photo
    // discovered in the directory. This method is only called for photographs
    // that have been successfully imported.
    //
    // Returns true if any action was taken, false otherwise.
165 166
    //
    // NOTE: complete( )is called from the foreground thread
167
    public virtual bool complete(MediaSource source, BatchImportRoll import_roll) throws Error {
168 169
        return false;
    }
170 171 172 173 174 175
    
    // returns a non-zero time_t value if this has a valid exposure time override, returns zero
    // otherwise
    public virtual time_t get_exposure_time_override() {
        return 0;
    }
176 177
}

178 179 180
public class FileImportJob : BatchImportJob {
    private File file_or_dir;
    private bool copy_to_library;
Eric Gregory's avatar
Eric Gregory committed
181
    private FileImportJob? associated = null;
182 183 184 185 186 187
    
    public FileImportJob(File file_or_dir, bool copy_to_library) {
        this.file_or_dir = file_or_dir;
        this.copy_to_library = copy_to_library;
    }
    
188 189 190 191 192
    public override string get_dest_identifier() {
        return file_or_dir.get_path();
    }
    
    public override string get_source_identifier() {
193 194 195 196 197 198 199
        return file_or_dir.get_path();
    }
    
    public override bool is_directory() {
        return query_is_directory(file_or_dir);
    }
    
Eric Gregory's avatar
Eric Gregory committed
200 201 202 203 204 205 206 207 208 209 210 211
    public override string get_basename() {
        return file_or_dir.get_basename();
    }
    
    public override string get_path() {
        return is_directory() ? file_or_dir.get_path() : file_or_dir.get_parent().get_path();
    }
    
    public override void set_associated(BatchImportJob associated) {
        this.associated = associated as FileImportJob;
    }
    
212
    public override bool determine_file_size(out uint64 filesize, out File file) {
213
        filesize = 0;
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        file = file_or_dir;
        
        return false;
    }
    
    public override bool prepare(out File file_to_import, out bool copy) {
        file_to_import = file_or_dir;
        copy = copy_to_library;
        
        return true;
    }
    
    public File get_file() {
        return file_or_dir;
    }
}

231 232 233 234 235 236 237 238
// A BatchImportRoll represents important state for a group of imported media.  If this is shared
// among multiple BatchImport objects, the imported media will appear to have been imported all at
// once.
public class BatchImportRoll {
    public ImportID import_id;
    public ViewCollection generated_events = new ViewCollection("BatchImportRoll generated events");
    
    public BatchImportRoll() {
239
        this.import_id = ImportID.generate();
240 241 242
    }
}

243 244 245 246 247 248
// A BatchImportResult associates a particular job with a File that an import was performed on
// and the import result.  A BatchImportJob can specify multiple files, so there is not necessarily
// a one-to-one relationship beteen it and this object.
//
// Note that job may be null (in the case of a pre-failed job that must be reported) and file may
// be null (for similar reasons).
249
public class BatchImportResult {
250
    public BatchImportJob job;
251
    public File? file;
252 253
    public string src_identifier;  // Source path
    public string dest_identifier; // Destination path
254
    public ImportResult result;
255
    public string? errmsg = null;
256
    
257 258
    public BatchImportResult(BatchImportJob job, File? file, string src_identifier, 
        string dest_identifier, ImportResult result) {
259 260
        this.job = job;
        this.file = file;
261 262
        this.src_identifier = src_identifier;
        this.dest_identifier = dest_identifier;
263 264
        this.result = result;
    }
265
    
266 267
    public BatchImportResult.from_error(BatchImportJob job, File? file, string src_identifier,
        string dest_identifier, Error err, ImportResult default_result) {
268 269
        this.job = job;
        this.file = file;
270 271
        this.src_identifier = src_identifier;
        this.dest_identifier = dest_identifier;
272 273 274
        this.result = ImportResult.convert_error(err, default_result);
        this.errmsg = err.message;
    }
275 276
}

277
public class ImportManifest {
278
    public Gee.List<MediaSource> imported = new Gee.ArrayList<MediaSource>();
279
    public Gee.List<BatchImportResult> success = new Gee.ArrayList<BatchImportResult>();
280
    public Gee.List<BatchImportResult> camera_failed = new Gee.ArrayList<BatchImportResult>();
281
    public Gee.List<BatchImportResult> failed = new Gee.ArrayList<BatchImportResult>();
282
    public Gee.List<BatchImportResult> write_failed = new Gee.ArrayList<BatchImportResult>();
283 284
    public Gee.List<BatchImportResult> skipped_photos = new Gee.ArrayList<BatchImportResult>();
    public Gee.List<BatchImportResult> skipped_files = new Gee.ArrayList<BatchImportResult>();
285 286 287 288
    public Gee.List<BatchImportResult> aborted = new Gee.ArrayList<BatchImportResult>();
    public Gee.List<BatchImportResult> already_imported = new Gee.ArrayList<BatchImportResult>();
    public Gee.List<BatchImportResult> all = new Gee.ArrayList<BatchImportResult>();
    
289 290
    public ImportManifest(Gee.List<BatchImportJob>? prefailed = null,
        Gee.List<BatchImportJob>? pre_already_imported = null) {
291 292
        if (prefailed != null) {
            foreach (BatchImportJob job in prefailed) {
293 294
                BatchImportResult batch_result = new BatchImportResult(job, null, 
                    job.get_source_identifier(), job.get_dest_identifier(), ImportResult.FILE_ERROR);
295 296 297 298 299 300
                add_result(batch_result);
            }
        }
        
        if (pre_already_imported != null) {
            foreach (BatchImportJob job in pre_already_imported) {
301 302
                BatchImportResult batch_result = new BatchImportResult(job, null, 
                job.get_source_identifier(), job.get_dest_identifier(), ImportResult.PHOTO_EXISTS);
303 304 305 306 307 308
                add_result(batch_result);
            }
        }
    }
    
    public void add_result(BatchImportResult batch_result) {
309
        bool reported = true;
310 311 312 313
        switch (batch_result.result) {
            case ImportResult.SUCCESS:
                success.add(batch_result);
            break;
314

315
            case ImportResult.USER_ABORT:
316
                if (batch_result.file != null && !query_is_directory(batch_result.file))
317
                    aborted.add(batch_result);
318 319
                else
                    reported = false;
320 321 322
            break;

            case ImportResult.UNSUPPORTED_FORMAT:
323 324 325 326 327 328
                skipped_photos.add(batch_result);
            break;

            case ImportResult.NOT_A_FILE:
            case ImportResult.NOT_AN_IMAGE:
                skipped_files.add(batch_result);
329 330 331 332 333 334
            break;
            
            case ImportResult.PHOTO_EXISTS:
                already_imported.add(batch_result);
            break;
            
335 336 337 338
            case ImportResult.CAMERA_ERROR:
                camera_failed.add(batch_result);
            break;
            
339 340 341 342
            case ImportResult.FILE_WRITE_ERROR:
                write_failed.add(batch_result);
            break;
            
343 344 345 346 347
            default:
                failed.add(batch_result);
            break;
        }
        
348 349
        if (reported)
            all.add(batch_result);
350 351 352
    }
}

353
// BatchImport performs the work of taking a file (supplied by BatchImportJob's) and properly importing
354 355
// it into the system, including database additions and thumbnail creation.  It can be monitored by
// multiple observers, but only one ImportReporter can be registered.
356 357 358 359 360
//
// TODO: With background threads. the better way to implement this is via a FSM (finite state 
// machine) that exists in states and responds to various events thrown off by the background
// jobs.  However, getting this code to a point that it works with threads is task enough, so it
// will have to wait (especially since we'll want to write a generic FSM engine).
361
public class BatchImport : Object {
362
    private const int WORK_SNIFFER_THROBBER_MSEC = 125;
363
    
364 365
    public const int REPORT_EVERY_N_PREPARED_FILES = 100;
    public const int REPORT_PREPARED_FILES_EVERY_N_MSEC = 3000;
366 367 368 369 370 371
    
    private const int READY_SOURCES_COUNT_OVERFLOW = 10;
    
    private const int DISPLAY_QUEUE_TIMER_MSEC = 125;
    private const int DISPLAY_QUEUE_HYSTERESIS_OVERFLOW = (3 * 1000) / DISPLAY_QUEUE_TIMER_MSEC;
    
372 373
    private static Workers feeder_workers = new Workers(1, false);
    private static Workers import_workers = new Workers(Workers.thread_per_cpu_minus_one(), false);
374
    
375
    private Gee.Iterable<BatchImportJob> jobs;
376
    private BatchImportRoll import_roll;
377
    private string name;
378 379
    private uint64 completed_bytes = 0;
    private uint64 total_bytes = 0;
380
    private unowned ImportReporter reporter;
381 382
    private ImportManifest manifest;
    private bool scheduled = false;
383 384 385 386
    private bool completed = false;
    private int file_imports_to_perform = -1;
    private int file_imports_completed = 0;
    private Cancellable? cancellable = null;
387
    private ulong last_preparing_ms = 0;
388
    private Gee.HashSet<File> skipset;
389
#if !NO_DUPE_DETECTION
390
    private Gee.HashSet<string> imported_full_md5 = new Gee.HashSet<string>();
391
#endif
392 393
    private uint throbber_id = 0;
    private int max_outstanding_import_jobs = Workers.thread_per_cpu_minus_one();
394
    private bool untrash_duplicates = true;
395
    private bool mark_duplicates_online = true;
396 397 398
    
    // These queues are staging queues, holding batches of work that must happen in the import
    // process, working on them all at once to minimize overhead.
399 400 401 402 403
    private Gee.List<PreparedFile> ready_files = new Gee.LinkedList<PreparedFile>();
    private Gee.List<CompletedImportObject> ready_thumbnails =
        new Gee.LinkedList<CompletedImportObject>();
    private Gee.List<CompletedImportObject> display_imported_queue =
        new Gee.LinkedList<CompletedImportObject>();
404
    private Gee.List<CompletedImportObject> ready_sources = new Gee.LinkedList<CompletedImportObject>();
405 406 407
    
    // Called at the end of the batched jobs.  Can be used to report the result of the import
    // to the user.  This is called BEFORE import_complete is fired.
408
    public delegate void ImportReporter(ImportManifest manifest, BatchImportRoll import_roll);
409
    
410
    // Called once, when the scheduled task begins
411 412
    public signal void starting();
    
413 414 415 416 417 418 419
    // Called repeatedly while preparing the launched BatchImport
    public signal void preparing();
    
    // Called repeatedly to report the progress of the BatchImport (but only called after the
    // last "preparing" signal)
    public signal void progress(uint64 completed_bytes, uint64 total_bytes);
    
420 421
    // Called for each Photo or Video imported to the system. For photos, the pixbuf is
    // screen-sized and rotated. For videos, the pixbuf is a frame-grab of the first frame.
422 423 424
    //
    // The to_follow number is the number of queued-up sources to expect following this signal
    // in one burst.
425
    public signal void imported(MediaSource source, Gdk.Pixbuf pixbuf, int to_follow);
426
    
427 428 429 430
    // Called when a fatal error occurs that stops the import entirely.  Remaining jobs will be
    // failed and import_complete() is still fired.
    public signal void fatal_error(ImportResult result, string message);
    
431 432 433 434
    // Called when a job fails.  import_complete will also be called at the end of the batch
    public signal void import_job_failed(BatchImportResult result);
    
    // Called at the end of the batched jobs; this will be signalled exactly once for the batch
435
    public signal void import_complete(ImportManifest manifest, BatchImportRoll import_roll);
436 437

    public BatchImport(Gee.Iterable<BatchImportJob> jobs, string name, ImportReporter? reporter,
438
        Gee.ArrayList<BatchImportJob>? prefailed = null,
439
        Gee.ArrayList<BatchImportJob>? pre_already_imported = null,
440 441
        Cancellable? cancellable = null, BatchImportRoll? import_roll = null,
        ImportManifest? skip_manifest = null) {
442 443 444 445
        this.jobs = jobs;
        this.name = name;
        this.reporter = reporter;
        this.manifest = new ImportManifest(prefailed, pre_already_imported);
446
        this.cancellable = (cancellable != null) ? cancellable : new Cancellable();
447
        this.import_roll = import_roll != null ? import_roll : new BatchImportRoll();
448
        
449 450
        if (skip_manifest != null) {
            skipset = new Gee.HashSet<File>(file_hash, file_equal);
451 452
            foreach (MediaSource source in skip_manifest.imported) {
                skipset.add(source.get_file());
453 454 455
            }
        }
        
456
        // watch for user exit in the application
457
        Application.get_instance().exiting.connect(user_halt);
458 459
        
        // Use a timer to report imported photos to observers
460
        Timeout.add(DISPLAY_QUEUE_TIMER_MSEC, display_imported_timer);
461 462
    }
    
463
    ~BatchImport() {
464 465 466
#if TRACE_DTORS
        debug("DTOR: BatchImport (%s)", name);
#endif
467
        Application.get_instance().exiting.disconnect(user_halt);
468 469
    }
    
470 471 472 473
    public string get_name() {
        return name;
    }
    
474 475
    public void user_halt() {
        cancellable.cancel();
476 477
    }
    
478 479 480 481 482 483 484 485
    public bool get_untrash_duplicates() {
        return untrash_duplicates;
    }
    
    public void set_untrash_duplicates(bool untrash_duplicates) {
        this.untrash_duplicates = untrash_duplicates;
    }
    
486 487 488 489 490 491 492 493
    public bool get_mark_duplicates_online() {
        return mark_duplicates_online;
    }
    
    public void set_mark_duplicates_online(bool mark_duplicates_online) {
        this.mark_duplicates_online = mark_duplicates_online;
    }
    
494 495
    private void log_status(string where) {
#if TRACE_IMPORT
496
        debug("%s: to_perform=%d completed=%d ready_files=%d ready_thumbnails=%d display_queue=%d ready_sources=%d",
497
            where, file_imports_to_perform, file_imports_completed, ready_files.size,
498
            ready_thumbnails.size, display_imported_queue.size, ready_sources.size);
499 500
        debug("%s workers: feeder=%d import=%d", where, feeder_workers.get_pending_job_count(),
            import_workers.get_pending_job_count());
501 502 503
#endif
    }
    
504 505 506 507 508 509 510 511 512 513 514 515 516 517
    private bool report_failure(BatchImportResult import_result) {
        bool proceed = true;
        
        manifest.add_result(import_result);
        
        if (import_result.result != ImportResult.SUCCESS) {
            import_job_failed(import_result);
            
            if (import_result.file != null && !import_result.result.is_abort()) {
                uint64 filesize = 0;
                try {
                    // A BatchImportResult file is guaranteed to be a single file
                    filesize = query_total_file_size(import_result.file);
                } catch (Error err) {
518
                    warning("Unable to query file size of %s: %s", import_result.file.get_path(),
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
                        err.message);
                }
                
                report_progress(filesize);
            }
        }
        
        // fire this signal only once, and only on non-user aborts
        if (import_result.result.is_nonuser_abort() && proceed) {
            fatal_error(import_result.result, import_result.errmsg);
            proceed = false;
        }
        
        return proceed;
    }
    
    private void report_progress(uint64 increment_of_progress) {
        completed_bytes += increment_of_progress;
        
        // only report "progress" if progress has been made (and enough time has progressed),
        // otherwise still preparing
        if (completed_bytes == 0) {
            ulong now = now_ms();
            if (now - last_preparing_ms > 250) {
                last_preparing_ms = now;
                preparing();
            }
        } else if (increment_of_progress > 0) {
547 548 549 550 551
            ulong now = now_ms();
            if (now - last_preparing_ms > 250) {
                last_preparing_ms = now;
                progress(completed_bytes, total_bytes);
            }
552 553 554
        }
    }
    
555 556 557 558
    private bool report_failures(BackgroundImportJob background_job) {
        bool proceed = true;
        
        foreach (BatchImportResult import_result in background_job.failed) {
559
            if (!report_failure(import_result))
560
                proceed = false;
561
        }
562 563
        
        return proceed;
564 565
    }
    
566 567 568 569 570 571
    private void report_completed(string where) {
        if (completed)
            error("Attempted to complete already-completed import: %s", where);
        
        completed = true;
        
572
        flush_ready_sources();
573 574
        
        log_status("Import completed: %s".printf(where));
575 576 577
        
        // report completed to the reporter (called prior to the "import_complete" signal)
        if (reporter != null)
578
            reporter(manifest, import_roll);
579
        
580
        import_complete(manifest, import_roll);
581 582 583 584 585 586 587 588 589 590 591 592 593
    }
    
    // This should be called whenever a file's import process is complete, successful or otherwise
    private void file_import_complete() {
        // mark this job as completed
        file_imports_completed++;
        if (file_imports_to_perform != -1)
            assert(file_imports_completed <= file_imports_to_perform);
        
        // because notifications can come in after completions, have to watch if this is the
        // last file
        if (file_imports_to_perform != -1 && file_imports_completed == file_imports_to_perform)
            report_completed("completed preparing files, all outstanding imports completed");
594 595 596 597 598 599 600 601 602
    }
    
    public void schedule() {
        assert(scheduled == false);
        scheduled = true;
        
        starting();
        
        // fire off a background job to generate all FileToPrepare work
603 604 605
        feeder_workers.enqueue(new WorkSniffer(this, jobs, on_work_sniffed_out, cancellable,
            on_sniffer_cancelled, skipset));
        throbber_id = Timeout.add(WORK_SNIFFER_THROBBER_MSEC, on_sniffer_working);
606 607
    }
    
608 609 610 611
    //
    // WorkSniffer stage
    //
    
612
    private bool on_sniffer_working() {
613
        report_progress(0);
614 615
        
        return true;
616 617 618
    }
    
    private void on_work_sniffed_out(BackgroundJob j) {
619 620
        assert(!completed);
        
621 622
        WorkSniffer sniffer = (WorkSniffer) j;
        
623 624
        log_status("on_work_sniffed_out");
        
625 626
        if (!report_failures(sniffer) || sniffer.files_to_prepare.size == 0) {
            report_completed("work sniffed out: nothing to do");
627
            
628
            return;
629
        }
630
        
631 632
        total_bytes = sniffer.total_bytes;
        
633 634 635
        // submit single background job to go out and prepare all the files, reporting back when/if
        // they're ready for import; this is important because gPhoto can't handle multiple accesses
        // to a camera without fat locking, and it's just not worth it.  Serializing the imports
636 637
        // also means the user sees the photos coming in in (roughly) the order they selected them
        // on the screen
638
        PrepareFilesJob prepare_files_job = new PrepareFilesJob(this, sniffer.files_to_prepare, 
639 640
            on_file_prepared, on_files_prepared, cancellable, on_file_prepare_cancelled);
        
641 642 643 644 645 646
        feeder_workers.enqueue(prepare_files_job);
        
        if (throbber_id > 0) {
            Source.remove(throbber_id);
            throbber_id = 0;
        }
647 648
    }
    
649
    private void on_sniffer_cancelled(BackgroundJob j) {
650 651
        assert(!completed);
        
652 653
        WorkSniffer sniffer = (WorkSniffer) j;
        
654 655
        log_status("on_sniffer_cancelled");
        
656 657
        report_failures(sniffer);
        report_completed("work sniffer cancelled");
658 659 660 661 662
        
        if (throbber_id > 0) {
            Source.remove(throbber_id);
            throbber_id = 0;
        }
663
    }
664
    
665 666 667 668
    //
    // PrepareFiles stage
    //
    
669 670 671 672 673
    private void flush_import_jobs() {
        // flush ready thumbnails before ready files because PreparedFileImportJob is more intense
        // than ThumbnailWriterJob; reversing this order causes work to back up in ready_thumbnails
        // and takes longer for the user to see progress (which is only reported after the thumbnail
        // has been written)
674
        while (ready_thumbnails.size > 0 && import_workers.get_pending_job_count() < max_outstanding_import_jobs) {
675 676
            import_workers.enqueue(new ThumbnailWriterJob(this, ready_thumbnails.remove_at(0),
                on_thumbnail_writer_completed, cancellable, on_thumbnail_writer_cancelled));
677 678
        }
        
679
        while(ready_files.size > 0 && import_workers.get_pending_job_count() < max_outstanding_import_jobs) {
680 681 682
            import_workers.enqueue(new PreparedFileImportJob(this, ready_files.remove_at(0),
                import_roll.import_id, on_import_files_completed, cancellable,
                on_import_files_cancelled));
683
        }
684 685 686 687
    }
    
    // This checks for duplicates in the current import batch, which may not already be in the
    // library and therefore not detected there.
688 689 690
    private bool is_in_current_import(PreparedFile prepared_file) {
#if !NO_DUPE_DETECTION
        if (prepared_file.full_md5 != null
691 692 693
            && imported_full_md5.contains(prepared_file.full_md5)) {            
            
            return true;
694 695 696 697
        }
        
        // add for next one
        if (prepared_file.full_md5 != null)
698
            imported_full_md5.add(prepared_file.full_md5);
699 700 701 702
#endif
        return false;
    }
    
703
    // Called when a cluster of files are located and deemed proper for import by PrepareFiledJob
704
    private void on_file_prepared(BackgroundJob j, NotificationObject? user) {
705 706
        assert(!completed);
        
707
        PreparedFileCluster cluster = (PreparedFileCluster) user;
708
        
709 710
        log_status("on_file_prepared (%d files)".printf(cluster.list.size));
        
711 712 713
        process_prepared_files.begin(cluster.list);
    }
    
714 715
    // TODO: This logic can be cleaned up.  Attempt to remove all calls to
    // the database, as it's a blocking call (use in-memory lookups whenever possible)
716 717 718 719 720
    private async void process_prepared_files(Gee.List<PreparedFile> list) {
        foreach (PreparedFile prepared_file in list) {
            Idle.add(process_prepared_files.callback);
            yield;
            
721 722
            BatchImportResult import_result = null;
            
723 724 725 726 727 728 729 730 731 732
            // first check if file is already registered as a media object
            
            LibraryPhotoSourceCollection.State photo_state;
            LibraryPhoto? photo = LibraryPhoto.global.get_state_by_file(prepared_file.file,
                out photo_state);
            if (photo != null) {
                switch (photo_state) {
                    case LibraryPhotoSourceCollection.State.ONLINE:
                    case LibraryPhotoSourceCollection.State.OFFLINE:
                    case LibraryPhotoSourceCollection.State.EDITABLE:
733
                    case LibraryPhotoSourceCollection.State.DEVELOPER:
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
                        import_result = new BatchImportResult(prepared_file.job, prepared_file.file,
                            prepared_file.file.get_path(), prepared_file.file.get_path(),
                            ImportResult.PHOTO_EXISTS);
                        
                        if (photo_state == LibraryPhotoSourceCollection.State.OFFLINE)
                            photo.mark_online();
                    break;
                    
                    case LibraryPhotoSourceCollection.State.TRASH:
                        // let the code below deal with it
                    break;
                    
                    default:
                        error("Unknown LibraryPhotoSourceCollection state: %s", photo_state.to_string());
                }
            }
            
            if (import_result != null) {
                report_failure(import_result);
                file_import_complete();
                
                continue;
            }
            
            VideoSourceCollection.State video_state;
            Video? video = Video.global.get_state_by_file(prepared_file.file, out video_state);
            if (video != null) {
                switch (video_state) {
                    case VideoSourceCollection.State.ONLINE:
                    case VideoSourceCollection.State.OFFLINE:
                        import_result = new BatchImportResult(prepared_file.job, prepared_file.file,
                            prepared_file.file.get_path(), prepared_file.file.get_path(),
                            ImportResult.PHOTO_EXISTS);
                        
                        if (video_state == VideoSourceCollection.State.OFFLINE)
                            video.mark_online();
                    break;
                    
                    case VideoSourceCollection.State.TRASH:
                        // let the code below deal with it
                    break;
                    
                    default:
                        error("Unknown VideoSourceCollection state: %s", video_state.to_string());
                }
            }
            
            if (import_result != null) {
                report_failure(import_result);
                file_import_complete();
                
                continue;
            }
            
            // now check if the file is a duplicate
            
790 791
            if (prepared_file.is_video && Video.is_duplicate(prepared_file.file, prepared_file.full_md5)) {
                import_result = new BatchImportResult(prepared_file.job, prepared_file.file, 
792 793
                    prepared_file.file.get_path(), prepared_file.file.get_path(), 
                    ImportResult.PHOTO_EXISTS);
794
            }
795
            
796 797 798 799 800 801
            if (is_in_current_import(prepared_file)) {
                // this looks for duplicates within the import set, since Photo.is_duplicate
                // only looks within already-imported photos for dupes
                import_result = new BatchImportResult(prepared_file.job, prepared_file.file,
                    prepared_file.file.get_path(), prepared_file.file.get_path(), 
                    ImportResult.PHOTO_EXISTS);
802 803 804 805 806 807
            } else if (Photo.is_duplicate(prepared_file.file, null, prepared_file.full_md5,
                prepared_file.file_format)) {
                if (untrash_duplicates) {
                    // If a file is being linked and has a dupe in the trash, we take it out of the trash
                    // and revert its edits.
                    photo = LibraryPhoto.global.get_trashed_by_file(prepared_file.file);
808
                    
809 810
                    if (photo == null && prepared_file.full_md5 != null)
                        photo = LibraryPhoto.global.get_trashed_by_md5(prepared_file.full_md5);
811
                    
812 813 814 815
                    if (photo != null) {
                        debug("duplicate linked photo found in trash, untrashing and removing transforms for %s",
                            prepared_file.file.get_path());
                        
816
                        photo.set_master_file(prepared_file.file);
817 818
                        photo.untrash();
                        photo.remove_all_transformations();
819 820 821 822 823 824 825 826 827 828 829 830 831
                    }
                }
                
                if (photo == null && mark_duplicates_online) {
                    // if a duplicate is found marked offline, make it online
                    photo = LibraryPhoto.global.get_offline_by_file(prepared_file.file);
                    
                    if (photo == null && prepared_file.full_md5 != null)
                        photo = LibraryPhoto.global.get_offline_by_md5(prepared_file.full_md5);
                    
                    if (photo != null) {
                        debug("duplicate photo found marked offline, marking online: %s",
                            prepared_file.file.get_path());
832
                        
833 834
                        photo.set_master_file(prepared_file.file);
                        photo.mark_online();
835
                    }
836 837
                }
                
838 839 840 841 842 843 844 845 846 847 848 849 850 851
                if (photo != null) {
                    import_result = new BatchImportResult(prepared_file.job, prepared_file.file,
                        prepared_file.file.get_path(), prepared_file.file.get_path(), 
                        ImportResult.SUCCESS);
                    
                    manifest.imported.add(photo);
                    manifest.add_result(import_result);
                    
                    report_progress(photo.get_filesize());
                    file_import_complete();
                    
                    continue;
                }
                
852
                debug("duplicate photo detected, not importing %s", prepared_file.file.get_path());
853
                
854 855 856 857 858
                // Ticket #3163 - display full path, not just folder when
                // can't import, due to duplicate.
                //
                // Instead of using the job's source or destination identifiers, which would be 
                // directory the image lived in, we now use the exact path to the file.
859
                import_result = new BatchImportResult(prepared_file.job, prepared_file.file, 
860
                    prepared_file.file.get_path(), prepared_file.file.get_path(), ImportResult.PHOTO_EXISTS); 
861
            }
862
            
863 864 865 866 867
            if (import_result != null) {
                report_failure(import_result);
                file_import_complete();
                
                continue;
868
            }
869
            
870
            report_progress(0);
871
            ready_files.add(prepared_file);
872 873
        }
        
874
        flush_import_jobs();
875 876
    }
    
877
    private void done_preparing_files(BackgroundJob j, string caller) {
878 879
        assert(!completed);
        
880 881 882 883 884 885
        PrepareFilesJob prepare_files_job = (PrepareFilesJob) j;
        
        report_failures(prepare_files_job);
        
        // mark this job as completed and record how many file imports must finish to be complete
        file_imports_to_perform = prepare_files_job.prepared_files;
886 887
        assert(file_imports_to_perform >= file_imports_completed);
        
888 889
        log_status(caller);
        
890
        // this call can result in report_completed() being called, so don't call twice
891
        flush_import_jobs();
892 893 894
        
        // if none prepared, then none outstanding (or will become outstanding, depending on how
        // the notifications are queued)
895
        if (file_imports_to_perform == 0 && !completed)
896
            report_completed("no files prepared for import");
897
        else if (file_imports_completed == file_imports_to_perform && !completed)
898 899 900
            report_completed("completed preparing files, all outstanding imports completed");
    }
    
901 902 903 904
    private void on_files_prepared(BackgroundJob j) {
        done_preparing_files(j, "on_files_prepared");
    }
    
905
    private void on_file_prepare_cancelled(BackgroundJob j) {
906 907 908 909 910 911 912 913
        done_preparing_files(j, "on_file_prepare_cancelled");
    }
    
    //
    // Files ready for import stage
    //
    
    private void on_import_files_completed(BackgroundJob j) {
914 915
        assert(!completed);
        
916
        PreparedFileImportJob job = (PreparedFileImportJob) j;
917
        
918
        log_status("on_import_files_completed");
919
        
920 921
        // should be ready in some form
        assert(job.not_ready == null);
922
        
923 924 925
        // mark failed photo
        if (job.failed != null) {
            assert(job.failed.result != ImportResult.SUCCESS);
926
            
927
            report_failure(job.failed);
928 929
            file_import_complete();
        }
930
        
931 932
        // resurrect ready photos before adding to database and rest of system ... this is more
        // efficient than doing them one at a time
933 934 935
        if (job.ready != null) {
            assert(job.ready.batch_result.result == ImportResult.SUCCESS);
            
936
            Tombstone? tombstone = Tombstone.global.locate(job.ready.final_file);
937
            if (tombstone != null)
938
                Tombstone.global.resurrect(tombstone);
939
        
940 941 942 943
            // import ready photos into database
            MediaSource? source = null;
            if (job.ready.is_video) {
                job.ready.batch_result.result = Video.import_create(job.ready.video_import_params,
944 945
                    out source);
            } else {
946
                job.ready.batch_result.result = LibraryPhoto.import_create(job.ready.photo_import_params,
947
                    out source);
948
                Photo photo = source as Photo;
Eric Gregory's avatar
Eric Gregory committed
949 950 951 952 953 954 955 956 957 958 959 960 961 962
                
                if (job.ready.photo_import_params.final_associated_file != null) {
                    // Associate RAW+JPEG in database.
                    BackingPhotoRow bpr = new BackingPhotoRow();
                    bpr.file_format = PhotoFileFormat.JFIF;
                    bpr.filepath = job.ready.photo_import_params.final_associated_file.get_path();
                    debug("Associating %s with sibbling %s", ((Photo) source).get_file().get_path(),
                        bpr.filepath);
                    try {
                        ((Photo) source).add_backing_photo_for_development(RawDeveloper.CAMERA, bpr);
                    } catch (Error e) {
                        warning("Unable to associate JPEG with RAW. File: %s Error: %s", 
                            bpr.filepath, e.message);
                    }
963 964 965 966 967 968 969
                }
                
                // Set the default developer for raw photos
                if (photo.get_master_file_format() == PhotoFileFormat.RAW) {
                    RawDeveloper d = Config.Facade.get_instance().get_default_raw_developer();
                    if (d == RawDeveloper.CAMERA && !photo.is_raw_developer_available(d))
                        d = RawDeveloper.EMBEDDED;
970
                    
971
                    photo.set_default_raw_developer(d);
Eric Gregory's avatar
Eric Gregory committed
972
                }
973
            }
974 975 976
            
            if (job.ready.batch_result.result != ImportResult.SUCCESS) {
                debug("on_import_file_completed: %s", job.ready.batch_result.result.to_string());
977
                
978
                report_failure(job.ready.batch_result);
979 980
                file_import_complete();
            } else {
981
                ready_thumbnails.add(new CompletedImportObject(source, job.ready.get_thumbnails(),
982
                    job.ready.prepared_file.job, job.ready.batch_result));
983 984 985
            }
        }
        
986
        flush_import_jobs();
987 988
    }
    
989
    private void on_import_files_cancelled(BackgroundJob j) {
990 991
        assert(!completed);
        
992
        PreparedFileImportJob job = (PreparedFileImportJob) j;
993
        
994
        log_status("on_import_files_cancelled");
995
        
996 997
        if (job.not_ready != null) {
            report_failure(new BatchImportResult(job.not_ready.job, job.not_ready.file,
998 999
                job.not_ready.file.get_path(), job.not_ready.file.get_path(), 
                ImportResult.USER_ABORT));
1000 1001
            file_import_complete();
        }
1002
        
1003 1004
        if (job.failed != null) {
            report_failure(job.failed);
1005 1006
            file_import_complete();
        }
1007
        
1008 1009
        if (job.ready != null) {
            report_failure(job.ready.abort());
1010
            file_import_complete();
1011 1012
        }
        
1013
        flush_import_jobs();
1014 1015
    }
    
1016 1017 1018
    //
    // ThumbnailWriter stage
    //
1019 1020 1021
    // Because the LibraryPhoto has been created at this stage, any cancelled work must also
    // destroy the LibraryPhoto.
    //
1022 1023
    
    private void on_thumbnail_writer_completed(BackgroundJob j) {
1024 1025
        assert(!completed);
        
1026
        ThumbnailWriterJob job = (ThumbnailWriterJob) j;
1027
        CompletedImportObject completed = job.completed_import_source;
1028
        
1029
        log_status("on_thumbnail_writer_completed");
1030
        
1031 1032 1033 1034 1035 1036 1037 1038
        if (completed.batch_result.result != ImportResult.SUCCESS) {
            warning("Failed to import %s: unable to write thumbnails (%s)",
                completed.source.to_string(), completed.batch_result.result.to_string());
            
            if (completed.source is LibraryPhoto)
                LibraryPhoto.import_failed(completed.source as LibraryPhoto);
            else if (completed.source is Video)
                Video.import_failed(completed.source as Video);
1039

1040 1041 1042
            report_failure(completed.batch_result);
            file_import_complete();
        } else {
1043
            manifest.imported.add(completed.source);
1044 1045 1046
            manifest.add_result(completed.batch_result);
            
            display_imported_queue.add(completed);
1047
        }
1048 1049
        
        flush_import_jobs();
1050 1051 1052 1053
    }
    
    private void on_thumbnail_writer_cancelled(BackgroundJob j) {
        assert(!completed);
1054
        
1055
        ThumbnailWriterJob job = (ThumbnailWriterJob) j;
1056
        CompletedImportObject completed = job.completed_import_source;
1057
        
1058
        log_status("on_thumbnail_writer_cancelled");
1059
        
1060 1061 1062 1063
        if (completed.source is LibraryPhoto)
            LibraryPhoto.import_failed(completed.source as LibraryPhoto);
        else if (completed.source is Video)
            Video.import_failed(completed.source as Video);
1064

1065 1066 1067 1068
        report_failure(completed.batch_result);
        file_import_complete();
        
        flush_import_jobs();
1069 1070 1071
    }
    
    //
1072
    // Display imported sources and integrate into system
1073 1074
    //
    
1075 1076
    private void flush_ready_sources() {
        if (ready_sources.size == 0)
1077
            return;
1078
        
1079 1080 1081
        // the user_preview and thumbnails in the CompletedImportObjects are not available at 
        // this stage
        
1082 1083
        log_status("flush_ready_sources (%d)".printf(ready_sources.size));
        
1084 1085 1086 1087 1088 1089 1090
        Gee.ArrayList<MediaSource> all = new Gee.ArrayList<MediaSource>();
        Gee.ArrayList<LibraryPhoto> photos = new Gee.ArrayList<LibraryPhoto>();
        Gee.ArrayList<Video> videos = new Gee.ArrayList<Video>();
        Gee.HashMap<MediaSource, BatchImportJob> completion_list =
            new Gee.HashMap<MediaSource, BatchImportJob>();
        foreach (CompletedImportObject completed in ready_sources) {
            all.add(completed.source);
1091
            
1092 1093 1094 1095
            if (completed.source is LibraryPhoto)
                photos.add((LibraryPhoto) completed.source);
            else if (completed.source is Video)
                videos.add((Video) completed.source);
1096
            
1097
            completion_list.set(completed.source, completed.original_job);
1098
        }
1099
        
1100 1101 1102
        MediaCollectionRegistry.get_instance().begin_transaction_on_all();
        Event.global.freeze_notifications();
        Tag.global.freeze_notifications();
1103
        
1104 1105
        LibraryPhoto.global.import_many(photos);
        Video.global.import_many(videos);
1106
        
1107 1108 1109 1110 1111 1112 1113 1114 1115
        // allow the BatchImportJob to perform final work on the MediaSource
        foreach (MediaSource media in completion_list.keys) {
            try {
                completion_list.get(media).complete(media, import_roll);
            } catch (Error err) {
                warning("Completion error when finalizing import of %s: %s", media.to_string(),
                    err.message);
            }
        }
1116
        
1117 1118
        // generate events for MediaSources not yet assigned
        Event.generate_many_events(all, import_roll.generated_events);
1119
        
1120 1121 1122
        Tag.global.thaw_notifications();
        Event.global.thaw_notifications();
        MediaCollectionRegistry.get_instance().commit_transaction_on_all();
1123
        
1124
        ready_sources.clear();
1125 1126 1127 1128 1129
    }
    
    // This is called throughout the import process to notify watchers of imported photos in such
    // a way that the GTK event queue gets a chance to operate.
    private bool display_imported_timer() {
1130
        if (display_imported_queue.size == 0)
1131 1132 1133 1134 1135 1136 1137
            return !completed;
        
        if (cancellable.is_cancelled())
            debug("Importing %d photos at once", display_imported_queue.size);
        
        log_status("display_imported_timer");
        
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
        // only display one at a time, so the user can see them come into the library in order.
        // however, if the queue backs up to the hysteresis point (currently defined as more than
        // 3 seconds wait for the last photo on the queue), then begin doing them in increasingly
        // larger chunks, to stop the queue from growing and then to get ahead of the other
        // import cycles.
        //
        // if cancelled, want to do as many as possible, but want to relinquish the thread to
        // keep the system active
        int total = 1;
        if (!cancellable.is_cancelled()) {
            if (display_imported_queue.size > DISPLAY_QUEUE_HYSTERESIS_OVERFLOW)
1149 1150
                total = 
                    1 << ((display_imported_queue.size / DISPLAY_QUEUE_HYSTERESIS_OVERFLOW) + 2).clamp(0, 16);
1151 1152
        } else {
            // do in overflow-sized chunks
1153
            total = DISPLAY_QUEUE_HYSTERESIS_OVERFLOW;
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
        }
        
        total = int.min(total, display_imported_queue.size);
        
#if TRACE_IMPORT
        if (total > 1) {
            debug("DISPLAY IMPORT QUEUE: hysteresis, dumping %d/%d media sources", total,
                display_imported_queue.size);
        }
#endif
        
        // post-decrement because the 0-based total is used when firing "imported"
        while (total-- > 0) {
1167
            CompletedImportObject completed_object = display_imported_queue.remove_at(0);
1168
            
1169 1170 1171 1172 1173 1174 1175
            // stash preview for reporting progress
            Gdk.Pixbuf user_preview = completed_object.user_preview;
            
            // expensive pixbufs no longer needed
            completed_object.user_preview = null;
            completed_object.thumbnails = null;
            
1176 1177
            // Stage the number of ready media objects to incorporate into the system rather than
            // doing them one at a time, to keep the UI thread responsive.
1178
            // NOTE: completed_object must be added prior to file_import_complete()
1179
            ready_sources.add(completed_object);
1180
            
1181
            imported(completed_object.source, user_preview, total);
1182 1183
            report_progress(completed_object.source.get_filesize());
            file_import_complete();
1184
        }
1185
        
1186
        if (ready_sources.size >= READY_SOURCES_COUNT_OVERFLOW || cancellable.is_cancelled())
1187
            flush_ready_sources();
1188
        
1189
        return true;
1190 1191
    }
}
1192

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208