diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 75258e6..3161b19 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -37,3 +37,17 @@ jobs: with: name: FoodSense-${{ runner.os }}-${{ runner.arch }} path: target/FoodSense.jar + + build: + name: Build + needs: [test-and-build] + runs-on: ubuntu-latest + if: always() + steps: + - name: Verify matrix status + run: | + if [ "${{ contains(needs.test-and-build.result, 'failure') || contains(needs.test-and-build.result, 'cancelled') || contains(needs.test-and-build.result, 'skipped') }}" = "true" ]; then + echo "Matrix test-and-build failed or was not successful: ${{ toJson(needs.test-and-build) }}" + exit 1 + fi + echo "All matrix test-and-build runs passed successfully" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cb6b261..ede6ea1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,6 +12,8 @@ jobs: runs-on: ${{ matrix.os }} permissions: contents: write + id-token: write + attestations: write steps: - uses: actions/checkout@v4 @@ -22,19 +24,39 @@ jobs: distribution: 'temurin' cache: maven - - name: Build Fat JAR - shell: bash - run: mvn -Djavacpp.platform.host --batch-mode clean package -DskipTests + - name: Build Fat JAR (Linux Headless) + if: runner.os == 'Linux' + run: | + sudo apt-get install -y xvfb + xvfb-run mvn -Djavacpp.platform.host --batch-mode clean package - - name: Print Output Size + - name: Build Fat JAR (Mac/Windows) + if: runner.os != 'Linux' shell: bash - run: ls -lh target/FoodSense.jar + run: mvn -Djavacpp.platform.host --batch-mode clean package - name: Rename OS/Arch-specific Artifact shell: bash run: mv target/FoodSense.jar target/FoodSense-${{ runner.os }}-${{ runner.arch }}.jar - - name: Upload Artifact to Release + - name: Generate SHA-256 Checksum + shell: bash + run: | + cd target + if command -v sha256sum >/dev/null 2>&1; then + sha256sum FoodSense-${{ runner.os }}-${{ runner.arch }}.jar > FoodSense-${{ runner.os }}-${{ runner.arch }}.jar.sha256 + else + shasum -a 256 FoodSense-${{ runner.os }}-${{ runner.arch }}.jar > FoodSense-${{ runner.os }}-${{ runner.arch }}.jar.sha256 + fi + + - name: Attest Build Provenance + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1 + with: + subject-path: target/FoodSense-${{ runner.os }}-${{ runner.arch }}.jar + + - name: Upload Artifacts to Release uses: softprops/action-gh-release@v2 with: - files: target/FoodSense-${{ runner.os }}-${{ runner.arch }}.jar + files: | + target/FoodSense-${{ runner.os }}-${{ runner.arch }}.jar + target/FoodSense-${{ runner.os }}-${{ runner.arch }}.jar.sha256 diff --git a/README.md b/README.md index dd4e8da..2df0522 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,28 @@ # FoodSense -FoodSense is a Java desktop application that scans barcodes to display nutrition data, ingredients, and Nutri-Score ratings via the Open Food Facts API. +FoodSense is a modern Java desktop application that scans grocery barcodes to display nutrition data, ingredients, allergen warnings, and official Nutri-Score ratings via the Open Food Facts API. ## Features -- Live webcam scanning for real-time barcode detection -- Manual barcode entry for quick lookups -- Auto-generated nutrition facts grid -- Nutri-Score and product image display -- Full ingredient breakdown +- **In-App Live Webcam Scanner:** Built-in modal dialog with illuminated corner reticles, animated scan guide, and automatic barcode detection. +- **Modern Adaptive Theme:** Sleek desktop interface built with FlatLaf, supporting instant Light and Dark mode toggling via an icon button. +- **Nutri-Score Spectrum Bar:** Displays the recognized European 5-pill indicator (A–E) with the active grade elevated and highlighted. +- **Nutrition Facts & Macro Visualizer:** Hero calorie callout, visual macronutrient distribution bar (Carbs, Fats, Protein), and per-100g nutrient table. +- **Allergen Alert Banners:** Highlighted alert cards parsing allergens with clear warning iconography. +- **Hardened Security & Input Validation:** Strict barcode sanitization, Swing HTML injection defenses, bounded async image loading, and SSRF prevention. +- **Headless CLI Mode:** Fast barcode query via `--barcode ` / `-b ` for headless terminal use without initializing GUI components. ## Tech Stack -- **Java 25 / Swing:** Core application and GUI +- **Java 25 / Swing:** Core desktop application and GUI +- **FlatLaf:** Modern cross-platform Look and Feel with Retina HiDPI scaling - **JavaCV (OpenCV):** Webcam capture and computer vision - **ZXing:** Barcode decoding -- **Gson:** JSON parsing +- **Gson:** JSON deserialization ## Deployment & Execution -You can run FoodSense directly without building from source. Download the `.jar` file for your operating system from the [Releases](https://github.com/SamuelIVX/FoodSense/releases) page. +Prebuilt platform-specific JARs are published on the [Releases](https://github.com/SamuelIVX/FoodSense/releases) page for macOS (Apple Silicon ARM64), Windows (x64), and Linux (x64). Requires **Java 25+** installed on your system. @@ -28,11 +31,29 @@ java -jar FoodSense-macOS-ARM64.jar # or FoodSense-Windows-X64.jar / FoodSense-Linux-X64.jar ``` -*Note for macOS users:* The latest releases are built for Apple Silicon (ARM64). When launching via terminal, ensure your terminal application (Terminal.app, iTerm) has Camera permissions granted in `System Settings > Privacy & Security > Camera` for live barcode scanning to function. +### Release Verification -## Building from Source +Every release publishes cryptographic SHA-256 checksums and GitHub build provenance attestations. To verify your downloaded artifact integrity: + +**macOS / Linux:** + +```bash +shasum -a 256 -c FoodSense-macOS-ARM64.jar.sha256 +gh attestation verify FoodSense-macOS-ARM64.jar --repo SamuelIVX/FoodSense +``` + +**Windows (PowerShell):** + +```powershell +Get-FileHash .\FoodSense-Windows-X64.jar -Algorithm SHA256 +gh attestation verify .\FoodSense-Windows-X64.jar --repo SamuelIVX/FoodSense +``` + +Compare the printed hash with the contents of `FoodSense-Windows-X64.jar.sha256`. -If you want to build the project yourself, clone the repository and use Maven. +*Note for macOS users:* When launching via terminal, ensure your terminal application (Terminal.app, iTerm) has Camera permissions granted in `System Settings > Privacy & Security > Camera` for live barcode scanning. + +## Building from Source ```bash git clone https://github.com/SamuelIVX/FoodSense.git @@ -40,9 +61,9 @@ cd FoodSense mvn clean package ``` -The Maven build uses the `maven-shade-plugin` and `javacpp.platform.host` to pull native dependencies for your specific operating system. +The build produces a self-contained fat JAR in `target/` using `maven-shade-plugin`. -### Running locally +### Running Locally Interactive GUI: ```bash @@ -63,25 +84,26 @@ mvn compile exec:java -Dexec.mainClass="com.foodsense.FoodSense" -Dfoodsense.hos ```text src/main/java/com/foodsense/ -├── FoodSense.java # Main entry point (CLI springboard + GUI launcher) -├── ProductApiClient.java # API client and host resolver -├── FoodSenseGUI.java # Swing desktop renderer -├── VideoProcessor.java # Webcam capture and barcode detection -├── Product.java # Product data model -├── Nutriments.java # Nutrition data model -└── ApiResponse.java # API response wrapper +├── FoodSense.java # Main entry point (CLI springboard + GUI launcher) +├── ProductApiClient.java # API client and host resolver +├── FoodSenseGUI.java # Main desktop window & search orchestrator +├── VideoProcessor.java # Webcam capture & barcode detection pipeline +├── Product.java # Product data model +├── Nutriments.java # Nutrition data model +├── ApiResponse.java # API response wrapper +├── security/ +│ ├── SecurityValidator.java # Barcode regex, HTML escaping, and HTTPS URL checks +│ └── SafeImageLoader.java # Bounded async image fetcher (5MB cap, timeouts) +└── ui/ + ├── FoodSenseTheme.java # Design tokens, palette scales, and Light/Dark toggle + ├── CameraScanDialog.java # In-app modal camera scanner with viewfinder reticles + ├── NutriScoreSpectrumView.java # 5-pill Nutri-Score spectrum (A-B-C-D-E) + ├── NutritionLabelPanel.java # Nutrition card with hero calories & macro proportion bar + └── AllergenBanner.java # Danger alert card for allergen warnings ``` ## Troubleshooting -**Camera Issues:** -Ensure no other applications are using the camera and check system permissions. Verify JavaCV native libraries match your OS. - -**Barcode Not Detected:** -Check lighting, ensure the barcode is in focus, and make sure it is fully visible in the frame. - -**Product Not Found:** -The product may not exist in the Open Food Facts database. - -**Build Errors:** -Confirm JDK 25 is installed (`java -version`). Run `mvn clean` and rebuild. +- **Camera Permissions:** Ensure your OS camera permissions allow the terminal or Java process to access video device 0. +- **Barcode Validation:** Barcodes must be 3–48 characters (letters, digits, hyphens, or underscores). +- **Product Not Found:** Products must be cataloged in Open Food Facts. Check the barcode on `world.openfoodfacts.org`. diff --git a/pom.xml b/pom.xml index 9444548..67e13fc 100644 --- a/pom.xml +++ b/pom.xml @@ -10,8 +10,7 @@ 1.0-SNAPSHOT - 25 - 25 + 25 UTF-8 **/VideoProcessorModelTest.java @@ -51,6 +50,12 @@ 3.5.3 + + com.formdev + flatlaf + 3.5.4 + + org.junit.jupiter diff --git a/src/main/java/com/foodsense/FoodSense.java b/src/main/java/com/foodsense/FoodSense.java index 1cf3229..987b287 100644 --- a/src/main/java/com/foodsense/FoodSense.java +++ b/src/main/java/com/foodsense/FoodSense.java @@ -42,7 +42,10 @@ public static void main(String[] args) { return; } - FoodSenseGUI foodSenseGUI = new FoodSenseGUI(); - foodSenseGUI.start(); + javax.swing.SwingUtilities.invokeLater(() -> { + com.foodsense.ui.FoodSenseTheme.initialize(); + FoodSenseGUI foodSenseGUI = new FoodSenseGUI(); + foodSenseGUI.start(); + }); } } diff --git a/src/main/java/com/foodsense/FoodSenseGUI.java b/src/main/java/com/foodsense/FoodSenseGUI.java index 19d2a4c..b67647e 100644 --- a/src/main/java/com/foodsense/FoodSenseGUI.java +++ b/src/main/java/com/foodsense/FoodSenseGUI.java @@ -1,95 +1,104 @@ /* - * Swing UI and Open Food Facts client for FoodSense. - * Builds the sidebar + product view, runs barcode search on a background thread, - * and marshals UI updates onto the EDT via {@link SwingUtilities#invokeLater}. - * Hits the staging host {@code world.openfoodfacts.net} (not {@code .org}). + * Swing UI and Open Food Facts desktop client for FoodSense. + * Builds the slim sidebar and responsive dashboard product view. */ package com.foodsense; +import com.foodsense.security.SafeImageLoader; +import com.foodsense.security.SecurityValidator; +import com.foodsense.ui.AllergenBanner; +import com.foodsense.ui.CameraScanDialog; +import com.foodsense.ui.FoodSenseTheme; +import com.foodsense.ui.IngredientsPanel; +import com.foodsense.ui.NutriScoreSpectrumView; +import com.foodsense.ui.NutritionLabelPanel; + import javax.swing.*; import java.awt.*; -import java.awt.event.*; -import java.net.URI; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.geom.RoundRectangle2D; /** - * Main application window: manual barcode entry, webcam scan handoff, and nutrition display. + * Main application window: manual barcode entry, in-app webcam scan handoff, + * theme toggle, and responsive dashboard nutrition display. */ public class FoodSenseGUI { - // ── Palette ─────────────────────────────────────────────── - private static final Color SIDEBAR_BG = new Color(18, 36, 20); - private static final Color SIDEBAR_ACCENT = new Color(30, 56, 33); - private static final Color PRIMARY = new Color(72, 199, 116); - private static final Color PRIMARY_DARK = new Color(52, 168, 83); - private static final Color BG = new Color(246, 248, 250); - private static final Color CARD = Color.WHITE; - private static final Color BORDER = new Color(226, 232, 240); - private static final Color TEXT = new Color(17, 24, 39); - private static final Color MUTED = new Color(107, 114, 128); - private static final Color DANGER = new Color(220, 38, 38); - private static final Color DANGER_BG = new Color(254, 242, 242); - private static final String F = "Segoe UI"; - - // ── State ───────────────────────────────────────────────── private final ProductApiClient apiClient; - private JFrame frame; - private JPanel root; - private JPanel contentArea; + private JFrame frame; + private JPanel root; + private JPanel contentArea; + + // Sidebar references for instant in-place theme recoloring + private JPanel sidebar; + private JLabel logo; + private JLabel tagline; + private JLabel barcodeLabel; private JTextField searchField; - private JButton searchBtn; - private JButton cameraBtn; - - // Sidebar product widgets (shown after a successful search) + private JButton searchBtn; + private JButton cameraBtn; + private JButton themeToggleBtn; + private JLabel bannerLabel; + + // Product card widgets in sidebar + private JPanel productCard; + private JPanel imgCard; private JLabel imgLabel; - private JLabel nameLabel; - private JLabel brandLabel; - private JPanel scorePanel; + private NutriScoreSpectrumView nutriScoreView; + + private Product currentProduct = null; + private int imageRequestId = 0; /** - * Constructs the main frame and widget tree with a default API client. - * Call {@link #start()} to show the window. + * Constructs the main frame with a default API client. */ public FoodSenseGUI() { this(new ProductApiClient()); } /** - * Constructs the main frame and widget tree with a custom API client. + * Constructs the main frame with a custom API client. * * @param apiClient API client instance */ public FoodSenseGUI(ProductApiClient apiClient) { this.apiClient = apiClient != null ? apiClient : new ProductApiClient(); + FoodSenseTheme.initialize(); build(); } /** - * Makes the main frame visible. Must be called after construction on the EDT - * (or before any other Swing work if this is the first Swing touch in the process). - * - * @example - *
{@code
-     * new FoodSenseGUI().start();
-     * }
+ * Makes the main frame visible. */ public void start() { frame.setVisible(true); } - // ── Frame ───────────────────────────────────────────────── + /** + * Returns the JFrame instance. + * + * @return top-level JFrame + */ + public JFrame getFrame() { + return frame; + } + + // ── Frame Construction ──────────────────────────────────── - /** Creates the JFrame, sidebar, and empty-state content area. */ private void build() { frame = new JFrame("FoodSense"); - frame.setSize(1100, 760); - frame.setMinimumSize(new Dimension(900, 600)); + frame.setSize(1140, 780); + frame.setMinimumSize(new Dimension(960, 640)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); root = new JPanel(new BorderLayout()); - root.setBackground(BG); - root.add(buildSidebar(), BorderLayout.WEST); + root.setBackground(FoodSenseTheme.getBackground()); + + sidebar = buildSidebar(); + root.add(sidebar, BorderLayout.WEST); contentArea = buildEmptyState(); root.add(contentArea, BorderLayout.CENTER); @@ -97,546 +106,416 @@ private void build() { frame.setContentPane(root); } - // ── Sidebar ─────────────────────────────────────────────── + // ── Sidebar (Slim 240px) ────────────────────────────────── - /** - * Builds the dark-green left rail: logo, barcode field, Search/Scan buttons, product card. - * - * @return sidebar panel for {@link BorderLayout#WEST} - */ private JPanel buildSidebar() { - JPanel sidebar = new JPanel(new BorderLayout()); - sidebar.setBackground(SIDEBAR_BG); - sidebar.setPreferredSize(new Dimension(270, 0)); + JPanel bar = new JPanel(new BorderLayout()); + bar.setBackground(FoodSenseTheme.getSidebarBackground()); + bar.setPreferredSize(new Dimension(240, 0)); + bar.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, FoodSenseTheme.getCardBorder())); - // Top: logo + search controls + // Top controls block JPanel top = new JPanel(); top.setLayout(new BoxLayout(top, BoxLayout.Y_AXIS)); - top.setBackground(SIDEBAR_BG); - top.setBorder(BorderFactory.createEmptyBorder(28, 20, 20, 20)); - - JLabel logo = new JLabel("FoodSense"); - logo.setFont(new Font(F, Font.BOLD, 22)); - logo.setForeground(PRIMARY); - logo.setAlignmentX(Component.LEFT_ALIGNMENT); - - JLabel tagline = new JLabel("Nutrition at a glance"); - tagline.setFont(new Font(F, Font.PLAIN, 12)); - tagline.setForeground(new Color(100, 150, 100)); - tagline.setAlignmentX(Component.LEFT_ALIGNMENT); - - top.add(logo); - top.add(Box.createVerticalStrut(3)); - top.add(tagline); - top.add(Box.createVerticalStrut(24)); - top.add(mkSeparator()); - top.add(Box.createVerticalStrut(20)); - - JLabel barcodeLabel = new JLabel("BARCODE"); - barcodeLabel.setFont(new Font(F, Font.BOLD, 10)); - barcodeLabel.setForeground(new Color(90, 130, 90)); + top.setOpaque(false); + top.setBorder(BorderFactory.createEmptyBorder(20, 16, 16, 16)); + + // Header: Logo & Theme Toggle + JPanel headerRow = new JPanel(new BorderLayout()); + headerRow.setOpaque(false); + headerRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, 36)); + + JPanel titleBlock = new JPanel(); + titleBlock.setLayout(new BoxLayout(titleBlock, BoxLayout.Y_AXIS)); + titleBlock.setOpaque(false); + + logo = new JLabel("FoodSense"); + logo.setFont(FoodSenseTheme.getFont(Font.BOLD, 19f)); + logo.setForeground(FoodSenseTheme.getPrimaryAccent()); + titleBlock.add(logo); + + tagline = new JLabel("Nutrition Intelligence"); + tagline.setFont(FoodSenseTheme.getFont(Font.PLAIN, 11f)); + tagline.setForeground(FoodSenseTheme.getSidebarMuted()); + titleBlock.add(tagline); + + headerRow.add(titleBlock, BorderLayout.WEST); + + themeToggleBtn = new JButton(FoodSenseTheme.isDarkMode() ? "☀" : "☾"); + themeToggleBtn.setFont(FoodSenseTheme.getFont(Font.BOLD, 13f)); + themeToggleBtn.setToolTipText("Toggle Light / Dark mode"); + themeToggleBtn.setFocusPainted(false); + themeToggleBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + themeToggleBtn.putClientProperty("JButton.buttonType", "roundRect"); + themeToggleBtn.addActionListener(e -> { + FoodSenseTheme.toggleTheme(frame); + themeToggleBtn.setText(FoodSenseTheme.isDarkMode() ? "☀" : "☾"); + updateComponentColors(); + }); + headerRow.add(themeToggleBtn, BorderLayout.EAST); + top.add(headerRow); + + top.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_16)); + + // Input Label + barcodeLabel = new JLabel("PRODUCT BARCODE"); + barcodeLabel.setFont(FoodSenseTheme.getFont(Font.BOLD, 10f)); + barcodeLabel.setForeground(FoodSenseTheme.getSidebarMuted()); barcodeLabel.setAlignmentX(Component.LEFT_ALIGNMENT); top.add(barcodeLabel); - top.add(Box.createVerticalStrut(7)); + top.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_4)); + // Text Field searchField = new JTextField(); - searchField.setFont(new Font(F, Font.PLAIN, 14)); - searchField.setBackground(SIDEBAR_ACCENT); - searchField.setForeground(Color.WHITE); - searchField.setCaretColor(PRIMARY); - searchField.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createLineBorder(new Color(55, 85, 55), 1), - BorderFactory.createEmptyBorder(9, 11, 9, 11))); - searchField.setMaximumSize(new Dimension(Integer.MAX_VALUE, 40)); + searchField.setFont(FoodSenseTheme.getFont(Font.PLAIN, 12f)); + searchField.putClientProperty("JTextField.placeholderText", "Enter barcode number"); + searchField.setMaximumSize(new Dimension(Integer.MAX_VALUE, 34)); searchField.setAlignmentX(Component.LEFT_ALIGNMENT); - top.add(searchField); - top.add(Box.createVerticalStrut(10)); - - JPanel btnRow = new JPanel(new GridLayout(1, 2, 8, 0)); - btnRow.setOpaque(false); - btnRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, 38)); - btnRow.setAlignmentX(Component.LEFT_ALIGNMENT); - searchBtn = mkBtn("Search", true); - cameraBtn = mkBtn("Scan", false); - btnRow.add(searchBtn); - btnRow.add(cameraBtn); - top.add(btnRow); - - sidebar.add(top, BorderLayout.NORTH); - sidebar.add(buildSidebarProductCard(), BorderLayout.CENTER); - searchField.addActionListener(e -> searchProduct()); + searchField.addKeyListener(new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) { + clearBanner(); + } + }); + top.add(searchField); + top.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_8)); + + // Stacked Buttons + searchBtn = new JButton("Search Barcode"); + searchBtn.setFont(FoodSenseTheme.getFont(Font.BOLD, 12f)); + searchBtn.setFocusPainted(false); + searchBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + searchBtn.setMaximumSize(new Dimension(Integer.MAX_VALUE, 32)); + searchBtn.setAlignmentX(Component.LEFT_ALIGNMENT); searchBtn.addActionListener(e -> searchProduct()); - cameraBtn.addActionListener(e -> startBarcodeScanner()); - - return sidebar; + top.add(searchBtn); + + top.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_4)); + + cameraBtn = new JButton("Scan with Camera"); + cameraBtn.setFont(FoodSenseTheme.getFont(Font.BOLD, 12f)); + cameraBtn.setFocusPainted(false); + cameraBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + cameraBtn.setMaximumSize(new Dimension(Integer.MAX_VALUE, 32)); + cameraBtn.setAlignmentX(Component.LEFT_ALIGNMENT); + cameraBtn.addActionListener(e -> openCameraModal()); + top.add(cameraBtn); + + // Status banner + top.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_8)); + bannerLabel = new JLabel(""); + bannerLabel.setFont(FoodSenseTheme.getFont(Font.PLAIN, 11f)); + bannerLabel.setForeground(FoodSenseTheme.getDanger()); + bannerLabel.setAlignmentX(Component.LEFT_ALIGNMENT); + bannerLabel.setVisible(false); + top.add(bannerLabel); + + bar.add(top, BorderLayout.NORTH); + bar.add(buildSidebarProductCard(), BorderLayout.CENTER); + + return bar; } - /** - * Sidebar widgets for product image, name, brand, and Nutri-Score (hidden until a lookup succeeds). - * - * @return center section of the sidebar - */ private JPanel buildSidebarProductCard() { - JPanel card = new JPanel(); - card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS)); - card.setBackground(SIDEBAR_BG); - card.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); - - card.add(mkSeparator()); - card.add(Box.createVerticalStrut(20)); + productCard = new JPanel(); + productCard.setLayout(new BoxLayout(productCard, BoxLayout.Y_AXIS)); + productCard.setOpaque(false); + productCard.setBorder(BorderFactory.createEmptyBorder(12, 16, 16, 16)); + + JSeparator sep = new JSeparator(); + sep.setMaximumSize(new Dimension(Integer.MAX_VALUE, 1)); + productCard.add(sep); + productCard.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_16)); + + // Styled image frame card + imgCard = new JPanel(new BorderLayout()) { + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setColor(FoodSenseTheme.getCardBackground()); + g2.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 12, 12)); + g2.setColor(FoodSenseTheme.getCardBorder()); + g2.setStroke(new BasicStroke(1f)); + g2.draw(new RoundRectangle2D.Float(0, 0, getWidth() - 1, getHeight() - 1, 12, 12)); + g2.dispose(); + } + }; + imgCard.setOpaque(false); + imgCard.setPreferredSize(new Dimension(150, 150)); + imgCard.setMaximumSize(new Dimension(150, 150)); + imgCard.setAlignmentX(Component.CENTER_ALIGNMENT); imgLabel = new JLabel(); - imgLabel.setAlignmentX(Component.CENTER_ALIGNMENT); imgLabel.setHorizontalAlignment(JLabel.CENTER); - imgLabel.setVisible(false); - card.add(imgLabel); - card.add(Box.createVerticalStrut(14)); - - nameLabel = new JLabel(); - nameLabel.setFont(new Font(F, Font.BOLD, 13)); - nameLabel.setForeground(Color.WHITE); - nameLabel.setAlignmentX(Component.LEFT_ALIGNMENT); - nameLabel.setVisible(false); - card.add(nameLabel); - card.add(Box.createVerticalStrut(4)); - - brandLabel = new JLabel(); - brandLabel.setFont(new Font(F, Font.PLAIN, 12)); - brandLabel.setForeground(new Color(110, 160, 110)); - brandLabel.setAlignmentX(Component.LEFT_ALIGNMENT); - brandLabel.setVisible(false); - card.add(brandLabel); - card.add(Box.createVerticalStrut(10)); - - scorePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 0)); - scorePanel.setOpaque(false); - scorePanel.setAlignmentX(Component.LEFT_ALIGNMENT); - scorePanel.setVisible(false); - card.add(scorePanel); - - return card; - } + imgLabel.setFont(FoodSenseTheme.getFont(Font.PLAIN, 11f)); + imgLabel.setForeground(FoodSenseTheme.getTextMuted()); + imgCard.add(imgLabel, BorderLayout.CENTER); + imgCard.setVisible(false); - /** - * @param text button label - * @param primary if true, filled primary green; otherwise muted accent style - * @return styled {@link JButton} with hover background swap - */ - private JButton mkBtn(String text, boolean primary) { - JButton b = new JButton(text); - b.setFont(new Font(F, Font.BOLD, 13)); - b.setFocusPainted(false); - b.setBorderPainted(false); - b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - Color base = primary ? PRIMARY : SIDEBAR_ACCENT; - Color hover = primary ? PRIMARY_DARK : new Color(42, 72, 45); - b.setBackground(base); - b.setForeground(primary ? Color.WHITE : new Color(170, 210, 170)); - b.addMouseListener(new MouseAdapter() { - public void mouseEntered(MouseEvent e) { b.setBackground(hover); } - public void mouseExited(MouseEvent e) { b.setBackground(base); } - }); - return b; - } + productCard.add(imgCard); + productCard.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_16)); - /** @return thin separator tinted to {@link #SIDEBAR_ACCENT} */ - private JSeparator mkSeparator() { - JSeparator s = new JSeparator(); - s.setForeground(SIDEBAR_ACCENT); - s.setMaximumSize(new Dimension(Integer.MAX_VALUE, 1)); - return s; - } + nutriScoreView = new NutriScoreSpectrumView(); + nutriScoreView.setAlignmentX(Component.CENTER_ALIGNMENT); + nutriScoreView.setVisible(false); + productCard.add(nutriScoreView); - // ── Sidebar product update ──────────────────────────────── + return productCard; + } /** - * Fills sidebar image/name/brand/Nutri-Score from a looked-up product. - * Loads {@link Product#getImage_front_url()} over the network on the calling thread. - * Must run on the EDT. - * - * @param p product to display; image URL may be missing + * Reapplies theme colors to sidebar components in-place without restarting image fetch. */ - private void updateSidebar(Product p) { - try { - if (p.getImage_front_url() != null && !p.getImage_front_url().isEmpty()) { - ImageIcon raw = new ImageIcon(new URI(p.getImage_front_url()).toURL()); - Image scaled = raw.getImage().getScaledInstance(170, 190, Image.SCALE_SMOOTH); - imgLabel.setIcon(new ImageIcon(scaled)); - imgLabel.setText(null); - } else { - imgLabel.setIcon(null); - imgLabel.setText("No image"); - imgLabel.setForeground(MUTED); - } - } catch (Exception ex) { - imgLabel.setIcon(null); - imgLabel.setText("No image"); - imgLabel.setForeground(MUTED); - } + private void applySidebarTheme() { + sidebar.setBackground(FoodSenseTheme.getSidebarBackground()); + sidebar.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, FoodSenseTheme.getCardBorder())); + logo.setForeground(FoodSenseTheme.getPrimaryAccent()); + tagline.setForeground(FoodSenseTheme.getSidebarMuted()); + barcodeLabel.setForeground(FoodSenseTheme.getSidebarMuted()); + bannerLabel.setForeground(FoodSenseTheme.getDanger()); + imgLabel.setForeground(FoodSenseTheme.getTextMuted()); + nutriScoreView.repaint(); + sidebar.revalidate(); + sidebar.repaint(); + } - String name = p.getProduct_name() != null ? p.getProduct_name() : "Unknown product"; - nameLabel.setText("
" + name + "
"); - brandLabel.setText(p.getBrands() != null ? p.getBrands() : ""); - - scorePanel.removeAll(); - if (p.getNutriscore_grade() != null && !p.getNutriscore_grade().isBlank()) { - JLabel lbl = new JLabel("Nutri-Score"); - lbl.setFont(new Font(F, Font.PLAIN, 11)); - lbl.setForeground(new Color(110, 160, 110)); - scorePanel.add(lbl); - scorePanel.add(mkNutriscoreBadge(p.getNutriscore_grade(), 12)); + private void updateComponentColors() { + root.setBackground(FoodSenseTheme.getBackground()); + applySidebarTheme(); + if (currentProduct != null) { + swapContent(buildProductView(currentProduct)); + } else { + swapContent(buildEmptyState()); } - - imgLabel.setVisible(true); - nameLabel.setVisible(true); - brandLabel.setVisible(true); - scorePanel.setVisible(true); - scorePanel.revalidate(); - scorePanel.repaint(); + frame.revalidate(); + frame.repaint(); } - // ── Empty state ─────────────────────────────────────────── + // ── Content Panes ───────────────────────────────────────── - /** - * Placeholder shown before any successful product lookup. - * - * @return center content panel - */ private JPanel buildEmptyState() { JPanel p = new JPanel(new GridBagLayout()); - p.setBackground(BG); + p.setBackground(FoodSenseTheme.getBackground()); JPanel inner = new JPanel(); inner.setLayout(new BoxLayout(inner, BoxLayout.Y_AXIS)); inner.setOpaque(false); - JLabel icon = new JLabel("🔍"); - icon.setFont(new Font(F, Font.PLAIN, 52)); + JLabel icon = new JLabel("⌕"); + icon.setFont(FoodSenseTheme.getFont(Font.PLAIN, 48f)); + icon.setForeground(FoodSenseTheme.getTextMuted()); icon.setAlignmentX(Component.CENTER_ALIGNMENT); - JLabel title = new JLabel("No product loaded"); - title.setFont(new Font(F, Font.BOLD, 20)); - title.setForeground(TEXT); + JLabel title = new JLabel("Ready to Scan"); + title.setFont(FoodSenseTheme.getFont(Font.BOLD, 18f)); + title.setForeground(FoodSenseTheme.getTextPrimary()); title.setAlignmentX(Component.CENTER_ALIGNMENT); - JLabel hint = new JLabel("
Enter a barcode on the left or use your camera to scan.
"); - hint.setFont(new Font(F, Font.PLAIN, 14)); - hint.setForeground(MUTED); + JLabel hint = new JLabel("Enter a barcode on the left or scan live with your camera."); + hint.setFont(FoodSenseTheme.getFont(Font.PLAIN, 12f)); + hint.setForeground(FoodSenseTheme.getTextMuted()); hint.setAlignmentX(Component.CENTER_ALIGNMENT); inner.add(icon); - inner.add(Box.createVerticalStrut(14)); + inner.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_8)); inner.add(title); - inner.add(Box.createVerticalStrut(8)); + inner.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_4)); inner.add(hint); p.add(inner); return p; } - // ── Product view ────────────────────────────────────────── - /** - * Scrollable nutrition / ingredients / allergens view for a product. - * - * @param p product with optional nutriments and allergen text - * @return content panel to swap into the center region + * Builds a balanced, two-column responsive dashboard that fills the window + * and eliminates blank spaces and horizontal scrollbars. */ private JPanel buildProductView(Product p) { - JPanel sections = new JPanel(); - sections.setLayout(new BoxLayout(sections, BoxLayout.Y_AXIS)); - sections.setBackground(BG); - sections.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30)); + JPanel main = new JPanel(new BorderLayout()); + main.setBackground(FoodSenseTheme.getBackground()); + main.setBorder(BorderFactory.createEmptyBorder(24, 28, 24, 28)); + + // Top Header Banner inside Main Content + JPanel headerCard = new JPanel(new BorderLayout()) { + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setColor(FoodSenseTheme.getCardBackground()); + g2.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 12, 12)); + g2.setColor(FoodSenseTheme.getCardBorder()); + g2.setStroke(new BasicStroke(1f)); + g2.draw(new RoundRectangle2D.Float(0, 0, getWidth() - 1, getHeight() - 1, 12, 12)); + g2.dispose(); + } + }; + headerCard.setOpaque(false); + headerCard.setBorder(BorderFactory.createEmptyBorder(16, 20, 16, 20)); + + JPanel headerLeft = new JPanel(); + headerLeft.setLayout(new BoxLayout(headerLeft, BoxLayout.Y_AXIS)); + headerLeft.setOpaque(false); + + String titleText = p.getProduct_name() != null ? p.getProduct_name() : "Unknown Product"; + JLabel prodTitle = new JLabel(titleText); + prodTitle.putClientProperty("html.disable", Boolean.TRUE); + prodTitle.setFont(FoodSenseTheme.getFont(Font.BOLD, 22f)); + prodTitle.setForeground(FoodSenseTheme.getTextPrimary()); + headerLeft.add(prodTitle); + headerLeft.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_4)); + + String brandText = p.getBrands() != null && !p.getBrands().isBlank() ? p.getBrands() : "Generic / Unbranded"; + JLabel prodBrand = new JLabel("Brand: " + + SecurityValidator.escapeHtml(brandText) + ""); + prodBrand.setFont(FoodSenseTheme.getFont(Font.PLAIN, 12.5f)); + prodBrand.setForeground(FoodSenseTheme.getTextSecondary()); + headerLeft.add(prodBrand); + + headerCard.add(headerLeft, BorderLayout.WEST); + + // Header right Nutri-Score badge + if (p.getNutriscore_grade() != null && p.getNutriscore_grade().trim().matches("(?i)[a-e]")) { + String g = p.getNutriscore_grade().trim().toUpperCase(); + JLabel gradeBadge = new JLabel(" Nutri-Score Grade " + g + " "); + gradeBadge.setFont(FoodSenseTheme.getFont(Font.BOLD, 12f)); + gradeBadge.setForeground(Color.WHITE); + gradeBadge.setBackground(FoodSenseTheme.getNutriscoreColor(g)); + gradeBadge.setOpaque(true); + gradeBadge.setBorder(BorderFactory.createEmptyBorder(6, 12, 6, 12)); + + JPanel badgeWrapper = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 4)); + badgeWrapper.setOpaque(false); + badgeWrapper.add(gradeBadge); + headerCard.add(badgeWrapper, BorderLayout.EAST); + } + + main.add(headerCard, BorderLayout.NORTH); + + // 2-Column Dashboard Center + JPanel columns = new JPanel(new GridLayout(1, 2, 20, 0)); + columns.setOpaque(false); + columns.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 0)); - sections.add(buildNutritionSection(p.getNutriments())); - sections.add(Box.createVerticalStrut(24)); - sections.add(buildIngredientsSection(p)); + // Column 1: Nutrition Profile + columns.add(new NutritionLabelPanel(p.getNutriments())); + + // Column 2: Ingredients & Allergens + JPanel col2 = new JPanel(); + col2.setLayout(new BoxLayout(col2, BoxLayout.Y_AXIS)); + col2.setOpaque(false); + + col2.add(new IngredientsPanel(p.getIngredients_text(), p.getAllergens_from_ingredients())); if (p.getAllergens_from_ingredients() != null && !p.getAllergens_from_ingredients().isBlank()) { - sections.add(Box.createVerticalStrut(24)); - sections.add(buildAllergensSection(p)); + col2.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_16)); + col2.add(new AllergenBanner(p.getAllergens_from_ingredients())); } - // Wrap in BorderLayout.NORTH so BoxLayout uses preferred height, not stretched height - JPanel wrapper = new JPanel(new BorderLayout()); - wrapper.setBackground(BG); - wrapper.add(sections, BorderLayout.NORTH); + columns.add(col2); + main.add(columns, BorderLayout.CENTER); - JScrollPane scroll = new JScrollPane(wrapper); + // ScrollPane with horizontal scrollbar disabled + JScrollPane scroll = new JScrollPane(main); scroll.setBorder(null); + scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scroll.getVerticalScrollBar().setUnitIncrement(16); - scroll.getViewport().setBackground(BG); + scroll.getViewport().setBackground(FoodSenseTheme.getBackground()); JPanel container = new JPanel(new BorderLayout()); - container.setBackground(BG); + container.setBackground(FoodSenseTheme.getBackground()); container.add(scroll, BorderLayout.CENTER); return container; } - // ── Sections ────────────────────────────────────────────── - - /** - * @param n nutriments DTO (may contain null fields) - * @return "Nutrition Facts" section panel - */ - private JPanel buildNutritionSection(Nutriments n) { - JPanel section = new JPanel(); - section.setLayout(new BoxLayout(section, BoxLayout.Y_AXIS)); - section.setOpaque(false); - section.setAlignmentX(Component.LEFT_ALIGNMENT); - - section.add(mkSectionTitle("Nutrition Facts", "per 100g")); - section.add(Box.createVerticalStrut(12)); - section.add(buildNutritionLabel(n)); - return section; - } - - /** - * Builds the bordered per-100g nutrition grid rows. - * - * @param n nutriments source; null field values render as an em dash - * @return card panel of nutrient rows - */ - private JPanel buildNutritionLabel(Nutriments n) { - JPanel card = new JPanel(); - card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS)); - card.setBackground(CARD); - card.setBorder(BorderFactory.createLineBorder(BORDER, 1)); - card.setAlignmentX(Component.LEFT_ALIGNMENT); - card.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE)); - - Object[][] rows = { - { "Energy", n.getEnergy(), "kcal", false }, - { "Carbohydrates", n.getCarbohydrates(), "g", false }, - { "of which Sugars", n.getSugars(), "g", true }, - { "Fat", n.getFat(), "g", false }, - { "of which Saturates", n.getSaturated_fat(), "g", true }, - { "Proteins", n.getProteins(), "g", false }, - { "Salt", n.getSalt(), "g", false }, - { "Sodium", n.getSodium(), "mg", false }, - }; + // ── Search & Logic ──────────────────────────────────────── - boolean first = true; - for (Object[] r : rows) { - if (!first) { - JSeparator sep = new JSeparator(); - sep.setForeground(BORDER); - sep.setMaximumSize(new Dimension(Integer.MAX_VALUE, 1)); - card.add(sep); - } - card.add(mkNutritionRow((String) r[0], (String) r[1], (String) r[2], (boolean) r[3])); - first = false; + private void searchProduct() { + if (!searchBtn.isEnabled()) { + return; } - return card; - } - - /** - * @param name left-side nutrient label - * @param value amount string, or blank/{@code null} for "—" - * @param unit unit suffix (e.g. {@code g}, {@code kcal}) - * @param sub if true, indented muted "of which …" style row - * @return single nutrition row panel - */ - private JPanel mkNutritionRow(String name, String value, String unit, boolean sub) { - JPanel row = new JPanel(new BorderLayout()); - row.setBackground(sub ? new Color(250, 252, 250) : CARD); - row.setBorder(BorderFactory.createEmptyBorder(11, sub ? 28 : 16, 11, 16)); - - JLabel left = new JLabel(name); - left.setFont(new Font(F, sub ? Font.PLAIN : Font.BOLD, sub ? 13 : 14)); - left.setForeground(sub ? MUTED : TEXT); - - String v = (value != null && !value.isBlank()) ? value : "—"; - JLabel right = new JLabel(v + " " + unit); - right.setFont(new Font(F, Font.BOLD, 14)); - right.setForeground(sub ? MUTED : PRIMARY_DARK); - - row.add(left, BorderLayout.WEST); - row.add(right, BorderLayout.EAST); - return row; - } - - /** - * @param p product whose {@code ingredients_text} is shown (fallback copy if blank) - * @return ingredients section panel - */ - private JPanel buildIngredientsSection(Product p) { - JPanel section = new JPanel(); - section.setLayout(new BoxLayout(section, BoxLayout.Y_AXIS)); - section.setOpaque(false); - section.setAlignmentX(Component.LEFT_ALIGNMENT); - - section.add(mkSectionTitle("Ingredients", null)); - section.add(Box.createVerticalStrut(12)); - - String text = (p.getIngredients_text() != null && !p.getIngredients_text().isBlank()) - ? p.getIngredients_text() - : "No ingredients information available."; - - JTextArea area = new JTextArea(text); - area.setFont(new Font(F, Font.PLAIN, 13)); - area.setForeground(TEXT); - area.setBackground(CARD); - area.setLineWrap(true); - area.setWrapStyleWord(true); - area.setEditable(false); - area.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createLineBorder(BORDER, 1), - BorderFactory.createEmptyBorder(16, 16, 16, 16))); - area.setAlignmentX(Component.LEFT_ALIGNMENT); - section.add(area); - return section; - } - - /** - * Danger-styled allergens panel. Caller should only invoke when allergen text is present. - * - * @param p product with non-blank {@link Product#getAllergens_from_ingredients()} - * @return allergens section panel - */ - private JPanel buildAllergensSection(Product p) { - JPanel section = new JPanel(); - section.setLayout(new BoxLayout(section, BoxLayout.Y_AXIS)); - section.setOpaque(false); - section.setAlignmentX(Component.LEFT_ALIGNMENT); - - JLabel header = new JLabel("⚠ Allergens"); - header.setFont(new Font(F, Font.BOLD, 18)); - header.setForeground(DANGER); - header.setBorder(BorderFactory.createEmptyBorder(0, 0, 12, 0)); - header.setAlignmentX(Component.LEFT_ALIGNMENT); - section.add(header); - - JTextArea area = new JTextArea(p.getAllergens_from_ingredients()); - area.setFont(new Font(F, Font.PLAIN, 13)); - area.setForeground(DANGER); - area.setBackground(DANGER_BG); - area.setLineWrap(true); - area.setWrapStyleWord(true); - area.setEditable(false); - area.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createLineBorder(new Color(252, 165, 165), 1), - BorderFactory.createEmptyBorder(16, 16, 16, 16))); - area.setAlignmentX(Component.LEFT_ALIGNMENT); - section.add(area); - return section; - } - - // ── Shared helpers ──────────────────────────────────────── + clearBanner(); + String rawBarcode = searchField.getText(); - /** - * @param title section heading - * @param subtitle optional muted line under the title; {@code null} to omit - * @return title block panel - */ - private JPanel mkSectionTitle(String title, String subtitle) { - JPanel p = new JPanel(); - p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); - p.setOpaque(false); - p.setAlignmentX(Component.LEFT_ALIGNMENT); - p.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); - - JLabel t = new JLabel(title); - t.setFont(new Font(F, Font.BOLD, 18)); - t.setForeground(TEXT); - t.setAlignmentX(Component.LEFT_ALIGNMENT); - p.add(t); - - if (subtitle != null) { - JLabel s = new JLabel(subtitle); - s.setFont(new Font(F, Font.PLAIN, 12)); - s.setForeground(MUTED); - s.setAlignmentX(Component.LEFT_ALIGNMENT); - p.add(s); + if (rawBarcode == null || rawBarcode.trim().isEmpty()) { + showBanner("Please enter a barcode number."); + return; } - return p; - } - - /** - * @param grade Nutri-Score letter (case-insensitive) - * @param fontSize badge font size in points - * @return opaque colored badge label - */ - private JLabel mkNutriscoreBadge(String grade, int fontSize) { - JLabel badge = new JLabel(grade.toUpperCase()); - badge.setFont(new Font(F, Font.BOLD, fontSize)); - badge.setForeground(Color.WHITE); - badge.setBackground(getNutriscoreColor(grade)); - badge.setOpaque(true); - badge.setBorder(BorderFactory.createEmptyBorder(4, 10, 4, 10)); - return badge; - } - - /** - * Maps Nutri-Score A–E to badge background colors; unknown grades use {@link #MUTED}. - * - * @param grade Nutri-Score letter - * @return background color for the badge - */ - private Color getNutriscoreColor(String grade) { - return switch (grade.toUpperCase()) { - case "A" -> new Color(0, 150, 57); - case "B" -> new Color(133, 192, 66); - case "C" -> new Color(255, 210, 0); - case "D" -> new Color(255, 130, 0); - case "E" -> new Color(220, 38, 38); - default -> MUTED; - }; - } - - // ── Logic ───────────────────────────────────────────────── - /** - * Opens the webcam scan pipeline; on detect, fills the search field and runs {@link #searchProduct()} - * on the EDT. - */ - private void startBarcodeScanner() { - VideoProcessor vp = new VideoProcessor(barcode -> SwingUtilities.invokeLater(() -> { - searchField.setText(barcode); - searchProduct(); - })); - vp.start(); - } - - /** - * Reads the barcode field, disables controls, fetches on a background thread, then updates the UI - * on the EDT. Shows a warning dialog for empty input or a failed/not-found lookup. - */ - private void searchProduct() { - String barcode = searchField.getText().trim(); - if (barcode.isEmpty()) { - JOptionPane.showMessageDialog(frame, "Please enter a barcode.", "Empty Input", JOptionPane.WARNING_MESSAGE); + String barcode = rawBarcode.trim(); + if (!SecurityValidator.isValidBarcode(barcode)) { + showBanner("Invalid barcode (3-48 alphanumeric characters, hyphens, or underscores)."); return; } searchBtn.setEnabled(false); cameraBtn.setEnabled(false); - searchBtn.setText("..."); + searchBtn.setText("Searching..."); new Thread(() -> { Product product = apiClient.fetchProduct(barcode); SwingUtilities.invokeLater(() -> { - if (product != null) { - updateSidebar(product); - swapContent(buildProductView(product)); + try { + if (product != null) { + this.currentProduct = product; + updateSidebar(product); + swapContent(buildProductView(product)); + } else { + showBanner("Product not found. Verify code."); + } + } finally { + searchBtn.setEnabled(true); + cameraBtn.setEnabled(true); + searchBtn.setText("Search Barcode"); + } + }); + }, "foodsense-api-search").start(); + } + + private void openCameraModal() { + clearBanner(); + CameraScanDialog dialog = new CameraScanDialog(frame, scannedCode -> { + searchField.setText(scannedCode); + searchProduct(); + }); + dialog.open(); + } + + private void updateSidebar(Product p) { + final int currentReq = ++imageRequestId; + + imgCard.setVisible(true); + imgLabel.setIcon(null); + imgLabel.setText("Loading..."); + + String imgUrl = p.getImage_front_url(); + if (imgUrl != null && !imgUrl.isBlank()) { + SafeImageLoader.loadImageAsync(imgUrl, 140, 140, icon -> { + if (currentReq != imageRequestId) { + return; + } + if (icon != null) { + imgLabel.setIcon(icon); + imgLabel.setText(null); } else { - JOptionPane.showMessageDialog(frame, - "Product not found. Check the barcode and try again.", - "Not Found", JOptionPane.WARNING_MESSAGE); + imgLabel.setIcon(null); + imgLabel.setText("No photo"); } - searchBtn.setEnabled(true); - cameraBtn.setEnabled(true); - searchBtn.setText("Search"); }); - }).start(); + } else { + imgLabel.setIcon(null); + imgLabel.setText("No photo"); + } + + nutriScoreView.setGrade(p.getNutriscore_grade()); + nutriScoreView.setVisible(true); + productCard.revalidate(); + productCard.repaint(); } - /** - * Replaces the center content panel. Must run on the EDT. - * - * @param next panel to show (empty state or product view) - */ private void swapContent(JPanel next) { root.remove(contentArea); contentArea = next; @@ -644,4 +523,19 @@ private void swapContent(JPanel next) { root.revalidate(); root.repaint(); } + + private void showBanner(String message) { + bannerLabel.setText("
" + + SecurityValidator.escapeHtml(message) + "
"); + bannerLabel.setVisible(true); + } + + private void clearBanner() { + bannerLabel.setText(""); + bannerLabel.setVisible(false); + } + + private static String toHex(Color c) { + return String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue()); + } } diff --git a/src/main/java/com/foodsense/Nutriments.java b/src/main/java/com/foodsense/Nutriments.java index ad13775..131dbdb 100644 --- a/src/main/java/com/foodsense/Nutriments.java +++ b/src/main/java/com/foodsense/Nutriments.java @@ -15,6 +15,12 @@ public class Nutriments { @SerializedName("energy") private String calories; + @SerializedName("energy-kcal") + private String energyKcal; + + @SerializedName("energy-kj") + private String energyKj; + private String sugars; private String fat; @@ -64,6 +70,38 @@ public void setEnergy(String energy) { this.calories = energy; } + /** + * Explicit energy in kcal (JSON key {@code energy-kcal}). + * + * @return energy in kcal string, or {@code null} + */ + public String getEnergyKcal() { + return energyKcal; + } + + /** + * @param energyKcal explicit energy in kcal from the API + */ + public void setEnergyKcal(String energyKcal) { + this.energyKcal = energyKcal; + } + + /** + * Explicit energy in kJ (JSON key {@code energy-kj}). + * + * @return energy in kJ string, or {@code null} + */ + public String getEnergyKj() { + return energyKj; + } + + /** + * @param energyKj explicit energy in kJ from the API + */ + public void setEnergyKj(String energyKj) { + this.energyKj = energyKj; + } + /** @return fat amount string, or {@code null} */ public String getFat() { return fat; diff --git a/src/main/java/com/foodsense/ProductApiClient.java b/src/main/java/com/foodsense/ProductApiClient.java index 75009dc..3942e76 100644 --- a/src/main/java/com/foodsense/ProductApiClient.java +++ b/src/main/java/com/foodsense/ProductApiClient.java @@ -6,8 +6,11 @@ package com.foodsense; +import com.foodsense.security.SecurityValidator; import com.google.gson.Gson; import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; @@ -111,23 +114,26 @@ public String getHost() { /** * Constructs the full request URI for a given barcode. + * Encodes the barcode path segment to avoid injection or illegal character exceptions. * * @param barcode barcode string * @return request URI */ public URI buildUri(String barcode) { - return URI.create("https://" + host + "/api/v2/product/" + barcode); + String encoded = barcode != null ? URLEncoder.encode(barcode.trim(), StandardCharsets.UTF_8) : ""; + return URI.create("https://" + host + "/api/v2/product/" + encoded); } /** * GETs product details from Open Food Facts API and deserializes with Gson. * Network I/O — call off the EDT. + * Validates barcode format with {@link SecurityValidator#isValidBarcode(String)} before sending. * * @param barcode product barcode * @return {@link Product} when found (status != 0); {@code null} on failure or status == 0 */ public Product fetchProduct(String barcode) { - if (barcode == null || barcode.isBlank()) { + if (!SecurityValidator.isValidBarcode(barcode)) { return null; } try { diff --git a/src/main/java/com/foodsense/VideoProcessor.java b/src/main/java/com/foodsense/VideoProcessor.java index 73763b9..5c6f684 100644 --- a/src/main/java/com/foodsense/VideoProcessor.java +++ b/src/main/java/com/foodsense/VideoProcessor.java @@ -1,7 +1,7 @@ /* * Live webcam barcode scan pipeline: OpenCV grabber producer + ZXing decode consumer. * Uses a bounded {@link java.util.concurrent.BlockingQueue} of frames and notifies a - * {@link BarcodeListener} when a code is found. Side effect: opens a JavaCV {@code CanvasFrame}. + * {@link BarcodeListener} when a code is found. Supports in-app frame rendering or fallback CanvasFrame. */ package com.foodsense; @@ -22,10 +22,10 @@ /** * Producer/consumer webcam scanner. Call {@link #start()} once; {@link #stop()} ends both threads. - * Assumes a display and camera device {@code 0}; not safe to start twice without stopping first - * (second {@link #start()} is a no-op while {@code running}). + * Assumes a display and camera device {@code 0}; safe to call {@link #stop()} multiple times. */ public class VideoProcessor { + /** * Callback invoked on the consumer thread when a barcode is decoded. * Callers that touch Swing must marshal to the EDT themselves. @@ -35,67 +35,105 @@ public interface BarcodeListener { * Called on the consumer thread after a successful ZXing decode. * * @param barcodeText decoded barcode payload (digits / text as returned by ZXing) - * @example - *
{@code
-         * barcode -> SwingUtilities.invokeLater(() -> searchField.setText(barcode))
-         * }
*/ void onBarcodeDetected(String barcodeText); } + /** + * Callback invoked on the consumer thread with each live preview image. + */ + @FunctionalInterface + public interface FrameListener { + /** + * Called when a new processed frame is available for rendering. + * + * @param image decoded video frame as a BufferedImage + */ + void onFrame(BufferedImage image); + } + + /** + * Callback invoked when a camera hardware or permission error occurs. + */ + @FunctionalInterface + public interface ErrorListener { + /** + * Called when camera acquisition or streaming encounters a fatal error. + * + * @param message diagnostic error message + */ + void onError(String message); + } + private final BlockingQueue frameQueue = new LinkedBlockingQueue<>(2); private final BarcodeListener listener; + private final FrameListener frameListener; + private final ErrorListener errorListener; private volatile boolean running = false; + private volatile CanvasFrame canvas = null; /** * Creates a scanner that will notify {@code listener} when a code is found. + * Uses fallback {@link CanvasFrame} for video preview. * * @param listener notified when a barcode is detected; may be {@code null} to skip callbacks - * @example - *
{@code
-     * VideoProcessor vp = new VideoProcessor(code -> System.out.println(code));
-     * vp.start();
-     * }
*/ public VideoProcessor(BarcodeListener listener) { + this(listener, null, null); + } + + /** + * Creates a scanner with in-app frame streaming and error notification callbacks. + * + * @param listener notified when a barcode is detected + * @param frameListener stream listener for in-app frame painting (if null, CanvasFrame is used) + * @param errorListener notified if camera cannot be accessed or throws an exception + */ + public VideoProcessor(BarcodeListener listener, FrameListener frameListener, ErrorListener errorListener) { this.listener = listener; + this.frameListener = frameListener; + this.errorListener = errorListener; } /** * Starts producer (webcam grab) and consumer (decode + preview) threads if not already running. - * Opens a {@code CanvasFrame} titled "Live Barcode Scanner". - * - * @example - *
{@code
-     * new VideoProcessor(System.out::println).start();
-     * }
*/ - public void start() { - if (running) + public synchronized void start() { + if (running) { return; + } running = true; - Thread producer = new Thread(new ProducerTask()); - Thread consumer = new Thread(new ConsumerTask(listener)); + Thread producer = new Thread(new ProducerTask(), "foodsense-camera-producer"); + Thread consumer = new Thread(new ConsumerTask(listener), "foodsense-camera-consumer"); + producer.setDaemon(true); + consumer.setDaemon(true); producer.start(); consumer.start(); } /** - * Signals both threads to exit and clears the frame queue. - * Safe to call from the CanvasFrame close listener or after a successful decode. - * - * @example - *
{@code
-     * VideoProcessor vp = new VideoProcessor(null);
-     * vp.start();
-     * // later, or from windowClosing:
-     * vp.stop();
-     * }
+ * Signals both threads to exit, disposes canvas if active, and clears the frame queue. */ - public void stop() { + public synchronized void stop() { running = false; frameQueue.clear(); + if (canvas != null) { + try { + canvas.dispose(); + } catch (Exception ignored) { + } + canvas = null; + } + } + + /** + * Returns whether the scanner is actively running. + * + * @return {@code true} if running; {@code false} otherwise + */ + public boolean isRunning() { + return running; } /** @@ -105,55 +143,56 @@ public void stop() { private class ProducerTask implements Runnable { @Override public void run() { - try (OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0)) { + OpenCVFrameGrabber grabber = null; + try { + grabber = new OpenCVFrameGrabber(0); grabber.start(); while (running) { Frame frame = grabber.grab(); if (frame == null) { running = false; + if (errorListener != null) { + errorListener.onError("Camera stream ended unexpectedly"); + } break; } - // Clone the frame — grab() reuses the same internal buffer Frame cloned = frame.clone(); if (!frameQueue.offer(cloned)) { frameQueue.poll(); frameQueue.offer(cloned); } } - - grabber.stop(); } catch (Exception e) { - e.printStackTrace(); + running = false; + if (errorListener != null) { + errorListener.onError("Camera error: " + (e.getMessage() != null ? e.getMessage() : "Unable to access camera device")); + } + } finally { + if (grabber != null) { + try { + grabber.stop(); + grabber.release(); + } catch (Exception ignored) { + } + } } } } /** - * Polls frames, runs ZXing decode, draws an optional green box, and shows the live preview. + * Polls frames, runs ZXing decode, draws an optional green box, and streams preview. */ private class ConsumerTask implements Runnable { private final BarcodeListener listener; - /** - * @param listener same listener passed to the outer {@link VideoProcessor} - */ public ConsumerTask(BarcodeListener listener) { this.listener = listener; } - /** - * Draws a padded green rectangle when ZXing returns exactly two result points - * (typical for 1D barcodes). Leaves the frame unchanged otherwise. - * - * @param result ZXing decode result with geometry points - * @param frame current preview frame to annotate - * @return frame with box drawn, or the original frame when points are unsuitable - */ private Frame drawBoxOverBarcode(Result result, Frame frame) { ResultPoint[] points = result.getResultPoints(); - if (points != null && points.length == 2) { OpenCVFrameConverter.ToMat matConverter = new OpenCVFrameConverter.ToMat(); Mat mat = matConverter.convert(frame); @@ -161,23 +200,14 @@ private Frame drawBoxOverBarcode(Result result, Frame frame) { Point p1 = new Point((int) points[0].getX(), (int) points[0].getY()); Point p2 = new Point((int) points[1].getX(), (int) points[1].getY()); - // Compute expanded bounding box (padding to make it larger & visible) int paddingX = 150; int paddingY = 120; - // Compute the corners of the box - int minX = Math.min(p1.x(), p2.x()) - paddingX; - int minY = Math.min(p1.y(), p2.y()) - paddingY; - int maxX = Math.max(p1.x(), p2.x()) + paddingX; - int maxY = Math.max(p1.y(), p2.y()) + paddingY; + int minX = Math.max(0, Math.min(p1.x(), p2.x()) - paddingX); + int minY = Math.max(0, Math.min(p1.y(), p2.y()) - paddingY); + int maxX = Math.min(mat.cols() - 1, Math.max(p1.x(), p2.x()) + paddingX); + int maxY = Math.min(mat.rows() - 1, Math.max(p1.y(), p2.y()) + paddingY); - // Make sure the box is within bounds (not outside the video frame) - minX = Math.max(0, minX); - minY = Math.max(0, minY); - maxX = Math.min(mat.cols() - 1, maxX); - maxY = Math.min(mat.rows() - 1, maxY); - - // Draw a bold box around the barcode rectangle( mat, new Point(minX, minY), @@ -194,68 +224,86 @@ private Frame drawBoxOverBarcode(Result result, Frame frame) { @Override public void run() { - CanvasFrame canvas = new CanvasFrame("Live Barcode Scanner"); - canvas.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); - canvas.setCanvasSize(640, 480); - - // Stop the producer when the user closes the window - canvas.addWindowListener(new java.awt.event.WindowAdapter() { - @Override - public void windowClosing(java.awt.event.WindowEvent e) { - stop(); - } - }); + if (frameListener == null) { + canvas = new CanvasFrame("Live Barcode Scanner"); + canvas.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + canvas.setCanvasSize(640, 480); + canvas.addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + stop(); + } + }); + } Java2DFrameConverter frameToImage = new Java2DFrameConverter(); MultiFormatReader barcodeReader = new MultiFormatReader(); - while (running && canvas.isVisible()) { + while (running) { + CanvasFrame localCanvas = canvas; + if (frameListener == null && (localCanvas == null || !localCanvas.isVisible())) { + break; + } try { Frame frame = frameQueue.poll(100, java.util.concurrent.TimeUnit.MILLISECONDS); - if (frame == null) + if (frame == null) { continue; + } - // Convert Frame → BufferedImage for ZXing BufferedImage image = frameToImage.convert(frame); - if (image == null) + if (image == null) { continue; + } + LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); try { Result result = barcodeReader.decode(bitmap); - - // Draw box on frame frame = drawBoxOverBarcode(result, frame); + image = frameToImage.convert(frame); - System.out.println("Detected: " + result.getText() + " (" + result.getBarcodeFormat() + ")"); - - if (listener != null) + if (listener != null) { listener.onBarcodeDetected(result.getText()); + } + + if (frameListener != null) { + frameListener.onFrame(image); + } else if (localCanvas != null) { + localCanvas.showImage(frame); + } - // Pause for a short moment - canvas.showImage(frame); try { - Thread.sleep(1000); // 1 second pause + Thread.sleep(600); } catch (InterruptedException ignored) { } stop(); - canvas.dispose(); break; + } catch (NotFoundException ignored) { + // Frame did not contain a valid barcode + } - } catch (NotFoundException e) { - // No barcode in this frame + if (frameListener != null) { + frameListener.onFrame(image); + } else if (localCanvas != null) { + localCanvas.showImage(frame); } - canvas.showImage(frame); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } catch (Exception e) { - e.printStackTrace(); + System.err.println("Notice: camera frame processing exception: " + e.getMessage()); + } + } + + if (canvas != null) { + try { + canvas.dispose(); + } catch (Exception ignored) { } + canvas = null; } - canvas.dispose(); } } } diff --git a/src/main/java/com/foodsense/security/SafeImageLoader.java b/src/main/java/com/foodsense/security/SafeImageLoader.java new file mode 100644 index 0000000..972083f --- /dev/null +++ b/src/main/java/com/foodsense/security/SafeImageLoader.java @@ -0,0 +1,153 @@ +/* + * Asynchronous, bounded image loader for FoodSense. + * Protects against EDT blocking, SSRF, non-HTTPS URLs, memory exhaustion (payload & pixel caps), + * and hung response body streams. + */ + +package com.foodsense.security; + +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.stream.ImageInputStream; +import javax.swing.*; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.Iterator; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +/** + * Handles safe asynchronous image loading from verified HTTPS Open Food Facts URLs. + * Limits image size to 5MB, caps pixel dimensions to 16 megapixels, enforces a watchdog + * deadline on body reading, and dispatches the scaled {@link ImageIcon} back to the Swing EDT. + */ +public final class SafeImageLoader { + + private static final int MAX_IMAGE_BYTES = 5 * 1024 * 1024; // 5 MB maximum + private static final long MAX_IMAGE_PIXELS = 16_000_000L; // 16 Megapixels + private static final Duration TIMEOUT = Duration.ofSeconds(5); + private static final long BODY_DEADLINE_SECONDS = 10; + + private static final HttpClient HTTP_CLIENT = HttpClient.newBuilder() + .connectTimeout(TIMEOUT) + .followRedirects(HttpClient.Redirect.NEVER) + .build(); + + private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(2, r -> { + Thread t = new Thread(r, "foodsense-image-loader"); + t.setDaemon(true); + return t; + }); + + private static final ScheduledExecutorService WATCHDOG = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "foodsense-image-watchdog"); + t.setDaemon(true); + return t; + }); + + private SafeImageLoader() { + // Prevent instantiation + } + + /** + * Asynchronously downloads an image from a verified HTTPS URL, scales it smoothly preserving aspect ratio, + * and delivers the resulting {@link ImageIcon} to {@code callback} on the EDT. + * Passes {@code null} to the callback if the URL is invalid, download fails, or data is corrupt. + * + * @param urlString target image URL (must be HTTPS) + * @param targetWidth desired scaled width in pixels + * @param targetHeight desired scaled height in pixels + * @param callback consumer invoked on the Swing EDT with the loaded icon, or {@code null} on failure + */ + public static void loadImageAsync(String urlString, int targetWidth, int targetHeight, Consumer callback) { + if (!SecurityValidator.isSafeHttpsUrl(urlString)) { + SwingUtilities.invokeLater(() -> callback.accept(null)); + return; + } + + EXECUTOR.submit(() -> { + ImageIcon icon = null; + try { + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(urlString.trim())) + .timeout(TIMEOUT) + .GET() + .build(); + + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofInputStream()); + if (response.statusCode() == 200) { + try (InputStream in = response.body()) { + ScheduledFuture guard = WATCHDOG.schedule(() -> { + try { + in.close(); + } catch (IOException ignored) { + } + }, BODY_DEADLINE_SECONDS, TimeUnit.SECONDS); + + byte[] bytes; + try { + bytes = in.readNBytes(MAX_IMAGE_BYTES + 1); + } finally { + guard.cancel(false); + } + + if (bytes.length <= MAX_IMAGE_BYTES) { + BufferedImage img = readBounded(bytes); + if (img != null && img.getWidth() > 0 && img.getHeight() > 0) { + double scale = Math.min((double) targetWidth / img.getWidth(), + (double) targetHeight / img.getHeight()); + int w = Math.max(1, (int) Math.round(img.getWidth() * scale)); + int h = Math.max(1, (int) Math.round(img.getHeight() * scale)); + Image scaled = img.getScaledInstance(w, h, Image.SCALE_SMOOTH); + icon = new ImageIcon(scaled); + } + } + } + } else if (response.body() != null) { + response.body().close(); + } + } catch (Exception ignored) { + // Return null icon on network, parse, or timeout error + } + + final ImageIcon result = icon; + SwingUtilities.invokeLater(() -> callback.accept(result)); + }); + } + + /** + * Reads image bytes safely by inspecting image dimensions through ImageReader + * before allocating memory for the full raster, mitigating decompression bombs. + */ + private static BufferedImage readBounded(byte[] bytes) throws IOException { + try (ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes))) { + if (iis == null) { + return null; + } + Iterator readers = ImageIO.getImageReaders(iis); + if (!readers.hasNext()) { + return null; + } + ImageReader reader = readers.next(); + try { + reader.setInput(iis, true, true); + long pixels = (long) reader.getWidth(0) * reader.getHeight(0); + return pixels <= MAX_IMAGE_PIXELS ? reader.read(0) : null; + } finally { + reader.dispose(); + } + } + } +} diff --git a/src/main/java/com/foodsense/security/SecurityValidator.java b/src/main/java/com/foodsense/security/SecurityValidator.java new file mode 100644 index 0000000..1e554cb --- /dev/null +++ b/src/main/java/com/foodsense/security/SecurityValidator.java @@ -0,0 +1,117 @@ +/* + * Input validation, sanitization, and security defenses for FoodSense. + * Protects against barcode path manipulation, Swing HTML injection, and SSRF. + */ + +package com.foodsense.security; + +import java.net.URI; +import java.util.regex.Pattern; + +/** + * Utility class providing defense-in-depth security validations: + * strict barcode formatting, HTML escaping for Swing labels, and HTTPS URL verification. + */ +public final class SecurityValidator { + + private static final java.util.List ALLOWED_IMAGE_HOST_SUFFIXES = + java.util.List.of("openfoodfacts.org", "openfoodfacts.net"); + + /** + * Barcodes must be 3-48 characters containing only alphanumeric characters, dashes, or underscores. + * Rejects control characters, path separators ('/' or '\\'), spaces, and query characters ('?', '#'). + */ + private static final Pattern BARCODE_PATTERN = Pattern.compile("^[A-Za-z0-9_-]{3,48}$"); + + private SecurityValidator() { + // Prevent instantiation of utility class + } + + /** + * Validates whether a barcode string matches the permitted allowlist pattern. + * + * @param barcode candidate barcode string + * @return {@code true} if non-null and matching {@code ^[A-Za-z0-9_-]{3,48}$}; {@code false} otherwise + * @example + *
{@code
+     * boolean valid = SecurityValidator.isValidBarcode("0049000006346"); // true
+     * boolean invalid = SecurityValidator.isValidBarcode("../evil");     // false
+     * }
+ */ + public static boolean isValidBarcode(String barcode) { + if (barcode == null) { + return false; + } + String trimmed = barcode.trim(); + return BARCODE_PATTERN.matcher(trimmed).matches(); + } + + /** + * Sanitizes untrusted text for safe interpolation inside Swing {@code } components. + * Converts {@code &}, {@code <}, {@code >}, {@code "}, and {@code '} to HTML entities. + * + * @param text raw input text (may be {@code null}) + * @return escaped HTML-safe string, or empty string if input is {@code null} + * @example + *
{@code
+     * String safe = SecurityValidator.escapeHtml("");
+     * // returns "<script>alert(1)</script>"
+     * }
+ */ + public static String escapeHtml(String text) { + if (text == null) { + return ""; + } + StringBuilder sb = new StringBuilder(text.length() + 16); + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + switch (c) { + case '&' -> sb.append("&"); + case '<' -> sb.append("<"); + case '>' -> sb.append(">"); + case '"' -> sb.append("""); + case '\'' -> sb.append("'"); + default -> sb.append(c); + } + } + return sb.toString(); + } + + /** + * Validates whether a given URL string is an external HTTPS URL and does not target + * loopback or cloud metadata IP addresses. + * + * @param urlString URL candidate to validate + * @return {@code true} if scheme is strictly {@code https} and host is not a private/loopback address + * @example + *
{@code
+     * SecurityValidator.isSafeHttpsUrl("https://images.openfoodfacts.org/img.jpg"); // true
+     * SecurityValidator.isSafeHttpsUrl("http://169.254.169.254/latest");          // false
+     * }
+ */ + public static boolean isSafeHttpsUrl(String urlString) { + if (urlString == null || urlString.isBlank()) { + return false; + } + try { + URI uri = URI.create(urlString.trim()); + String scheme = uri.getScheme(); + if (!"https".equalsIgnoreCase(scheme)) { + return false; + } + String host = uri.getHost(); + if (host == null || host.isBlank()) { + return false; + } + String lowerHost = host.toLowerCase(java.util.Locale.ROOT); + for (String suffix : ALLOWED_IMAGE_HOST_SUFFIXES) { + if (lowerHost.equals(suffix) || lowerHost.endsWith("." + suffix)) { + return true; + } + } + return false; + } catch (Exception ignored) { + return false; + } + } +} diff --git a/src/main/java/com/foodsense/ui/AllergenBanner.java b/src/main/java/com/foodsense/ui/AllergenBanner.java new file mode 100644 index 0000000..5a6183d --- /dev/null +++ b/src/main/java/com/foodsense/ui/AllergenBanner.java @@ -0,0 +1,77 @@ +/* + * Danger-styled allergen warning banner for FoodSense. + * Displays allergen chips/pills in a highlighted alert card. + */ + +package com.foodsense.ui; + +import javax.swing.*; +import java.awt.*; +import java.awt.geom.RoundRectangle2D; + +/** + * Modern allergen warning card displaying parsed allergen badges with clear warning iconography. + */ +public class AllergenBanner extends JPanel { + + public AllergenBanner(String allergensText) { + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setOpaque(false); + setAlignmentX(Component.LEFT_ALIGNMENT); + + JPanel card = new JPanel() { + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setColor(FoodSenseTheme.getDangerBackground()); + g2.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 12, 12)); + g2.setColor(FoodSenseTheme.getDangerBorder()); + g2.setStroke(new BasicStroke(1.2f)); + g2.draw(new RoundRectangle2D.Float(0, 0, getWidth() - 1, getHeight() - 1, 12, 12)); + g2.dispose(); + } + }; + card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS)); + card.setOpaque(false); + card.setBorder(BorderFactory.createEmptyBorder(16, 20, 16, 20)); + card.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE)); + card.setAlignmentX(Component.LEFT_ALIGNMENT); + + // Header row + JPanel header = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0)); + header.setOpaque(false); + header.setAlignmentX(Component.LEFT_ALIGNMENT); + + JLabel icon = new JLabel("⚠"); + icon.setFont(FoodSenseTheme.getFont(Font.BOLD, 18f)); + icon.setForeground(FoodSenseTheme.getDanger()); + header.add(icon); + + JLabel title = new JLabel("Allergen Warning"); + title.setFont(FoodSenseTheme.getFont(Font.BOLD, 15f)); + title.setForeground(FoodSenseTheme.getDanger()); + header.add(title); + + card.add(header); + card.add(Box.createVerticalStrut(10)); + + // Details + JTextArea area = new JTextArea(allergensText != null ? allergensText : "") { + @Override + public boolean getScrollableTracksViewportWidth() { + return true; + } + }; + area.setFont(FoodSenseTheme.getFont(Font.PLAIN, 13f)); + area.setForeground(FoodSenseTheme.getDanger()); + area.setOpaque(false); + area.setLineWrap(true); + area.setWrapStyleWord(true); + area.setEditable(false); + card.add(area); + + add(card); + } +} diff --git a/src/main/java/com/foodsense/ui/CameraScanDialog.java b/src/main/java/com/foodsense/ui/CameraScanDialog.java new file mode 100644 index 0000000..ff05b73 --- /dev/null +++ b/src/main/java/com/foodsense/ui/CameraScanDialog.java @@ -0,0 +1,220 @@ +/* + * In-app camera scanner modal dialog for FoodSense. + * Embeds live camera stream with an illuminated viewfinder reticle and animated scan guide. + */ + +package com.foodsense.ui; + +import com.foodsense.VideoProcessor; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.geom.RoundRectangle2D; +import java.awt.image.BufferedImage; +import java.util.function.Consumer; + +/** + * Modern modal scanner dialog displaying live webcam feed with viewfinder reticles + * and animated scan line. + */ +public class CameraScanDialog extends JDialog { + + private final Consumer onBarcodeScanned; + private VideoProcessor videoProcessor; + private BufferedImage currentFrame = null; + private final ViewfinderPanel viewfinder; + private final JLabel statusLabel; + private final Timer scanAnimTimer; + private float scanLinePos = 0.0f; + private boolean scanLineDown = true; + + /** + * Constructs and opens the camera scanner modal. + * + * @param parent parent JFrame + * @param onBarcodeScanned callback invoked on EDT with detected barcode string + */ + public CameraScanDialog(JFrame parent, Consumer onBarcodeScanned) { + super(parent, "Live Barcode Scanner", true); + this.onBarcodeScanned = onBarcodeScanned; + + setSize(680, 560); + setResizable(false); + setLocationRelativeTo(parent); + setLayout(new BorderLayout()); + getContentPane().setBackground(new Color(15, 23, 42)); + + viewfinder = new ViewfinderPanel(); + add(viewfinder, BorderLayout.CENTER); + + // Bottom control bar + JPanel bottomBar = new JPanel(new BorderLayout()); + bottomBar.setBackground(new Color(11, 19, 32)); + bottomBar.setBorder(BorderFactory.createEmptyBorder(12, 20, 12, 20)); + + statusLabel = new JLabel("● Align barcode within the viewfinder"); + statusLabel.setFont(FoodSenseTheme.getFont(Font.PLAIN, 13f)); + statusLabel.setForeground(new Color(148, 163, 184)); + bottomBar.add(statusLabel, BorderLayout.WEST); + + JButton cancelBtn = new JButton("Cancel"); + cancelBtn.setFont(FoodSenseTheme.getFont(Font.BOLD, 12f)); + cancelBtn.setFocusPainted(false); + cancelBtn.addActionListener(e -> closeScanner()); + bottomBar.add(cancelBtn, BorderLayout.EAST); + + add(bottomBar, BorderLayout.SOUTH); + + // Esc key listener + getRootPane().registerKeyboardAction( + e -> closeScanner(), + KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), + JComponent.WHEN_IN_FOCUSED_WINDOW + ); + + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + closeScanner(); + } + }); + + // Scan line animation timer (30 FPS) + scanAnimTimer = new Timer(33, e -> { + if (scanLineDown) { + scanLinePos += 0.03f; + if (scanLinePos >= 1.0f) { + scanLinePos = 1.0f; + scanLineDown = false; + } + } else { + scanLinePos -= 0.03f; + if (scanLinePos <= 0.0f) { + scanLinePos = 0.0f; + scanLineDown = true; + } + } + viewfinder.repaint(); + }); + } + + /** + * Initializes camera grabber and makes modal visible. + */ + public void open() { + scanAnimTimer.start(); + + videoProcessor = new VideoProcessor( + barcode -> SwingUtilities.invokeLater(() -> { + statusLabel.setText("✔ Barcode detected!"); + statusLabel.setForeground(new Color(52, 211, 153)); + if (onBarcodeScanned != null) { + onBarcodeScanned.accept(barcode); + } + closeScanner(); + }), + image -> SwingUtilities.invokeLater(() -> { + this.currentFrame = image; + viewfinder.repaint(); + }), + errorMsg -> SwingUtilities.invokeLater(() -> { + statusLabel.setText("⚠ " + errorMsg); + statusLabel.setForeground(new Color(248, 113, 113)); + }) + ); + + videoProcessor.start(); + setVisible(true); + } + + private void closeScanner() { + scanAnimTimer.stop(); + if (videoProcessor != null) { + videoProcessor.stop(); + } + dispose(); + } + + /** + * Custom surface rendering camera feed with semi-transparent vignette and viewfinder reticle. + */ + private class ViewfinderPanel extends JPanel { + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + + int w = getWidth(); + int h = getHeight(); + + // 1. Draw camera video frame if available + if (currentFrame != null) { + g2.drawImage(currentFrame, 0, 0, w, h, null); + } else { + g2.setColor(new Color(15, 23, 42)); + g2.fillRect(0, 0, w, h); + g2.setColor(new Color(148, 163, 184)); + g2.setFont(FoodSenseTheme.getFont(Font.PLAIN, 14f)); + String msg = "Connecting to camera..."; + FontMetrics fm = g2.getFontMetrics(); + g2.drawString(msg, (w - fm.stringWidth(msg)) / 2, h / 2); + } + + // 2. Viewfinder dimensions + int boxW = 380; + int boxH = 200; + int boxX = (w - boxW) / 2; + int boxY = (h - boxH) / 2; + + // Semi-transparent dark overlay around the viewfinder + g2.setColor(new Color(0, 0, 0, 140)); + // Top + g2.fillRect(0, 0, w, boxY); + // Bottom + g2.fillRect(0, boxY + boxH, w, h - (boxY + boxH)); + // Left + g2.fillRect(0, boxY, boxX, boxH); + // Right + g2.fillRect(boxX + boxW, boxY, w - (boxX + boxW), boxH); + + // 3. Viewfinder border & corner reticles + g2.setColor(new Color(255, 255, 255, 60)); + g2.setStroke(new BasicStroke(1f)); + g2.draw(new RoundRectangle2D.Float(boxX, boxY, boxW, boxH, 12, 12)); + + // Corner brackets (bold mint accent) + g2.setColor(new Color(52, 211, 153)); + g2.setStroke(new BasicStroke(3.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); + int arm = 24; + // Top-left + g2.drawLine(boxX, boxY + arm, boxX, boxY); + g2.drawLine(boxX, boxY, boxX + arm, boxY); + // Top-right + g2.drawLine(boxX + boxW - arm, boxY, boxX + boxW, boxY); + g2.drawLine(boxX + boxW, boxY, boxX + boxW, boxY + arm); + // Bottom-left + g2.drawLine(boxX, boxY + boxH - arm, boxX, boxY + boxH); + g2.drawLine(boxX, boxY + boxH, boxX + arm, boxY + boxH); + // Bottom-right + g2.drawLine(boxX + boxW - arm, boxY + boxH, boxX + boxW, boxY + boxH); + g2.drawLine(boxX + boxW, boxY + boxH - arm, boxX + boxW, boxY + boxH); + + // 4. Animated scan line + int lineY = (int) (boxY + (boxH * scanLinePos)); + GradientPaint gp = new GradientPaint( + boxX, lineY, new Color(52, 211, 153, 0), + boxX + boxW / 2f, lineY, new Color(52, 211, 153, 220), + true + ); + g2.setPaint(gp); + g2.setStroke(new BasicStroke(2f)); + g2.drawLine(boxX + 10, lineY, boxX + boxW - 10, lineY); + + g2.dispose(); + } + } +} diff --git a/src/main/java/com/foodsense/ui/FoodSenseTheme.java b/src/main/java/com/foodsense/ui/FoodSenseTheme.java new file mode 100644 index 0000000..2933457 --- /dev/null +++ b/src/main/java/com/foodsense/ui/FoodSenseTheme.java @@ -0,0 +1,216 @@ +/* + * Design token definitions, color palettes, and theme management for FoodSense. + * Features an authentic forest green / botanical aesthetic for both Light and Dark modes. + */ + +package com.foodsense.ui; + +import com.formdev.flatlaf.FlatDarkLaf; +import com.formdev.flatlaf.FlatLightLaf; + +import javax.swing.*; +import java.awt.*; + +/** + * Central design tokens, color scales, and theme configuration for FoodSense. + * Adheres to a botanical forest green aesthetic for both light and dark modes. + */ +public final class FoodSenseTheme { + + // ── Spacing Scale (4px grid) ────────────────────────────── + public static final int SPACE_2 = 2; + public static final int SPACE_4 = 4; + public static final int SPACE_8 = 8; + public static final int SPACE_12 = 12; + public static final int SPACE_16 = 16; + public static final int SPACE_20 = 20; + public static final int SPACE_24 = 24; + public static final int SPACE_32 = 32; + + // ── Nutri-Score Official Palette ────────────────────────── + public static final Color SCORE_A = new Color(3, 129, 65); + public static final Color SCORE_B = new Color(133, 187, 47); + public static final Color SCORE_C = new Color(254, 203, 2); + public static final Color SCORE_D = new Color(238, 129, 0); + public static final Color SCORE_E = new Color(230, 62, 17); + + // ── State ───────────────────────────────────────────────── + private static boolean darkMode = false; + + private FoodSenseTheme() { + // Prevent instantiation + } + + /** + * Initializes FlatLaf Look and Feel with anti-aliasing rendering hints. + */ + public static void initialize() { + System.setProperty("awt.useSystemAAFontSettings", "on"); + System.setProperty("swing.aatext", "true"); + + try { + if (darkMode) { + FlatDarkLaf.setup(); + } else { + FlatLightLaf.setup(); + } + } catch (Exception e) { + System.err.println("Notice: FlatLaf setup fallback: " + e.getMessage()); + } + } + + /** + * Returns whether the active theme is dark mode. + * + * @return {@code true} if dark mode; {@code false} if light mode + */ + public static boolean isDarkMode() { + return darkMode; + } + + /** + * Toggles between Light and Dark mode, updating FlatLaf and repainting the component tree. + * + * @param root component tree to update (typically top-level JFrame) + */ + public static void toggleTheme(Component root) { + setDarkMode(!darkMode, root); + } + + /** + * Sets the active theme mode and updates Swing component UI defaults. + * + * @param dark true for dark mode; false for light mode + * @param root component tree to update + */ + public static void setDarkMode(boolean dark, Component root) { + darkMode = dark; + try { + if (darkMode) { + FlatDarkLaf.setup(); + } else { + FlatLightLaf.setup(); + } + if (root != null) { + SwingUtilities.updateComponentTreeUI(root); + root.repaint(); + } + } catch (Exception e) { + System.err.println("Theme update failed: " + e.getMessage()); + } + } + + // ── Forest Theme Semantic Colors ────────────────────────── + + public static Color getBackground() { + // Light: Gentle morning mist botanical green; Dark: Deep obsidian forest + return darkMode ? new Color(11, 22, 14) : new Color(244, 248, 244); + } + + public static Color getSidebarBackground() { + // Light: Soft light sage rail; Dark: Deep midnight evergreen rail + return darkMode ? new Color(8, 18, 11) : new Color(235, 244, 237); + } + + public static Color getSidebarText() { + // Light: Deep pine green; Dark: Crisp mint white + return darkMode ? new Color(240, 253, 244) : new Color(18, 48, 26); + } + + public static Color getSidebarMuted() { + // Light: Medium fern green; Dark: Radiant mint + return darkMode ? new Color(110, 231, 183) : new Color(68, 108, 80); + } + + public static Color getCardBackground() { + // Light: Pure white; Dark: Elevated dark pine surface + return darkMode ? new Color(18, 35, 22) : Color.WHITE; + } + + public static Color getCardBorder() { + return darkMode ? new Color(31, 58, 37) : new Color(212, 228, 215); + } + + public static Color getTextPrimary() { + // Light: Deep pine black; Dark: Crisp mint white + return darkMode ? new Color(240, 253, 244) : new Color(16, 44, 24); + } + + public static Color getTextSecondary() { + return darkMode ? new Color(167, 243, 208) : new Color(38, 72, 48); + } + + public static Color getTextMuted() { + return darkMode ? new Color(110, 231, 183) : new Color(78, 114, 88); + } + + public static Color getPrimaryAccent() { + // Light: Rich botanical emerald green; Dark: Radiant emerald mint + return darkMode ? new Color(52, 211, 153) : new Color(22, 102, 53); + } + + public static Color getPrimaryAccentHover() { + return darkMode ? new Color(16, 185, 129) : new Color(16, 82, 42); + } + + public static Color getPrimaryLight() { + return darkMode ? new Color(12, 54, 30) : new Color(230, 246, 233); + } + + public static Color getChipBackground() { + return darkMode ? new Color(16, 36, 24) : new Color(236, 247, 238); + } + + public static Color getChipBorder() { + return darkMode ? new Color(30, 64, 40) : new Color(200, 226, 204); + } + + public static Color getChipText() { + return darkMode ? new Color(236, 253, 245) : new Color(20, 52, 30); + } + + public static Color getDanger() { + return darkMode ? new Color(248, 113, 113) : new Color(220, 38, 38); + } + + public static Color getDangerBackground() { + return darkMode ? new Color(69, 10, 10) : new Color(254, 242, 242); + } + + public static Color getDangerBorder() { + return darkMode ? new Color(127, 29, 29) : new Color(254, 202, 202); + } + + /** + * Resolves the official background color for a Nutri-Score grade letter. + * + * @param grade letter grade (A-E) + * @return matching Nutri-Score color, or muted grey if unknown + */ + public static Color getNutriscoreColor(String grade) { + if (grade == null) { + return getTextMuted(); + } + return switch (grade.trim().toUpperCase()) { + case "A" -> SCORE_A; + case "B" -> SCORE_B; + case "C" -> SCORE_C; + case "D" -> SCORE_D; + case "E" -> SCORE_E; + default -> getTextMuted(); + }; + } + + // ── Typography ──────────────────────────────────────────── + + /** + * Returns a styled modern font for the given weight and size. + * + * @param weight Font.PLAIN or Font.BOLD + * @param size font size in points + * @return Font instance + */ + public static Font getFont(int weight, float size) { + return new Font("SansSerif", weight, (int) size); + } +} diff --git a/src/main/java/com/foodsense/ui/IngredientsPanel.java b/src/main/java/com/foodsense/ui/IngredientsPanel.java new file mode 100644 index 0000000..4ab3507 --- /dev/null +++ b/src/main/java/com/foodsense/ui/IngredientsPanel.java @@ -0,0 +1,268 @@ +/* + * Structured ingredients panel for FoodSense. + * Parses raw ingredient paragraphs into discrete, readable chips with allergen highlights. + */ + +package com.foodsense.ui; + +import com.foodsense.security.SecurityValidator; + +import javax.swing.*; +import java.awt.*; +import java.awt.geom.RoundRectangle2D; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +/** + * Modern ingredients card with discrete tags/chips, allergen highlighting, + * item count badge, and a toggle between chip flow and original text. + */ +public class IngredientsPanel extends JPanel { + + private final String rawText; + private final String allergensText; + private final List parsedIngredients; + private final CardLayout cardLayout = new CardLayout(); + private final JPanel bodyContainer = new JPanel(cardLayout); + private boolean showingChips = true; + private JButton toggleBtn; + + /** + * Constructs the ingredients panel for a given ingredients string and allergen list. + * + * @param rawText raw ingredients text from Open Food Facts API + * @param allergensText allergens text from API used to highlight suspect ingredients + */ + public IngredientsPanel(String rawText, String allergensText) { + this.rawText = rawText != null ? rawText.trim() : ""; + this.allergensText = allergensText != null ? allergensText.toLowerCase(Locale.ROOT) : ""; + this.parsedIngredients = parseIngredients(this.rawText); + + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setOpaque(false); + setAlignmentX(Component.LEFT_ALIGNMENT); + + add(buildCard()); + } + + private JPanel buildCard() { + JPanel card = new JPanel() { + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setColor(FoodSenseTheme.getCardBackground()); + g2.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 12, 12)); + g2.setColor(FoodSenseTheme.getCardBorder()); + g2.setStroke(new BasicStroke(1f)); + g2.draw(new RoundRectangle2D.Float(0, 0, getWidth() - 1, getHeight() - 1, 12, 12)); + g2.dispose(); + } + }; + card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS)); + card.setOpaque(false); + card.setBorder(BorderFactory.createEmptyBorder(16, 20, 16, 20)); + card.setAlignmentX(Component.LEFT_ALIGNMENT); + + // Header Row + JPanel headerRow = new JPanel(new BorderLayout()); + headerRow.setOpaque(false); + headerRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, 30)); + + JPanel titleBlock = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0)); + titleBlock.setOpaque(false); + + JLabel title = new JLabel("Ingredients"); + title.setFont(FoodSenseTheme.getFont(Font.BOLD, 16f)); + title.setForeground(FoodSenseTheme.getTextPrimary()); + titleBlock.add(title); + + if (!parsedIngredients.isEmpty()) { + JLabel countBadge = new JLabel(parsedIngredients.size() + " items"); + countBadge.setFont(FoodSenseTheme.getFont(Font.BOLD, 10f)); + countBadge.setForeground(FoodSenseTheme.getPrimaryAccent()); + countBadge.setBackground(FoodSenseTheme.getPrimaryLight()); + countBadge.setOpaque(true); + countBadge.setBorder(BorderFactory.createEmptyBorder(3, 8, 3, 8)); + titleBlock.add(countBadge); + } + headerRow.add(titleBlock, BorderLayout.WEST); + + if (!rawText.isEmpty()) { + toggleBtn = new JButton("View Text"); + toggleBtn.setFont(FoodSenseTheme.getFont(Font.BOLD, 11f)); + toggleBtn.setFocusPainted(false); + toggleBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + toggleBtn.putClientProperty("JButton.buttonType", "roundRect"); + toggleBtn.addActionListener(e -> { + showingChips = !showingChips; + cardLayout.show(bodyContainer, showingChips ? "CHIPS" : "TEXT"); + toggleBtn.setText(showingChips ? "View Text" : "View Chips"); + }); + headerRow.add(toggleBtn, BorderLayout.EAST); + } + + card.add(headerRow); + card.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_12)); + + // Body Panes + bodyContainer.setOpaque(false); + + if (rawText.isEmpty() || parsedIngredients.isEmpty()) { + JLabel emptyLabel = new JLabel("No ingredients listed for this product."); + emptyLabel.setFont(FoodSenseTheme.getFont(Font.PLAIN, 12f)); + emptyLabel.setForeground(FoodSenseTheme.getTextMuted()); + bodyContainer.add(emptyLabel, "EMPTY"); + } else { + bodyContainer.add(buildChipsView(), "CHIPS"); + bodyContainer.add(buildTextView(), "TEXT"); + } + + card.add(bodyContainer); + return card; + } + + private JPanel buildChipsView() { + JPanel chipsPanel = new JPanel(new WrapLayout(FlowLayout.LEFT, 6, 6)); + chipsPanel.setOpaque(false); + + for (String ingredient : parsedIngredients) { + chipsPanel.add(createIngredientChip(ingredient)); + } + + return chipsPanel; + } + + private JPanel buildTextView() { + JTextArea area = new JTextArea(rawText) { + @Override + public boolean getScrollableTracksViewportWidth() { + return true; + } + }; + area.setFont(FoodSenseTheme.getFont(Font.PLAIN, 12f)); + area.setForeground(FoodSenseTheme.getTextSecondary()); + area.setOpaque(false); + area.setLineWrap(true); + area.setWrapStyleWord(true); + area.setEditable(false); + + JPanel p = new JPanel(new BorderLayout()); + p.setOpaque(false); + p.add(area, BorderLayout.CENTER); + return p; + } + + private JComponent createIngredientChip(String text) { + boolean isAllergen = isSuspectAllergen(text); + + JPanel chip = new JPanel(new FlowLayout(FlowLayout.CENTER, 8, 4)) { + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setColor(isAllergen ? FoodSenseTheme.getDangerBackground() : FoodSenseTheme.getChipBackground()); + g2.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 10, 10)); + g2.setColor(isAllergen ? FoodSenseTheme.getDangerBorder() : FoodSenseTheme.getChipBorder()); + g2.setStroke(new BasicStroke(1f)); + g2.draw(new RoundRectangle2D.Float(0, 0, getWidth() - 1, getHeight() - 1, 10, 10)); + g2.dispose(); + } + }; + chip.setOpaque(false); + + String displayText = (isAllergen ? "⚠️ " : "") + text; + JLabel lbl = new JLabel(displayText); + lbl.putClientProperty("html.disable", Boolean.TRUE); + lbl.setFont(FoodSenseTheme.getFont(isAllergen ? Font.BOLD : Font.PLAIN, 11.5f)); + lbl.setForeground(isAllergen ? FoodSenseTheme.getDanger() : FoodSenseTheme.getChipText()); + chip.add(lbl); + + if (text.length() > 30) { + chip.setToolTipText(text); + } + + return chip; + } + + private boolean isSuspectAllergen(String ingredient) { + if (allergensText.isEmpty() || ingredient == null) { + return false; + } + String lowerIng = ingredient.toLowerCase(Locale.ROOT); + String[] allergens = allergensText.split("[,;]"); + for (String a : allergens) { + String trimmed = a.trim(); + if (!trimmed.isEmpty() && lowerIng.contains(trimmed)) { + return true; + } + } + return false; + } + + /** + * Parses an ingredients string into individual ingredient tokens, preserving + * sub-ingredients inside parentheses or brackets. + * + * @param raw raw ingredients string + * @return list of parsed discrete ingredients + */ + public static List parseIngredients(String raw) { + if (raw == null || raw.isBlank()) { + return Collections.emptyList(); + } + List items = new ArrayList<>(); + StringBuilder current = new StringBuilder(); + int parenDepth = 0; + int bracketDepth = 0; + + for (int i = 0; i < raw.length(); i++) { + char c = raw.charAt(i); + if (c == '(') { + parenDepth++; + } else if (c == ')') { + parenDepth = Math.max(0, parenDepth - 1); + } else if (c == '[') { + bracketDepth++; + } else if (c == ']') { + bracketDepth = Math.max(0, bracketDepth - 1); + } + + // Split when outside parentheses/brackets on comma, semicolon, bullet, or newline + if ((c == ',' || c == ';' || c == '•' || c == '\n') && parenDepth == 0 && bracketDepth == 0) { + String token = cleanIngredientToken(current.toString()); + if (!token.isEmpty()) { + items.add(token); + } + current.setLength(0); + } else { + current.append(c); + } + } + + String last = cleanIngredientToken(current.toString()); + if (!last.isEmpty()) { + items.add(last); + } + + return items; + } + + private static String cleanIngredientToken(String s) { + if (s == null) { + return ""; + } + String trimmed = s.trim(); + while (trimmed.endsWith(".") || trimmed.endsWith(";") || trimmed.endsWith(",")) { + trimmed = trimmed.substring(0, trimmed.length() - 1).trim(); + } + while (trimmed.startsWith("-") || trimmed.startsWith("*") || trimmed.startsWith("•")) { + trimmed = trimmed.substring(1).trim(); + } + return trimmed; + } +} diff --git a/src/main/java/com/foodsense/ui/NutriScoreSpectrumView.java b/src/main/java/com/foodsense/ui/NutriScoreSpectrumView.java new file mode 100644 index 0000000..113b702 --- /dev/null +++ b/src/main/java/com/foodsense/ui/NutriScoreSpectrumView.java @@ -0,0 +1,145 @@ +/* + * Official 5-pill Nutri-Score spectrum view (A, B, C, D, E) for FoodSense. + * Renders the detected grade enlarged and highlighted while dimming non-active grades. + */ + +package com.foodsense.ui; + +import javax.swing.*; +import java.awt.*; +import java.awt.geom.RoundRectangle2D; + +/** + * Custom Swing component that renders the standard 5-pill Nutri-Score spectrum. + * Compact and proportioned to fit sidebars without clipping. + */ +public class NutriScoreSpectrumView extends JPanel { + + private static final String[] GRADES = { "A", "B", "C", "D", "E" }; + private static final Color[] COLORS = { + FoodSenseTheme.SCORE_A, + FoodSenseTheme.SCORE_B, + FoodSenseTheme.SCORE_C, + FoodSenseTheme.SCORE_D, + FoodSenseTheme.SCORE_E + }; + + private String activeGrade = null; + + /** + * Constructs a spectrum view with no initial grade selected. + */ + public NutriScoreSpectrumView() { + this(null); + } + + /** + * Constructs a spectrum view displaying the specified active grade. + * + * @param grade Nutri-Score grade letter (A-E, case-insensitive) + */ + public NutriScoreSpectrumView(String grade) { + setOpaque(false); + setGrade(grade); + setPreferredSize(new Dimension(160, 36)); + setMaximumSize(new Dimension(180, 40)); + } + + /** + * Updates the active grade and repaints the spectrum. + * + * @param grade letter grade (A-E), or null for neutral spectrum + */ + public void setGrade(String grade) { + String normalized = grade != null ? grade.trim().toUpperCase(java.util.Locale.ROOT) : ""; + this.activeGrade = normalized.matches("[A-E]") ? normalized : null; + setToolTipText(this.activeGrade != null ? "Nutri-Score: Grade " + this.activeGrade : "Nutri-Score not available"); + repaint(); + } + + /** + * Returns the currently displayed Nutri-Score grade. + * + * @return uppercase grade string, or {@code null} + */ + public String getGrade() { + return activeGrade; + } + + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + + int totalWidth = getWidth(); + int totalHeight = getHeight(); + int pillCount = GRADES.length; + + int standardW = 24; + int standardH = 24; + int activeW = 30; + int activeH = 32; + int gap = 3; + + int activeIndex = -1; + if (activeGrade != null) { + for (int i = 0; i < GRADES.length; i++) { + if (GRADES[i].equalsIgnoreCase(activeGrade)) { + activeIndex = i; + break; + } + } + } + + int requiredWidth = (pillCount - (activeIndex >= 0 ? 1 : 0)) * standardW + + (activeIndex >= 0 ? activeW : 0) + + (pillCount - 1) * gap; + + int startX = Math.max(0, (totalWidth - requiredWidth) / 2); + int currentX = startX; + + for (int i = 0; i < pillCount; i++) { + boolean isActive = (i == activeIndex); + int w = isActive ? activeW : standardW; + int h = isActive ? activeH : standardH; + int y = (totalHeight - h) / 2; + + Color baseColor = COLORS[i]; + + if (isActive) { + // Elevated active pill + g2.setColor(baseColor); + g2.fill(new RoundRectangle2D.Float(currentX, y, w, h, 8, 8)); + + // Clean highlight border + g2.setColor(new Color(255, 255, 255, 220)); + g2.setStroke(new BasicStroke(1.5f)); + g2.draw(new RoundRectangle2D.Float(currentX, y, w, h, 8, 8)); + + g2.setFont(FoodSenseTheme.getFont(Font.BOLD, 14f)); + g2.setColor(Color.WHITE); + } else { + // Dimmed inactive pill + int alpha = (activeIndex >= 0) ? 90 : 180; + Color dimmed = new Color(baseColor.getRed(), baseColor.getGreen(), baseColor.getBlue(), alpha); + g2.setColor(dimmed); + g2.fill(new RoundRectangle2D.Float(currentX, y, w, h, 6, 6)); + + g2.setFont(FoodSenseTheme.getFont(Font.BOLD, 11f)); + g2.setColor(new Color(255, 255, 255, (activeIndex >= 0) ? 140 : 220)); + } + + // Draw centered letter + FontMetrics fm = g2.getFontMetrics(); + int textX = currentX + (w - fm.stringWidth(GRADES[i])) / 2; + int textY = y + ((h - fm.getHeight()) / 2) + fm.getAscent(); + g2.drawString(GRADES[i], textX, textY); + + currentX += w + gap; + } + + g2.dispose(); + } +} diff --git a/src/main/java/com/foodsense/ui/NutritionLabelPanel.java b/src/main/java/com/foodsense/ui/NutritionLabelPanel.java new file mode 100644 index 0000000..5ff9b5a --- /dev/null +++ b/src/main/java/com/foodsense/ui/NutritionLabelPanel.java @@ -0,0 +1,532 @@ +/* + * Structured nutrition card for FoodSense. + * Displays hero calorie metric, macronutrient summary cards, energy distribution ratio, + * authentic subdivided nutrition facts table, and dietary benchmark indicators. + */ + +package com.foodsense.ui; + +import com.foodsense.Nutriments; + +import javax.swing.*; +import java.awt.*; +import java.awt.geom.RoundRectangle2D; +import java.util.Locale; + +/** + * Modern nutrition facts panel featuring rounded hero calories, macronutrient summary cards, + * calorie distribution ratio bar, dietary health benchmarks, and a subdivided per-100g nutrient breakdown. + */ +public class NutritionLabelPanel extends JPanel { + + public NutritionLabelPanel(Nutriments nutriments) { + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setOpaque(false); + setAlignmentX(Component.LEFT_ALIGNMENT); + + Nutriments n = nutriments != null ? nutriments : new Nutriments(); + + add(buildHeader()); + add(Box.createVerticalStrut(FoodSenseTheme.SPACE_16)); + add(buildHeroCalories(n)); + add(Box.createVerticalStrut(FoodSenseTheme.SPACE_16)); + add(buildMacroCards(n)); + add(Box.createVerticalStrut(FoodSenseTheme.SPACE_12)); + + JPanel ratioBar = buildMacroRatioBar(n); + if (ratioBar != null) { + add(ratioBar); + add(Box.createVerticalStrut(FoodSenseTheme.SPACE_16)); + } + + JPanel dietaryProfile = buildDietaryBenchmarkCards(n); + if (dietaryProfile != null) { + add(dietaryProfile); + add(Box.createVerticalStrut(FoodSenseTheme.SPACE_16)); + } + + add(buildNutrientTable(n)); + } + + private JPanel buildHeader() { + JPanel p = new JPanel(); + p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); + p.setOpaque(false); + p.setAlignmentX(Component.LEFT_ALIGNMENT); + + JLabel title = new JLabel("Nutrition Facts"); + title.setFont(FoodSenseTheme.getFont(Font.BOLD, 18f)); + title.setForeground(FoodSenseTheme.getTextPrimary()); + p.add(title); + + JLabel subtitle = new JLabel("Reference amounts per 100g / 100ml"); + subtitle.setFont(FoodSenseTheme.getFont(Font.PLAIN, 12f)); + subtitle.setForeground(FoodSenseTheme.getTextMuted()); + p.add(subtitle); + + return p; + } + + private JPanel buildHeroCalories(Nutriments n) { + JPanel hero = new JPanel(new BorderLayout()) { + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setColor(FoodSenseTheme.getCardBackground()); + g2.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 12, 12)); + g2.setColor(FoodSenseTheme.getCardBorder()); + g2.setStroke(new BasicStroke(1f)); + g2.draw(new RoundRectangle2D.Float(0, 0, getWidth() - 1, getHeight() - 1, 12, 12)); + g2.dispose(); + } + }; + hero.setOpaque(false); + hero.setBorder(BorderFactory.createEmptyBorder(14, 20, 14, 20)); + hero.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75)); + hero.setAlignmentX(Component.LEFT_ALIGNMENT); + + JPanel left = new JPanel(); + left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS)); + left.setOpaque(false); + + JLabel label = new JLabel("ENERGY / CALORIES"); + label.setFont(FoodSenseTheme.getFont(Font.BOLD, 10f)); + label.setForeground(FoodSenseTheme.getTextMuted()); + left.add(label); + + // Resolve calories using explicit Open Food Facts fields + String kcalText = "— kcal"; + String kjText = ""; + + if (n.getEnergyKcal() != null && !n.getEnergyKcal().isBlank()) { + try { + double val = Double.parseDouble(n.getEnergyKcal().trim()); + int kcal = (int) Math.round(val); + kcalText = kcal + " kcal"; + if (n.getEnergyKj() != null && !n.getEnergyKj().isBlank()) { + int kj = (int) Math.round(Double.parseDouble(n.getEnergyKj().trim())); + kjText = kj + " kJ"; + } else { + int kj = (int) Math.round(val * 4.184); + kjText = kj + " kJ"; + } + } catch (NumberFormatException ignored) { + kcalText = n.getEnergyKcal() + " kcal"; + } + } else if (n.getEnergyKj() != null && !n.getEnergyKj().isBlank()) { + try { + double val = Double.parseDouble(n.getEnergyKj().trim()); + int kj = (int) Math.round(val); + int kcal = (int) Math.round(val / 4.184); + kcalText = kcal + " kcal"; + kjText = kj + " kJ"; + } catch (NumberFormatException ignored) { + kjText = n.getEnergyKj() + " kJ"; + } + } else if (n.getEnergy() != null && !n.getEnergy().isBlank()) { + try { + double val = Double.parseDouble(n.getEnergy().trim()); + // Open Food Facts API spec: standard "energy" without suffix is reported in kJ + int kj = (int) Math.round(val); + int kcal = (int) Math.round(val / 4.184); + kcalText = kcal + " kcal"; + kjText = kj + " kJ"; + } catch (NumberFormatException ignored) { + kcalText = n.getEnergy() + " kcal"; + } + } + + JLabel num = new JLabel(kcalText); + num.putClientProperty("html.disable", Boolean.TRUE); + num.setFont(FoodSenseTheme.getFont(Font.BOLD, 24f)); + num.setForeground(FoodSenseTheme.getPrimaryAccent()); + left.add(num); + + hero.add(left, BorderLayout.WEST); + + if (!kjText.isEmpty()) { + JLabel rightKj = new JLabel(kjText); + rightKj.putClientProperty("html.disable", Boolean.TRUE); + rightKj.setFont(FoodSenseTheme.getFont(Font.BOLD, 13f)); + rightKj.setForeground(FoodSenseTheme.getTextMuted()); + hero.add(rightKj, BorderLayout.EAST); + } + + return hero; + } + + private JPanel buildMacroCards(Nutriments n) { + JPanel grid = new JPanel(new GridLayout(1, 3, 10, 0)); + grid.setOpaque(false); + grid.setMaximumSize(new Dimension(Integer.MAX_VALUE, 72)); + grid.setAlignmentX(Component.LEFT_ALIGNMENT); + + String carbVal = formatRounded(n.getCarbohydrates()); + String sugarVal = formatRounded(n.getSugars()); + String fatVal = formatRounded(n.getFat()); + String satFatVal = formatRounded(n.getSaturated_fat()); + String proteinVal = formatRounded(n.getProteins()); + + String carbMain = carbVal != null ? carbVal + "g" : "—"; + String sugarSub = sugarVal != null ? "Sugars " + sugarVal + "g" : "Sugars —"; + String fatMain = fatVal != null ? fatVal + "g" : "—"; + String satFatSub = satFatVal != null ? "Saturates " + satFatVal + "g" : "Saturates —"; + String proteinMain = proteinVal != null ? proteinVal + "g" : "—"; + + grid.add(mkMacroChip("Carbohydrates", carbMain, sugarSub, new Color(217, 119, 6))); + grid.add(mkMacroChip("Fats", fatMain, satFatSub, new Color(225, 29, 72))); + grid.add(mkMacroChip("Proteins", proteinMain, "Building blocks", new Color(5, 150, 105))); + + return grid; + } + + private JPanel mkMacroChip(String title, String mainValue, String subValue, Color accentColor) { + JPanel chip = new JPanel() { + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setColor(FoodSenseTheme.getCardBackground()); + g2.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 10, 10)); + g2.setColor(FoodSenseTheme.getCardBorder()); + g2.setStroke(new BasicStroke(1f)); + g2.draw(new RoundRectangle2D.Float(0, 0, getWidth() - 1, getHeight() - 1, 10, 10)); + + // Left color accent bar + g2.setColor(accentColor); + g2.fill(new RoundRectangle2D.Float(0, 0, 4, getHeight(), 4, 4)); + g2.dispose(); + } + }; + chip.setLayout(new BoxLayout(chip, BoxLayout.Y_AXIS)); + chip.setOpaque(false); + chip.setBorder(BorderFactory.createEmptyBorder(10, 14, 10, 12)); + + JLabel t = new JLabel(title); + t.setFont(FoodSenseTheme.getFont(Font.BOLD, 10f)); + t.setForeground(FoodSenseTheme.getTextMuted()); + chip.add(t); + + JLabel v = new JLabel(mainValue); + v.putClientProperty("html.disable", Boolean.TRUE); + v.setFont(FoodSenseTheme.getFont(Font.BOLD, 15f)); + v.setForeground(FoodSenseTheme.getTextPrimary()); + chip.add(v); + + JLabel sub = new JLabel(subValue); + sub.setFont(FoodSenseTheme.getFont(Font.PLAIN, 10f)); + sub.setForeground(FoodSenseTheme.getTextMuted()); + chip.add(sub); + + return chip; + } + + /** + * Builds a segmented calorie contribution ratio bar (% Carbs, % Fat, % Protein). + */ + private JPanel buildMacroRatioBar(Nutriments n) { + double carbs = parseDouble(n.getCarbohydrates()); + double fat = parseDouble(n.getFat()); + double protein = parseDouble(n.getProteins()); + + double carbKcal = carbs * 4.0; + double fatKcal = fat * 9.0; + double protKcal = protein * 4.0; + double totalKcal = carbKcal + fatKcal + protKcal; + + if (totalKcal <= 0) { + return null; + } + + final int carbPct = (int) Math.round((carbKcal / totalKcal) * 100); + final int fatPct = (int) Math.round((fatKcal / totalKcal) * 100); + final int protPct = Math.max(0, 100 - carbPct - fatPct); + + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); + panel.setOpaque(false); + panel.setAlignmentX(Component.LEFT_ALIGNMENT); + + // Segmented bar + JPanel bar = new JPanel() { + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + + int w = getWidth(); + int h = getHeight(); + int r = 8; + + // Clip to rounded rectangle + Shape clip = new RoundRectangle2D.Float(0, 0, w, h, r, r); + g2.setClip(clip); + + int carbW = (int) Math.round(w * (carbPct / 100.0)); + int fatW = (int) Math.round(w * (fatPct / 100.0)); + int protW = w - carbW - fatW; + + g2.setColor(new Color(217, 119, 6)); // Carbs amber + g2.fillRect(0, 0, carbW, h); + + g2.setColor(new Color(225, 29, 72)); // Fat rose + g2.fillRect(carbW, 0, fatW, h); + + g2.setColor(new Color(5, 150, 105)); // Protein emerald + g2.fillRect(carbW + fatW, 0, protW, h); + + g2.setClip(null); + g2.setColor(FoodSenseTheme.getCardBorder()); + g2.setStroke(new BasicStroke(1f)); + g2.draw(new RoundRectangle2D.Float(0, 0, w - 1, h - 1, r, r)); + + g2.dispose(); + } + }; + bar.setPreferredSize(new Dimension(0, 10)); + bar.setMaximumSize(new Dimension(Integer.MAX_VALUE, 10)); + bar.setOpaque(false); + panel.add(bar); + + panel.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_4)); + + // Legend + JPanel legend = new JPanel(new FlowLayout(FlowLayout.LEFT, 12, 0)); + legend.setOpaque(false); + + legend.add(mkLegendDot("Carbs " + carbPct + "%", new Color(217, 119, 6))); + legend.add(mkLegendDot("Fat " + fatPct + "%", new Color(225, 29, 72))); + legend.add(mkLegendDot("Protein " + protPct + "%", new Color(5, 150, 105))); + + panel.add(legend); + return panel; + } + + private JLabel mkLegendDot(String text, Color dotColor) { + JLabel l = new JLabel("● " + text); + l.setFont(FoodSenseTheme.getFont(Font.BOLD, 10f)); + l.setForeground(dotColor); + return l; + } + + /** + * Builds dietary health benchmark indicators based on WHO / FDA nutritional guidelines. + */ + private JPanel buildDietaryBenchmarkCards(Nutriments n) { + double sugars = parseDouble(n.getSugars()); + double satFat = parseDouble(n.getSaturated_fat()); + double sodium = parseSodiumMg(n.getSodium()); + + boolean hasData = n.getSugars() != null || n.getSaturated_fat() != null || n.getSodium() != null; + if (!hasData) { + return null; + } + + JPanel wrapper = new JPanel(new GridLayout(1, 3, 10, 0)); + wrapper.setOpaque(false); + wrapper.setMaximumSize(new Dimension(Integer.MAX_VALUE, 50)); + wrapper.setAlignmentX(Component.LEFT_ALIGNMENT); + + // Sugar Benchmark: Low <= 5g, Moderate 5-15g, High > 15g + if (n.getSugars() != null) { + if (sugars <= 5.0) { + wrapper.add(mkBenchmarkPill("Sugar", "Low (" + fmt(sugars) + "g)", FoodSenseTheme.SCORE_A, "≤ 5.0g / 100g")); + } else if (sugars <= 15.0) { + wrapper.add(mkBenchmarkPill("Sugar", "Moderate (" + fmt(sugars) + "g)", FoodSenseTheme.SCORE_C, "5-15g / 100g")); + } else { + wrapper.add(mkBenchmarkPill("Sugar", "High (" + fmt(sugars) + "g)", FoodSenseTheme.SCORE_E, "> 15g / 100g")); + } + } + + // Saturated Fat Benchmark: Low <= 1.5g, Moderate 1.5-5.0g, High > 5.0g + if (n.getSaturated_fat() != null) { + if (satFat <= 1.5) { + wrapper.add(mkBenchmarkPill("Sat. Fat", "Low (" + fmt(satFat) + "g)", FoodSenseTheme.SCORE_A, "≤ 1.5g / 100g")); + } else if (satFat <= 5.0) { + wrapper.add(mkBenchmarkPill("Sat. Fat", "Moderate (" + fmt(satFat) + "g)", FoodSenseTheme.SCORE_C, "1.5-5.0g / 100g")); + } else { + wrapper.add(mkBenchmarkPill("Sat. Fat", "High (" + fmt(satFat) + "g)", FoodSenseTheme.SCORE_E, "> 5.0g / 100g")); + } + } + + // Sodium Benchmark: Low <= 120mg, Moderate 120-600mg, High > 600mg + if (n.getSodium() != null) { + if (sodium <= 120.0) { + wrapper.add(mkBenchmarkPill("Sodium", "Low (" + Math.round(sodium) + "mg)", FoodSenseTheme.SCORE_A, "≤ 120mg / 100g")); + } else if (sodium <= 600.0) { + wrapper.add(mkBenchmarkPill("Sodium", "Moderate (" + Math.round(sodium) + "mg)", FoodSenseTheme.SCORE_C, "120-600mg / 100g")); + } else { + wrapper.add(mkBenchmarkPill("Sodium", "High (" + Math.round(sodium) + "mg)", FoodSenseTheme.SCORE_E, "> 600mg / 100g")); + } + } + + return wrapper; + } + + private JPanel mkBenchmarkPill(String metric, String status, Color statusColor, String hint) { + JPanel pill = new JPanel() { + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setColor(FoodSenseTheme.getCardBackground()); + g2.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 8, 8)); + g2.setColor(FoodSenseTheme.getCardBorder()); + g2.setStroke(new BasicStroke(1f)); + g2.draw(new RoundRectangle2D.Float(0, 0, getWidth() - 1, getHeight() - 1, 8, 8)); + + // Left status indicator dot + g2.setColor(statusColor); + g2.fillOval(10, (getHeight() - 8) / 2, 8, 8); + g2.dispose(); + } + }; + pill.setLayout(new BoxLayout(pill, BoxLayout.Y_AXIS)); + pill.setOpaque(false); + pill.setBorder(BorderFactory.createEmptyBorder(6, 24, 6, 8)); + pill.setToolTipText(metric + " reference: " + hint); + + JLabel m = new JLabel(metric.toUpperCase(Locale.ROOT)); + m.setFont(FoodSenseTheme.getFont(Font.BOLD, 9f)); + m.setForeground(FoodSenseTheme.getTextMuted()); + pill.add(m); + + JLabel s = new JLabel(status); + s.setFont(FoodSenseTheme.getFont(Font.BOLD, 11f)); + s.setForeground(statusColor); + pill.add(s); + + return pill; + } + + private JPanel buildNutrientTable(Nutriments n) { + JPanel card = new JPanel() { + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setColor(FoodSenseTheme.getCardBackground()); + g2.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 12, 12)); + g2.setColor(FoodSenseTheme.getCardBorder()); + g2.setStroke(new BasicStroke(1f)); + g2.draw(new RoundRectangle2D.Float(0, 0, getWidth() - 1, getHeight() - 1, 12, 12)); + g2.dispose(); + } + }; + card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS)); + card.setOpaque(false); + card.setAlignmentX(Component.LEFT_ALIGNMENT); + card.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE)); + + // Format values with proper rounding and units + String carbVal = formatRounded(n.getCarbohydrates()); + String sugarVal = formatRounded(n.getSugars()); + String fatVal = formatRounded(n.getFat()); + String satFatVal = formatRounded(n.getSaturated_fat()); + String proteinVal = formatRounded(n.getProteins()); + String saltVal = formatRounded(n.getSalt()); + String sodiumVal = formatSodium(n.getSodium()); + + Object[][] rows = { + { "Total Carbohydrates", carbVal, "g", false }, + { "↳ of which Sugars", sugarVal, "g", true }, + { "Total Fat", fatVal, "g", false }, + { "↳ of which Saturates", satFatVal, "g", true }, + { "Proteins", proteinVal, "g", false }, + { "Salt", saltVal, "g", false }, + { "Sodium", sodiumVal, "mg", false }, + }; + + boolean first = true; + for (Object[] r : rows) { + if (!first) { + JSeparator sep = new JSeparator(); + sep.setForeground(FoodSenseTheme.getCardBorder()); + sep.setMaximumSize(new Dimension(Integer.MAX_VALUE, 1)); + card.add(sep); + } + card.add(mkRow((String) r[0], (String) r[1], (String) r[2], (boolean) r[3])); + first = false; + } + return card; + } + + private JPanel mkRow(String name, String value, String unit, boolean sub) { + JPanel row = new JPanel(new BorderLayout()); + row.setOpaque(false); + row.setBorder(BorderFactory.createEmptyBorder(9, sub ? 24 : 16, 9, 16)); + + JLabel left = new JLabel(name); + left.setFont(FoodSenseTheme.getFont(sub ? Font.ITALIC : Font.BOLD, sub ? 12f : 13f)); + left.setForeground(sub ? FoodSenseTheme.getTextMuted() : FoodSenseTheme.getTextPrimary()); + + String v = (value != null && !value.isBlank()) ? value : "—"; + String displayRight = v.equals("—") ? "—" : v + " " + unit; + JLabel right = new JLabel(displayRight); + right.putClientProperty("html.disable", Boolean.TRUE); + right.setFont(FoodSenseTheme.getFont(Font.BOLD, 13f)); + right.setForeground(sub ? FoodSenseTheme.getTextMuted() : FoodSenseTheme.getTextSecondary()); + + row.add(left, BorderLayout.WEST); + row.add(right, BorderLayout.EAST); + return row; + } + + private static double parseDouble(String str) { + if (str == null) { + return 0.0; + } + try { + return Double.parseDouble(str.trim()); + } catch (NumberFormatException e) { + return 0.0; + } + } + + private static String fmt(double d) { + return String.format(Locale.US, "%.1f", d); + } + + private static String formatRounded(String raw) { + if (raw == null || raw.isBlank()) { + return null; + } + try { + double d = Double.parseDouble(raw.trim()); + return String.format(Locale.US, "%.1f", d); + } catch (NumberFormatException e) { + return raw; + } + } + + private static double parseSodiumMg(String raw) { + if (raw == null || raw.isBlank()) { + return 0.0; + } + try { + double d = Double.parseDouble(raw.trim()); + return d * 1000.0; + } catch (NumberFormatException e) { + return 0.0; + } + } + + private static String formatSodium(String raw) { + if (raw == null || raw.isBlank()) { + return null; + } + try { + double d = Double.parseDouble(raw.trim()); + // Open Food Facts API spec: sodium is stored in grams; convert to milligrams + return String.format(Locale.US, "%.1f", d * 1000.0); + } catch (NumberFormatException e) { + return raw; + } + } +} diff --git a/src/main/java/com/foodsense/ui/WrapLayout.java b/src/main/java/com/foodsense/ui/WrapLayout.java new file mode 100644 index 0000000..532d304 --- /dev/null +++ b/src/main/java/com/foodsense/ui/WrapLayout.java @@ -0,0 +1,93 @@ +/* + * FlowLayout subclass that recalculates layout size based on container width. + * Prevents horizontal clipping inside scrollpanes and responsive card containers. + */ + +package com.foodsense.ui; + +import java.awt.*; + +/** + * A FlowLayout subclass that lays out components in lines and wraps to the next line + * when the available width is exceeded, dynamically calculating height. + */ +public class WrapLayout extends FlowLayout { + + public WrapLayout() { + super(); + } + + public WrapLayout(int align) { + super(align); + } + + public WrapLayout(int align, int hgap, int vgap) { + super(align, hgap, vgap); + } + + @Override + public Dimension preferredLayoutSize(Container target) { + return layoutSize(target, true); + } + + @Override + public Dimension minimumLayoutSize(Container target) { + Dimension minimum = layoutSize(target, false); + minimum.width -= (getHgap() + 1); + return minimum; + } + + private Dimension layoutSize(Container target, boolean preferred) { + synchronized (target.getTreeLock()) { + int targetWidth = target.getSize().width; + Container container = target; + + while (container.getSize().width == 0 && container.getParent() != null) { + container = container.getParent(); + } + if (targetWidth == 0) { + targetWidth = container.getSize().width; + } + if (targetWidth == 0) { + targetWidth = Integer.MAX_VALUE; + } + + int hgap = getHgap(); + int vgap = getVgap(); + Insets insets = target.getInsets(); + int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); + int maxWidth = targetWidth - horizontalInsetsAndGap; + + Dimension dim = new Dimension(0, 0); + int rowWidth = 0; + int rowHeight = 0; + int nmembers = target.getComponentCount(); + + for (int i = 0; i < nmembers; i++) { + Component m = target.getComponent(i); + if (m.isVisible()) { + Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); + if (rowWidth + d.width > maxWidth && rowWidth > 0) { + dim.width = Math.max(dim.width, rowWidth); + dim.height += rowHeight + vgap; + rowWidth = 0; + rowHeight = 0; + } + if (rowWidth != 0) { + rowWidth += hgap; + } + rowWidth += d.width; + rowHeight = Math.max(rowHeight, d.height); + } + } + + dim.width = Math.max(dim.width, rowWidth); + dim.height += rowHeight; + + dim.width += horizontalInsetsAndGap; + dim.height += insets.top + insets.bottom + (vgap * 2); + + return dim; + } + } +} diff --git a/src/test/java/com/foodsense/FoodSenseThemeTest.java b/src/test/java/com/foodsense/FoodSenseThemeTest.java new file mode 100644 index 0000000..b3f0823 --- /dev/null +++ b/src/test/java/com/foodsense/FoodSenseThemeTest.java @@ -0,0 +1,49 @@ +/* + * Unit tests for FoodSenseTheme tokens and mode toggling. + */ + +package com.foodsense; + +import com.foodsense.ui.FoodSenseTheme; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.awt.*; + +import static org.junit.jupiter.api.Assertions.*; + +class FoodSenseThemeTest { + + @AfterEach + void resetTheme() { + FoodSenseTheme.setDarkMode(false, null); + } + + @Test + void toggleTheme_switchesModeAndPalette() { + assertFalse(FoodSenseTheme.isDarkMode()); + Color lightBg = FoodSenseTheme.getBackground(); + + FoodSenseTheme.toggleTheme(null); + assertTrue(FoodSenseTheme.isDarkMode()); + Color darkBg = FoodSenseTheme.getBackground(); + + assertNotEquals(lightBg, darkBg); + + FoodSenseTheme.toggleTheme(null); + assertFalse(FoodSenseTheme.isDarkMode()); + assertEquals(lightBg, FoodSenseTheme.getBackground()); + } + + @Test + void getNutriscoreColor_mapsOfficialGrades() { + assertEquals(FoodSenseTheme.SCORE_A, FoodSenseTheme.getNutriscoreColor("a")); + assertEquals(FoodSenseTheme.SCORE_A, FoodSenseTheme.getNutriscoreColor("A")); + assertEquals(FoodSenseTheme.SCORE_B, FoodSenseTheme.getNutriscoreColor("B")); + assertEquals(FoodSenseTheme.SCORE_C, FoodSenseTheme.getNutriscoreColor("C")); + assertEquals(FoodSenseTheme.SCORE_D, FoodSenseTheme.getNutriscoreColor("D")); + assertEquals(FoodSenseTheme.SCORE_E, FoodSenseTheme.getNutriscoreColor("E")); + assertEquals(FoodSenseTheme.getTextMuted(), FoodSenseTheme.getNutriscoreColor(null)); + assertEquals(FoodSenseTheme.getTextMuted(), FoodSenseTheme.getNutriscoreColor("Z")); + } +} diff --git a/src/test/java/com/foodsense/IngredientsPanelTest.java b/src/test/java/com/foodsense/IngredientsPanelTest.java new file mode 100644 index 0000000..e4c063a --- /dev/null +++ b/src/test/java/com/foodsense/IngredientsPanelTest.java @@ -0,0 +1,75 @@ +/* + * Unit tests for IngredientsPanel and ingredient parsing contracts. + */ + +package com.foodsense; + +import com.foodsense.ui.IngredientsPanel; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +@DisplayName("IngredientsPanel and Parsing Tests") +class IngredientsPanelTest { + + @Test + @DisplayName("Should return empty list for null or blank input") + void testEmptyAndNull() { + assertTrue(IngredientsPanel.parseIngredients(null).isEmpty()); + assertTrue(IngredientsPanel.parseIngredients("").isEmpty()); + assertTrue(IngredientsPanel.parseIngredients(" \n\t ").isEmpty()); + } + + @Test + @DisplayName("Should parse comma-separated ingredients into discrete tokens") + void testBasicCommaSeparation() { + String raw = "Carbonated Water, High Fructose Corn Syrup, Caramel Color, Phosphoric Acid, Natural Flavors, Caffeine."; + List items = IngredientsPanel.parseIngredients(raw); + + assertEquals(6, items.size()); + assertEquals("Carbonated Water", items.get(0)); + assertEquals("High Fructose Corn Syrup", items.get(1)); + assertEquals("Caramel Color", items.get(2)); + assertEquals("Phosphoric Acid", items.get(3)); + assertEquals("Natural Flavors", items.get(4)); + assertEquals("Caffeine", items.get(5)); + } + + @Test + @DisplayName("Should preserve sub-ingredients inside parentheses and brackets") + void testParenthesesAndBracketsPreservation() { + String raw = "Enriched Flour (Wheat Flour, Niacin, Reduced Iron, Thiamin Mononitrate), Vegetable Oil [Palm, Canola], Salt."; + List items = IngredientsPanel.parseIngredients(raw); + + assertEquals(3, items.size()); + assertEquals("Enriched Flour (Wheat Flour, Niacin, Reduced Iron, Thiamin Mononitrate)", items.get(0)); + assertEquals("Vegetable Oil [Palm, Canola]", items.get(1)); + assertEquals("Salt", items.get(2)); + } + + @Test + @DisplayName("Should split on semicolons and bullets as well") + void testOtherDelimiters() { + String raw = "Sugar; Cocoa Butter • Milk Powder; Emulsifier (Soy Lecithin)"; + List items = IngredientsPanel.parseIngredients(raw); + + assertEquals(4, items.size()); + assertEquals("Sugar", items.get(0)); + assertEquals("Cocoa Butter", items.get(1)); + assertEquals("Milk Powder", items.get(2)); + assertEquals("Emulsifier (Soy Lecithin)", items.get(3)); + } + + @Test + @DisplayName("Should instantiate IngredientsPanel safely with null and populated inputs") + void testPanelInstantiation() { + IngredientsPanel emptyPanel = new IngredientsPanel(null, null); + assertNotNull(emptyPanel); + + IngredientsPanel fullPanel = new IngredientsPanel("Water, Sugar, Salt", "milk, sugar"); + assertNotNull(fullPanel); + } +} diff --git a/src/test/java/com/foodsense/JsonDeserializationTest.java b/src/test/java/com/foodsense/JsonDeserializationTest.java index c8677aa..2167718 100644 --- a/src/test/java/com/foodsense/JsonDeserializationTest.java +++ b/src/test/java/com/foodsense/JsonDeserializationTest.java @@ -26,6 +26,8 @@ void setUp() { void testNutrimentsDeserialization() { String json = "{" + "\"energy\": \"2000\"," + + "\"energy-kcal\": \"478\"," + + "\"energy-kj\": \"2000\"," + "\"sugars\": \"50\"," + "\"fat\": \"65\"," + "\"saturated-fat\": \"20\"," + @@ -38,6 +40,8 @@ void testNutrimentsDeserialization() { Nutriments nutriments = gson.fromJson(json, Nutriments.class); assertNotNull(nutriments); assertEquals("2000", nutriments.getEnergy()); + assertEquals("478", nutriments.getEnergyKcal()); + assertEquals("2000", nutriments.getEnergyKj()); assertEquals("50", nutriments.getSugars()); assertEquals("65", nutriments.getFat()); assertEquals("20", nutriments.getSaturated_fat()); diff --git a/src/test/java/com/foodsense/NutriScoreSpectrumViewTest.java b/src/test/java/com/foodsense/NutriScoreSpectrumViewTest.java new file mode 100644 index 0000000..c10da1f --- /dev/null +++ b/src/test/java/com/foodsense/NutriScoreSpectrumViewTest.java @@ -0,0 +1,56 @@ +/* + * Unit tests for NutriScoreSpectrumView. + * Tests grade normalization, null handling, and active grade inspection. + */ + +package com.foodsense; + +import com.foodsense.ui.NutriScoreSpectrumView; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; + +class NutriScoreSpectrumViewTest { + + @ParameterizedTest + @ValueSource(strings = {"a", "A", "b", "B", "c", "C", "d", "D", "e", "E"}) + void setGrade_normalizesValidGrades(String grade) { + NutriScoreSpectrumView view = new NutriScoreSpectrumView(grade); + assertEquals(grade.toUpperCase(), view.getGrade()); + } + + @Test + void setGrade_handlesNullAndBlank() { + NutriScoreSpectrumView view = new NutriScoreSpectrumView("A"); + assertEquals("A", view.getGrade()); + + view.setGrade(null); + assertNull(view.getGrade()); + + view.setGrade(" "); + assertNull(view.getGrade()); + } + + @ParameterizedTest + @ValueSource(strings = {"unknown", "Z", "123", "F", "not-a-grade", "a b"}) + void setGrade_treatsInvalidGradesAsUnavailable(String invalidGrade) { + NutriScoreSpectrumView view = new NutriScoreSpectrumView("A"); + assertEquals("A", view.getGrade()); + + view.setGrade(invalidGrade); + assertNull(view.getGrade()); + assertEquals("Nutri-Score not available", view.getToolTipText()); + } + + @Test + void setGrade_setsDescriptiveToolTip() { + NutriScoreSpectrumView view = new NutriScoreSpectrumView(); + view.setGrade("b"); + assertEquals("Nutri-Score: Grade B", view.getToolTipText()); + + view.setGrade(null); + assertEquals("Nutri-Score not available", view.getToolTipText()); + } +} diff --git a/src/test/java/com/foodsense/NutrimentsTest.java b/src/test/java/com/foodsense/NutrimentsTest.java index ccbd316..116527a 100644 --- a/src/test/java/com/foodsense/NutrimentsTest.java +++ b/src/test/java/com/foodsense/NutrimentsTest.java @@ -26,6 +26,15 @@ void testEnergyStorage() { assertEquals("2000", nutriments.getEnergy()); } + @Test + @DisplayName("Should set and get explicit energy in kcal and kJ") + void testExplicitEnergyStorage() { + nutriments.setEnergyKcal("140"); + nutriments.setEnergyKj("586"); + assertEquals("140", nutriments.getEnergyKcal()); + assertEquals("586", nutriments.getEnergyKj()); + } + @Test @DisplayName("Should set and get sugars") void testSugarsStorage() { diff --git a/src/test/java/com/foodsense/NutritionLabelPanelTest.java b/src/test/java/com/foodsense/NutritionLabelPanelTest.java new file mode 100644 index 0000000..4190b96 --- /dev/null +++ b/src/test/java/com/foodsense/NutritionLabelPanelTest.java @@ -0,0 +1,63 @@ +/* + * Unit tests for NutritionLabelPanel. + * Tests hero calorie resolution, null-aware macro formatting, and benchmark rendering. + */ + +package com.foodsense; + +import com.foodsense.ui.NutritionLabelPanel; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@DisplayName("NutritionLabelPanel Tests") +class NutritionLabelPanelTest { + + @Test + @DisplayName("Should instantiate panel with null nutriments safely") + void testNullNutriments() { + NutritionLabelPanel panel = new NutritionLabelPanel(null); + assertNotNull(panel); + } + + @Test + @DisplayName("Should instantiate panel with explicit kcal and kj nutriments") + void testExplicitKcalAndKj() { + Nutriments n = new Nutriments(); + n.setEnergyKcal("140"); + n.setEnergyKj("586"); + n.setCarbohydrates("36"); + n.setSugars("35"); + n.setFat("0"); + n.setSaturated_fat("0"); + n.setProteins("0"); + n.setSodium("0.015"); + + NutritionLabelPanel panel = new NutritionLabelPanel(n); + assertNotNull(panel); + } + + @Test + @DisplayName("Should instantiate panel with only fallback energy field in kJ") + void testFallbackEnergy() { + Nutriments n = new Nutriments(); + n.setEnergy("2000"); // Open Food Facts standard kJ + n.setCarbohydrates("50"); + n.setFat("20"); + n.setProteins("10"); + + NutritionLabelPanel panel = new NutritionLabelPanel(n); + assertNotNull(panel); + } + + @Test + @DisplayName("Should handle missing optional macros gracefully without crashing") + void testMissingMacros() { + Nutriments n = new Nutriments(); + n.setEnergy("100"); + + NutritionLabelPanel panel = new NutritionLabelPanel(n); + assertNotNull(panel); + } +} diff --git a/src/test/java/com/foodsense/ProductApiClientTest.java b/src/test/java/com/foodsense/ProductApiClientTest.java index 35ea8cf..f3e1659 100644 --- a/src/test/java/com/foodsense/ProductApiClientTest.java +++ b/src/test/java/com/foodsense/ProductApiClientTest.java @@ -136,6 +136,16 @@ void testFetchProductNullOrBlankBarcode() { assertNull(client.fetchProduct(" ")); } + @Test + void testFetchProductRejectsMaliciousBarcodes() { + ProductApiClient client = new ProductApiClient("world.openfoodfacts.org", req -> + new SimpleHttpResponse(200, "{\"status\": 1, \"product\": {}}")); + + assertNull(client.fetchProduct("../traversal")); + assertNull(client.fetchProduct("code with spaces")); + assertNull(client.fetchProduct("code?with=query")); + } + /** Helper stub for HttpResponse without bytecode instrumentation. */ private record SimpleHttpResponse(int statusCode, String body) implements HttpResponse { @Override diff --git a/src/test/java/com/foodsense/SafeImageLoaderTest.java b/src/test/java/com/foodsense/SafeImageLoaderTest.java new file mode 100644 index 0000000..81dec42 --- /dev/null +++ b/src/test/java/com/foodsense/SafeImageLoaderTest.java @@ -0,0 +1,50 @@ +/* + * Unit tests for SafeImageLoader. + * Verifies non-HTTPS URL rejection, null safety, and callback dispatching. + */ + +package com.foodsense; + +import com.foodsense.security.SafeImageLoader; +import org.junit.jupiter.api.Test; + +import javax.swing.SwingUtilities; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.jupiter.api.Assertions.*; + +class SafeImageLoaderTest { + + @Test + void loadImageAsync_rejectsInvalidUrlAndCallsBackOnEdt() throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + AtomicBoolean calledOnEdt = new AtomicBoolean(false); + AtomicBoolean receivedNull = new AtomicBoolean(false); + + SafeImageLoader.loadImageAsync("http://insecure.example.com/test.jpg", 100, 100, icon -> { + calledOnEdt.set(SwingUtilities.isEventDispatchThread()); + receivedNull.set(icon == null); + latch.countDown(); + }); + + assertTrue(latch.await(2, TimeUnit.SECONDS), "Callback should complete promptly"); + assertTrue(calledOnEdt.get(), "Callback must run on the Swing EDT"); + assertTrue(receivedNull.get(), "Icon must be null for insecure URL"); + } + + @Test + void loadImageAsync_handlesNullUrl() throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + AtomicBoolean receivedNull = new AtomicBoolean(false); + + SafeImageLoader.loadImageAsync(null, 100, 100, icon -> { + receivedNull.set(icon == null); + latch.countDown(); + }); + + assertTrue(latch.await(2, TimeUnit.SECONDS)); + assertTrue(receivedNull.get()); + } +} diff --git a/src/test/java/com/foodsense/SecurityValidatorTest.java b/src/test/java/com/foodsense/SecurityValidatorTest.java new file mode 100644 index 0000000..6aee3ff --- /dev/null +++ b/src/test/java/com/foodsense/SecurityValidatorTest.java @@ -0,0 +1,87 @@ +/* + * Unit tests for SecurityValidator. + * Tests barcode allowlist matching, Swing HTML escaping, and safe HTTPS URL validation. + */ + +package com.foodsense; + +import com.foodsense.security.SecurityValidator; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; + +class SecurityValidatorTest { + + @ParameterizedTest + @ValueSource(strings = { + "0049000006346", + "737628064502", + "123456", + "ABC-123_456", + "3017620422003" + }) + void isValidBarcode_permitsValidBarcodes(String barcode) { + assertTrue(SecurityValidator.isValidBarcode(barcode)); + } + + @ParameterizedTest + @ValueSource(strings = { + "", + " ", + "12", // Too short (< 3) + "123/../../etc/passwd", // Path traversal + "123 456", // Space + "123?query=1", // Query delimiter + "123#fragment", // Fragment + "123