# How to Select and Open DICOM Files

**Date**: 2025-01-13
**Status**: Current Implementation Guide

## Current Workflow

### Opening DICOM Files via Sidebar

1. **Open the Sidebar**
   - Click the extension icon in Chrome toolbar
   - The sidebar opens on the right side of the browser

2. **Select a Project**
   - Browse or search for a project in the project list
   - Click on a project to view its documents

3. **Find DICOM Files**
   - Browse the document list in the sidebar
   - Look for files with `.dcm` or `.dicom` extensions
   - DICOM files may also be identified by their filename or MIME type

4. **Click "Download" Button**
   - Each document has a "Download" button in the sidebar
   - Clicking it will:
     - Queue the file for download
     - Download the file from Filevine
     - Store it in IndexedDB
     - **Automatically open it in the DICOM viewer** (if `autoOpen: true`)

5. **Viewer Opens Automatically**
   - A new tab opens with the DICOM viewer
   - The image loads and renders
   - You can interact with the image using controls

### Using the Folder Browser (New Feature!)

Once you've opened a DICOM series in the viewer, you can browse and load other DICOM series from the same project:

1. **Open Folder Browser**
   - Click the 📁 folder icon in the top-left corner of the viewer
   - The folder browser sidebar opens on the left

2. **Browse Folders**
   - Folders are displayed in a hierarchical tree
   - Only folders containing DICOM files are shown
   - Click ▶ to expand a folder and see its subfolders
   - Click ▼ to collapse a folder
   - File counts show how many DICOM files are in each folder

3. **Load a DICOM Series**
   - Click on any folder to load its DICOM files as a series
   - The viewer will:
     - Load the first image immediately
     - Generate thumbnails for all images in the series
     - Show series navigation controls
     - Automatically start AI analysis

4. **Navigate Series**
   - Use ◀ ▶ buttons to navigate between images
   - Click thumbnails at the bottom to jump to specific images
   - Scroll with mouse wheel to navigate (when not zooming/adjusting contrast)

### Background Loading

The folder tree loads in the background after the initial DICOM viewer opens, so you can start viewing your first image immediately without waiting for the full folder structure to load.

### Current Code Flow

```javascript
// In sidebar.js (src/sidebar/sidebar.js)
async downloadDocument(docId) {
  const doc = this.state.documents.find(d => String(d.id || d.docId || d.documentId) === String(docId));
  
  await chrome.runtime.sendMessage({
    type: MESSAGE_TYPES.DOWNLOAD_FILE,
    docId: actualDocId,
    projectId: projectId,
    filename: filename,
    mimeType: mimeType,
    autoOpen: true  // ← This triggers automatic viewer opening
  });
}

// In downloads.js
async executeDownload(download) {
  // ... download file ...
  download.status = 'complete';
  
  // Auto-open if requested
  if (download.autoOpen) {
    this.openFile(download.docId);  // ← Opens viewer
  }
}
```

## UI Location

### Sidebar (Side Panel) - Primary Interface
- **Location**: Right side of browser
- **Access**: Click extension icon → Sidebar opens automatically
- **Features**: 
  - Project list with search
  - Document browser with folder navigation
  - Download buttons on each document
  - Download queue status panel
  - File type icons and metadata display

**Note**: The popup UI exists but is not used. All interactions happen through the sidebar.

## File Identification

DICOM files are identified by:
- **File extension**: `.dcm`, `.dicom`
- **MIME type**: `application/dicom`
- **Filename**: May contain "dicom" or "dcm"

The viewer registry (`src/viewers/registry.js`) routes these files to the DICOM viewer.

## Opening Already-Downloaded Files

Currently, there's no UI button to open already-downloaded files, but the functionality exists:

### Using Browser Console

If a file is already downloaded, you can open it programmatically:

```javascript
// In browser console (on any Filevine page)
chrome.runtime.sendMessage({
  type: 'open_viewer',
  docId: 'YOUR_DOC_ID_HERE'
}, (response) => {
  console.log('Viewer opened:', response);
});
```

### Adding a "View" Button (Future Enhancement)

To add a "View" button for already-downloaded files, you would:

1. **Check if file is downloaded**:
   ```javascript
   async isFileDownloaded(docId) {
     const response = await chrome.runtime.sendMessage({
       type: 'check_file_downloaded',
       docId: docId
     });
     return response.exists;
   }
   ```

2. **Add "View" button to UI**:
   ```javascript
   // In renderDocumentList()
   if (await this.isFileDownloaded(docId)) {
     html += `<button class="view-btn" data-doc-id="${docId}">View</button>`;
   }
   ```

3. **Handle click**:
   ```javascript
   viewBtn.addEventListener('click', async () => {
     await chrome.runtime.sendMessage({
       type: MESSAGE_TYPES.OPEN_VIEWER,
       docId: docId
     });
   });
   ```

## Multiple File Selection

Currently, files must be opened one at a time. To select multiple DICOM files:

1. Click "Download" on each file
2. Each file will download and open in its own viewer tab
3. You can have multiple viewer tabs open simultaneously

### Future Enhancement: Batch Selection

To add multi-select functionality:

1. Add checkboxes to document list
2. Add "Download Selected" button
3. Queue multiple downloads
4. Optionally open all in separate tabs or a multi-viewer interface

## Troubleshooting

### File Doesn't Open Automatically

**Check:**
1. Is `autoOpen: true` set in the download request?
2. Check browser console for errors
3. Verify file is actually a DICOM file (check extension/MIME type)
4. Check download manager logs in background service worker

### Viewer Doesn't Load

**Check:**
1. Are Cornerstone libraries bundled locally? (CDN won't work in MV3)
2. Check browser console for CSP errors
3. Verify viewer.html is accessible
4. Check that file was downloaded successfully

### File Too Large

Files > 10MB may not open automatically (data URL limit). They will download to your Downloads folder instead.

**Workaround:**
- Use the `OPEN_VIEWER` message type after download completes
- Or modify `maxDataUrlSize` in `downloads.js`

## Current Limitations

1. **No "View" button** - Must download to view (though auto-opens)
2. **No multi-select** - Files opened one at a time
3. **No "Open without downloading"** - Files must be downloaded first
4. **Large files** - Files > 10MB may not auto-open

## Quick Reference

| Action | Current Method | Future Enhancement |
|--------|---------------|-------------------|
| View DICOM file | Click "Download" (auto-opens) | Add "View" button |
| Open downloaded file | Use console/API | Add "View" button |
| Multiple files | Download each separately | Multi-select + batch open |
| Large files | Downloads to folder | Stream or chunk loading |

## Folder Browser Features

### Collapsible Folder Tree
- Folders with children show expand/collapse icons (▶/▼)
- All folders start collapsed by default for cleaner UI
- Click the arrow icon to expand/collapse without loading the folder
- Hierarchy is shown with visual indentation (16px per level)

### Smart Filtering
- Only folders containing DICOM files are displayed
- Parent folders are kept if any descendant has DICOM files
- Empty folders and folders without DICOM files are automatically filtered out
- Example: If only "DICOM/series-000001" has files, you'll see:
  - Root → DICOM → series-000001 (with file counts)
  - Other empty folders are hidden

### On-Demand File Loading
- Files are downloaded on-demand when you click a folder
- Already-cached files load instantly from IndexedDB
- Progress indicators show during download
- Files are cached for future access

### Technical Details

**Folder Tree API**:
```javascript
// First call gets root folders
POST /api/projects/{projectId}/limitedProjectFolderTree
{ descendantFolderIDs: [] }

// Second call gets complete tree
POST /api/projects/{projectId}/limitedProjectFolderTree
{ descendantFolderIDs: [all folder IDs from first call] }
```

**Document Fetching**:
- Fetches documents for each folder in batches of 5
- Filters for `.dcm` files only
- Stores metadata: docId, filename, size, uploadedBy, uploadedAt

**Filtering Logic**:
1. Identifies folders with DICOM files
2. Marks all parent folders as needed
3. Returns only folders with files or that are ancestors of folders with files

## Related Files

- `src/sidebar/sidebar.js` - **Primary UI** - Sidebar with project/document browser and download buttons
- `src/sidebar/sidebar.html` - Sidebar HTML structure
- `src/sidebar/sidebar.css` - Sidebar styling
- `src/background/downloads.js` - Download manager, folder tree fetching, and file filtering
- `src/background/web-api-client.js` - Filevine API client with folder tree and document endpoints
- `src/viewers/dicom/viewer.js` - DICOM viewer with folder browser UI and series loading
- `src/viewers/dicom/viewer.html` - Viewer HTML with folder browser sidebar
- `src/viewers/registry.js` - Routes files to appropriate viewer
- `src/lib/constants.js` - Message types including `OPEN_VIEWER` and `GET_PROJECT_DICOM_FILES`

**Note**: `src/popup/` files exist but are not used in the current implementation.

## Next Steps for Enhancement

1. **Add "View" button** for already-downloaded files
2. **Add file status indicator** (downloaded/not downloaded)
3. **Add multi-select** with checkboxes
4. **Add "Open without downloading"** option (stream directly to viewer)
5. **Add download queue UI** showing which files are ready to view
