From 368136215cf510bb03e0bac63e62784731bb343c Mon Sep 17 00:00:00 2001 From: Samuel Date: Mon, 9 Nov 2026 22:00:17 -0500 Subject: [PATCH 1/3] feat: modernize UI with adaptive theme and harden security defenses - Add FlatLaf Look and Feel with runtime Light and Dark mode icon toggle - Replace external OpenCV canvas with in-app modal CameraScanDialog (viewfinder reticles & scanline guide) - Implement 5-pill Nutri-Score spectrum view (A-E) with elevated active grade - Add NutritionLabelPanel with hero calorie callout and macro visualizer bar - Add AllergenBanner danger alert card - Harden barcode validation with strict allowlist (SecurityValidator) - Protect Swing labels against HTML injection attacks - Add SafeImageLoader with bounded 5MB payload caps and redirect defense - Update release workflow with SHA-256 checksums and build provenance attestation - Expand test suite to 78 unit tests (100% green) Co-authored-by: Codex --- .github/workflows/release.yml | 36 +- README.md | 80 +- pom.xml | 9 +- src/main/java/com/foodsense/FoodSense.java | 7 +- src/main/java/com/foodsense/FoodSenseGUI.java | 732 +++++++----------- .../java/com/foodsense/ProductApiClient.java | 10 +- .../java/com/foodsense/VideoProcessor.java | 228 +++--- .../foodsense/security/SafeImageLoader.java | 106 +++ .../foodsense/security/SecurityValidator.java | 123 +++ .../java/com/foodsense/ui/AllergenBanner.java | 76 ++ .../com/foodsense/ui/CameraScanDialog.java | 220 ++++++ .../java/com/foodsense/ui/FoodSenseTheme.java | 189 +++++ .../foodsense/ui/NutriScoreSpectrumView.java | 146 ++++ .../com/foodsense/ui/NutritionLabelPanel.java | 242 ++++++ .../com/foodsense/FoodSenseThemeTest.java | 49 ++ .../foodsense/NutriScoreSpectrumViewTest.java | 45 ++ .../com/foodsense/ProductApiClientTest.java | 10 + .../com/foodsense/SafeImageLoaderTest.java | 50 ++ .../com/foodsense/SecurityValidatorTest.java | 80 ++ 19 files changed, 1862 insertions(+), 576 deletions(-) create mode 100644 src/main/java/com/foodsense/security/SafeImageLoader.java create mode 100644 src/main/java/com/foodsense/security/SecurityValidator.java create mode 100644 src/main/java/com/foodsense/ui/AllergenBanner.java create mode 100644 src/main/java/com/foodsense/ui/CameraScanDialog.java create mode 100644 src/main/java/com/foodsense/ui/FoodSenseTheme.java create mode 100644 src/main/java/com/foodsense/ui/NutriScoreSpectrumView.java create mode 100644 src/main/java/com/foodsense/ui/NutritionLabelPanel.java create mode 100644 src/test/java/com/foodsense/FoodSenseThemeTest.java create mode 100644 src/test/java/com/foodsense/NutriScoreSpectrumViewTest.java create mode 100644 src/test/java/com/foodsense/SafeImageLoaderTest.java create mode 100644 src/test/java/com/foodsense/SecurityValidatorTest.java diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cb6b261..16dee84 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@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..0ce75e5 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 native binaries 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,23 @@ 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 +``` + +**Windows (PowerShell):** +```powershell +Get-FileHash .\FoodSense-Windows-X64.jar -Algorithm 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 +55,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 +78,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 alphanumeric characters. Special characters and spaces are rejected. +- **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..23344e6 100644 --- a/src/main/java/com/foodsense/FoodSenseGUI.java +++ b/src/main/java/com/foodsense/FoodSenseGUI.java @@ -2,49 +2,49 @@ * 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}). */ 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.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 modern 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; private JTextField searchField; - private JButton searchBtn; - private JButton cameraBtn; + private JButton searchBtn; + private JButton cameraBtn; + private JButton themeToggleBtn; + private JLabel bannerLabel; + + private Product currentProduct = null; + private int imageRequestId = 0; - // Sidebar product widgets (shown after a successful search) + // Sidebar product preview widgets + private JPanel productCard; private JLabel imgLabel; private JLabel nameLabel; private JLabel brandLabel; - private JPanel scorePanel; + private NutriScoreSpectrumView nutriScoreView; /** * Constructs the main frame and widget tree with a default API client. @@ -61,12 +61,12 @@ public FoodSenseGUI() { */ 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). + * Makes the main frame visible. Must be called after construction on the EDT. * * @example *
{@code
@@ -77,18 +77,27 @@ 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.setBackground(FoodSenseTheme.getBackground());
+
         root.add(buildSidebar(), BorderLayout.WEST);
 
         contentArea = buildEmptyState();
@@ -99,544 +108,383 @@ private void build() {
 
     // ── Sidebar ───────────────────────────────────────────────
 
-    /**
-     * 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));
+        sidebar.setBackground(FoodSenseTheme.getSidebarBackground());
+        sidebar.setPreferredSize(new Dimension(300, 0));
+        sidebar.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, FoodSenseTheme.getCardBorder()));
 
-        // Top: logo + search controls
+        // Top Section: Header, Theme Toggle, Search Input & Buttons
         JPanel top = new JPanel();
         top.setLayout(new BoxLayout(top, BoxLayout.Y_AXIS));
-        top.setBackground(SIDEBAR_BG);
-        top.setBorder(BorderFactory.createEmptyBorder(28, 20, 20, 20));
+        top.setOpaque(false);
+        top.setBorder(BorderFactory.createEmptyBorder(24, 20, 20, 20));
+
+        // Header row with logo and 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);
 
         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));
+        logo.setFont(FoodSenseTheme.getFont(Font.BOLD, 20f));
+        logo.setForeground(FoodSenseTheme.getPrimaryAccent());
+        titleBlock.add(logo);
+
+        JLabel tagline = new JLabel("Nutrition Intelligence");
+        tagline.setFont(FoodSenseTheme.getFont(Font.PLAIN, 11f));
+        tagline.setForeground(FoodSenseTheme.getTextMuted());
+        titleBlock.add(tagline);
+
+        headerRow.add(titleBlock, BorderLayout.WEST);
+
+        // Icon-only Theme Toggle button
+        themeToggleBtn = new JButton(FoodSenseTheme.isDarkMode() ? "☀" : "☾");
+        themeToggleBtn.setFont(FoodSenseTheme.getFont(Font.BOLD, 14f));
+        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_20));
+
+        // Barcode label
+        JLabel barcodeLabel = new JLabel("PRODUCT BARCODE");
+        barcodeLabel.setFont(FoodSenseTheme.getFont(Font.BOLD, 10f));
+        barcodeLabel.setForeground(FoodSenseTheme.getTextMuted());
         barcodeLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
         top.add(barcodeLabel);
-        top.add(Box.createVerticalStrut(7));
+        top.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_8));
 
+        // Search 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, 13f));
+        searchField.putClientProperty("JTextField.placeholderText", "Enter barcode (e.g. 0049000006346)");
+        searchField.setMaximumSize(new Dimension(Integer.MAX_VALUE, 38));
         searchField.setAlignmentX(Component.LEFT_ALIGNMENT);
+        searchField.addActionListener(e -> searchProduct());
+        searchField.addKeyListener(new KeyAdapter() {
+            @Override
+            public void keyTyped(KeyEvent e) {
+                clearBanner();
+            }
+        });
         top.add(searchField);
-        top.add(Box.createVerticalStrut(10));
+        top.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_8));
 
+        // Action Buttons Row (Search & Scan)
         JPanel btnRow = new JPanel(new GridLayout(1, 2, 8, 0));
         btnRow.setOpaque(false);
-        btnRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, 38));
+        btnRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, 36));
         btnRow.setAlignmentX(Component.LEFT_ALIGNMENT);
-        searchBtn = mkBtn("Search", true);
-        cameraBtn = mkBtn("Scan", false);
+
+        searchBtn = new JButton("Search");
+        searchBtn.setFont(FoodSenseTheme.getFont(Font.BOLD, 12f));
+        searchBtn.setFocusPainted(false);
+        searchBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
+        searchBtn.addActionListener(e -> searchProduct());
+
+        cameraBtn = new JButton("Scan with Camera");
+        cameraBtn.setFont(FoodSenseTheme.getFont(Font.BOLD, 12f));
+        cameraBtn.setFocusPainted(false);
+        cameraBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
+        cameraBtn.addActionListener(e -> openCameraModal());
+
         btnRow.add(searchBtn);
         btnRow.add(cameraBtn);
         top.add(btnRow);
 
+        // Status banner
+        top.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_8));
+        bannerLabel = new JLabel("");
+        bannerLabel.setFont(FoodSenseTheme.getFont(Font.PLAIN, 12f));
+        bannerLabel.setForeground(FoodSenseTheme.getDanger());
+        bannerLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
+        bannerLabel.setVisible(false);
+        top.add(bannerLabel);
+
         sidebar.add(top, BorderLayout.NORTH);
         sidebar.add(buildSidebarProductCard(), BorderLayout.CENTER);
 
-        searchField.addActionListener(e -> searchProduct());
-        searchBtn.addActionListener(e -> searchProduct());
-        cameraBtn.addActionListener(e -> startBarcodeScanner());
-
         return sidebar;
     }
 
-    /**
-     * 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));
+        productCard = new JPanel();
+        productCard.setLayout(new BoxLayout(productCard, BoxLayout.Y_AXIS));
+        productCard.setOpaque(false);
+        productCard.setBorder(BorderFactory.createEmptyBorder(16, 20, 20, 20));
 
-        card.add(mkSeparator());
-        card.add(Box.createVerticalStrut(20));
+        JSeparator sep = new JSeparator();
+        sep.setMaximumSize(new Dimension(Integer.MAX_VALUE, 1));
+        productCard.add(sep);
+        productCard.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_16));
 
+        // Product image container with smooth placeholder
         imgLabel = new JLabel();
         imgLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
         imgLabel.setHorizontalAlignment(JLabel.CENTER);
+        imgLabel.setPreferredSize(new Dimension(180, 180));
+        imgLabel.setMaximumSize(new Dimension(180, 180));
         imgLabel.setVisible(false);
-        card.add(imgLabel);
-        card.add(Box.createVerticalStrut(14));
+        productCard.add(imgLabel);
+        productCard.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_12));
 
         nameLabel = new JLabel();
-        nameLabel.setFont(new Font(F, Font.BOLD, 13));
-        nameLabel.setForeground(Color.WHITE);
+        nameLabel.setFont(FoodSenseTheme.getFont(Font.BOLD, 14f));
+        nameLabel.setForeground(FoodSenseTheme.getTextPrimary());
         nameLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
         nameLabel.setVisible(false);
-        card.add(nameLabel);
-        card.add(Box.createVerticalStrut(4));
+        productCard.add(nameLabel);
+        productCard.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_4));
 
         brandLabel = new JLabel();
-        brandLabel.setFont(new Font(F, Font.PLAIN, 12));
-        brandLabel.setForeground(new Color(110, 160, 110));
+        brandLabel.setFont(FoodSenseTheme.getFont(Font.PLAIN, 12f));
+        brandLabel.setForeground(FoodSenseTheme.getTextMuted());
         brandLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
         brandLabel.setVisible(false);
-        card.add(brandLabel);
-        card.add(Box.createVerticalStrut(10));
+        productCard.add(brandLabel);
+        productCard.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_16));
 
-        scorePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 0));
-        scorePanel.setOpaque(false);
-        scorePanel.setAlignmentX(Component.LEFT_ALIGNMENT);
-        scorePanel.setVisible(false);
-        card.add(scorePanel);
+        nutriScoreView = new NutriScoreSpectrumView();
+        nutriScoreView.setAlignmentX(Component.LEFT_ALIGNMENT);
+        nutriScoreView.setVisible(false);
+        productCard.add(nutriScoreView);
 
-        return card;
+        return productCard;
     }
 
-    /**
-     * @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;
-    }
-
-    /** @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;
-    }
-
-    // ── Sidebar product update ────────────────────────────────
-
-    /**
-     * 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
-     */
-    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);
-        }
-
-        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()); + if (currentProduct != null) { + updateSidebar(currentProduct); + 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, 56f)); + 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("No Product Loaded"); + title.setFont(FoodSenseTheme.getFont(Font.BOLD, 20f)); + 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 with your webcam to inspect nutrition facts."); + hint.setFont(FoodSenseTheme.getFont(Font.PLAIN, 13f)); + hint.setForeground(FoodSenseTheme.getTextMuted()); hint.setAlignmentX(Component.CENTER_ALIGNMENT); inner.add(icon); - inner.add(Box.createVerticalStrut(14)); + inner.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_12)); inner.add(title); - inner.add(Box.createVerticalStrut(8)); + inner.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_8)); 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 - */ 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)); + sections.setBackground(FoodSenseTheme.getBackground()); + sections.setBorder(BorderFactory.createEmptyBorder(30, 36, 30, 36)); + + // 1. Structured Nutrition Card + sections.add(new NutritionLabelPanel(p.getNutriments())); + sections.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_24)); - sections.add(buildNutritionSection(p.getNutriments())); - sections.add(Box.createVerticalStrut(24)); + // 2. Ingredients Section sections.add(buildIngredientsSection(p)); + // 3. Allergens Section (if present) if (p.getAllergens_from_ingredients() != null && !p.getAllergens_from_ingredients().isBlank()) { - sections.add(Box.createVerticalStrut(24)); - sections.add(buildAllergensSection(p)); + sections.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_24)); + sections.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.setBackground(FoodSenseTheme.getBackground()); wrapper.add(sections, BorderLayout.NORTH); JScrollPane scroll = new JScrollPane(wrapper); scroll.setBorder(null); 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 }, - }; - - 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; - } - 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)); + JLabel title = new JLabel("Ingredients"); + title.setFont(FoodSenseTheme.getFont(Font.BOLD, 18f)); + title.setForeground(FoodSenseTheme.getTextPrimary()); + section.add(title); + section.add(Box.createVerticalStrut(FoodSenseTheme.SPACE_12)); String text = (p.getIngredients_text() != null && !p.getIngredients_text().isBlank()) ? p.getIngredients_text() - : "No ingredients information available."; + : "No ingredients information available for this product."; + + JPanel card = 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(); + } + }; + card.setOpaque(false); + card.setBorder(BorderFactory.createEmptyBorder(16, 20, 16, 20)); + card.setAlignmentX(Component.LEFT_ALIGNMENT); JTextArea area = new JTextArea(text); - area.setFont(new Font(F, Font.PLAIN, 13)); - area.setForeground(TEXT); - area.setBackground(CARD); + area.setFont(FoodSenseTheme.getFont(Font.PLAIN, 13f)); + area.setForeground(FoodSenseTheme.getTextPrimary()); + area.setOpaque(false); 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); + card.add(area, BorderLayout.CENTER); - 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); + section.add(card); return section; } - // ── Shared helpers ──────────────────────────────────────── + // ── Logic & Handlers ────────────────────────────────────── - /** - * @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); + private void searchProduct() { + if (!searchBtn.isEnabled()) { + 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 ───────────────────────────────────────────────── + clearBanner(); + String rawBarcode = searchField.getText(); - /** - * 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(); - } + if (rawBarcode == null || rawBarcode.trim().isEmpty()) { + showBanner("Please enter a barcode number."); + return; + } - /** - * 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 format. Use numbers or alphanumeric codes (3-48 chars)."); return; } searchBtn.setEnabled(false); cameraBtn.setEnabled(false); - searchBtn.setText("..."); + searchBtn.setText("Fetching..."); new Thread(() -> { Product product = apiClient.fetchProduct(barcode); SwingUtilities.invokeLater(() -> { if (product != null) { + this.currentProduct = product; updateSidebar(product); swapContent(buildProductView(product)); } else { - JOptionPane.showMessageDialog(frame, - "Product not found. Check the barcode and try again.", - "Not Found", JOptionPane.WARNING_MESSAGE); + showBanner("Product not found. Verify the code and try again."); } searchBtn.setEnabled(true); cameraBtn.setEnabled(true); searchBtn.setText("Search"); }); - }).start(); + }, "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; + + // Load image asynchronously to prevent EDT freezing + imgLabel.setIcon(null); + imgLabel.setText("Loading image..."); + imgLabel.setForeground(FoodSenseTheme.getTextMuted()); + imgLabel.setVisible(true); + + String imgUrl = p.getImage_front_url(); + if (imgUrl != null && !imgUrl.isBlank()) { + SafeImageLoader.loadImageAsync(imgUrl, 180, 180, icon -> { + if (currentReq != imageRequestId) { + return; + } + if (icon != null) { + imgLabel.setIcon(icon); + imgLabel.setText(null); + } else { + imgLabel.setIcon(null); + imgLabel.setText("No image preview"); + } + }); + } else { + imgLabel.setIcon(null); + imgLabel.setText("No image preview"); + } + + String safeName = SecurityValidator.escapeHtml(p.getProduct_name() != null ? p.getProduct_name() : "Unknown product"); + nameLabel.setText("" + safeName + ""); + + brandLabel.putClientProperty("html.disable", Boolean.TRUE); + brandLabel.setText(p.getBrands() != null ? p.getBrands() : ""); + + nutriScoreView.setGrade(p.getNutriscore_grade()); + + nameLabel.setVisible(true); + brandLabel.setVisible(true); + 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 +492,14 @@ private void swapContent(JPanel next) { root.revalidate(); root.repaint(); } + + private void showBanner(String message) { + bannerLabel.setText(message); + bannerLabel.setVisible(true); + } + + private void clearBanner() { + bannerLabel.setText(""); + bannerLabel.setVisible(false); + } } 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..8c720cd 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 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,7 +143,9 @@ 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) { @@ -115,45 +155,41 @@ public void run() { 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 +197,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 +221,81 @@ 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 && (frameListener != null || (canvas != null && canvas.isVisible()))) { 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 (canvas != null) { + canvas.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 (canvas != null) { + canvas.showImage(frame); } - canvas.showImage(frame); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ignored) { + } + } + + 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..f2af1d4 --- /dev/null +++ b/src/main/java/com/foodsense/security/SafeImageLoader.java @@ -0,0 +1,106 @@ +/* + * Asynchronous, bounded image loader for FoodSense. + * Protects against EDT blocking, SSRF, non-HTTPS URLs, and memory exhaustion (payload caps). + */ + +package com.foodsense.security; + +import javax.imageio.ImageIO; +import javax.swing.*; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +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.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Consumer; + +/** + * Handles safe asynchronous image loading from remote HTTPS URLs. + * Limits image size to 5MB, enforces strict connect and read timeouts, 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 Duration TIMEOUT = Duration.ofSeconds(5); + + 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 SafeImageLoader() { + // Prevent instantiation + } + + /** + * Asynchronously downloads an image from a verified HTTPS URL, scales it smoothly, + * 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 + * @example + *
{@code
+     * SafeImageLoader.loadImageAsync("https://images.openfoodfacts.org/img.jpg", 180, 200, icon -> {
+     *     if (icon != null) {
+     *         label.setIcon(icon);
+     *     }
+     * });
+     * }
+ */ + 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()) { + byte[] bytes = in.readNBytes(MAX_IMAGE_BYTES + 1); + if (bytes.length <= MAX_IMAGE_BYTES) { + BufferedImage img = ImageIO.read(new ByteArrayInputStream(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); + } + } + } + } + } catch (Exception ignored) { + // Return null icon on network, parse, or timeout error + } + + final ImageIcon result = icon; + SwingUtilities.invokeLater(() -> callback.accept(result)); + }); + } +} 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..9cea5f7 --- /dev/null +++ b/src/main/java/com/foodsense/security/SecurityValidator.java @@ -0,0 +1,123 @@ +/* + * 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 { + + /** + * 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(); + return !lowerHost.equals("localhost") + && !lowerHost.equals("0.0.0.0") + && !lowerHost.startsWith("127.") + && !lowerHost.equals("::1") + && !lowerHost.equals("[::1]") + && !lowerHost.equals("169.254.169.254") + && !lowerHost.startsWith("10.") + && !lowerHost.startsWith("172.16.") + && !lowerHost.startsWith("172.17.") + && !lowerHost.startsWith("172.18.") + && !lowerHost.startsWith("172.19.") + && !lowerHost.startsWith("172.2") + && !lowerHost.startsWith("172.30.") + && !lowerHost.startsWith("172.31.") + && !lowerHost.startsWith("192.168."); + } 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..7f23249 --- /dev/null +++ b/src/main/java/com/foodsense/ui/AllergenBanner.java @@ -0,0 +1,76 @@ +/* + * Danger-styled allergen warning banner for FoodSense. + * Displays allergen chips/pills in a highlighted alert card. + */ + +package com.foodsense.ui; + +import com.foodsense.security.SecurityValidator; + +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 + String safeText = SecurityValidator.escapeHtml(allergensText); + JLabel content = new JLabel("" + safeText + ""); + content.setFont(FoodSenseTheme.getFont(Font.PLAIN, 13f)); + content.setAlignmentX(Component.LEFT_ALIGNMENT); + card.add(content); + + add(card); + } + + 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/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..d5130a7 --- /dev/null +++ b/src/main/java/com/foodsense/ui/FoodSenseTheme.java @@ -0,0 +1,189 @@ +/* + * Design token definitions, color palettes, and theme management for FoodSense. + * Adheres to 4px spacing scale, WCAG 2.2 AA contrast rules, and provides runtime light/dark switching. + */ + +package com.foodsense.ui; + +import com.formdev.flatlaf.FlatDarkLaf; +import com.formdev.flatlaf.FlatLaf; +import com.formdev.flatlaf.FlatLightLaf; + +import javax.swing.*; +import java.awt.*; + +/** + * Central design tokens, color scales, and theme configuration for FoodSense. + */ +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()); + } + } + + // ── Semantic Color Getters ──────────────────────────────── + + public static Color getBackground() { + return darkMode ? new Color(15, 23, 42) : new Color(248, 250, 252); + } + + public static Color getSidebarBackground() { + return darkMode ? new Color(11, 19, 32) : new Color(241, 245, 249); + } + + public static Color getCardBackground() { + return darkMode ? new Color(30, 41, 59) : Color.WHITE; + } + + public static Color getCardBorder() { + return darkMode ? new Color(51, 65, 85) : new Color(226, 232, 240); + } + + public static Color getTextPrimary() { + return darkMode ? new Color(248, 250, 252) : new Color(15, 23, 42); + } + + public static Color getTextSecondary() { + return darkMode ? new Color(203, 213, 225) : new Color(71, 85, 105); + } + + public static Color getTextMuted() { + return darkMode ? new Color(148, 163, 184) : new Color(100, 116, 139); + } + + public static Color getPrimaryAccent() { + return darkMode ? new Color(52, 211, 153) : new Color(27, 67, 50); + } + + public static Color getPrimaryAccentHover() { + return darkMode ? new Color(16, 185, 129) : new Color(45, 106, 79); + } + + public static Color getPrimaryLight() { + return darkMode ? new Color(6, 78, 59) : new Color(232, 245, 233); + } + + 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/NutriScoreSpectrumView.java b/src/main/java/com/foodsense/ui/NutriScoreSpectrumView.java new file mode 100644 index 0000000..8088297 --- /dev/null +++ b/src/main/java/com/foodsense/ui/NutriScoreSpectrumView.java @@ -0,0 +1,146 @@ +/* + * 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. + * The active grade is visually elevated and scaled, while remaining pills are dimmed. + */ +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(220, 48)); + setMaximumSize(new Dimension(240, 52)); + } + + /** + * Updates the active grade and repaints the spectrum. + * + * @param grade letter grade (A-E), or null for neutral spectrum + */ + public void setGrade(String grade) { + this.activeGrade = (grade != null && !grade.isBlank()) ? grade.trim().toUpperCase() : 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 = 28; + int standardH = 28; + int activeW = 34; + int activeH = 38; + int gap = 4; + + // Calculate total content width + 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, 10, 10)); + + // Crisp border highlight + g2.setColor(new Color(255, 255, 255, 180)); + g2.setStroke(new BasicStroke(1.5f)); + g2.draw(new RoundRectangle2D.Float(currentX, y, w, h, 10, 10)); + + // Font for active grade + g2.setFont(FoodSenseTheme.getFont(Font.BOLD, 17f)); + g2.setColor(Color.WHITE); + } else { + // Dimmed inactive pill (clean transparency) + int alpha = (activeIndex >= 0) ? 90 : 200; + Color dimmed = new Color(baseColor.getRed(), baseColor.getGreen(), baseColor.getBlue(), alpha); + g2.setColor(dimmed); + g2.fill(new RoundRectangle2D.Float(currentX, y, w, h, 8, 8)); + + g2.setFont(FoodSenseTheme.getFont(Font.BOLD, 12f)); + 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..8395868 --- /dev/null +++ b/src/main/java/com/foodsense/ui/NutritionLabelPanel.java @@ -0,0 +1,242 @@ +/* + * Structured nutrition card for FoodSense. + * Displays hero calorie metric, macronutrient breakdown bar, and tabular nutrient details. + */ + +package com.foodsense.ui; + +import com.foodsense.Nutriments; + +import javax.swing.*; +import java.awt.*; +import java.awt.geom.RoundRectangle2D; + +/** + * Modern nutrition panel featuring hero calories, macro visual proportion bar, and per-100g table. + */ +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.getEnergy())); + add(Box.createVerticalStrut(FoodSenseTheme.SPACE_16)); + add(buildMacroBar(n)); + 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("Per 100g reference amount"); + subtitle.setFont(FoodSenseTheme.getFont(Font.PLAIN, 12f)); + subtitle.setForeground(FoodSenseTheme.getTextMuted()); + p.add(subtitle); + + return p; + } + + private JPanel buildHeroCalories(String calories) { + 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(16, 20, 16, 20)); + hero.setMaximumSize(new Dimension(Integer.MAX_VALUE, 80)); + 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, 11f)); + label.setForeground(FoodSenseTheme.getTextMuted()); + left.add(label); + + String val = (calories != null && !calories.isBlank()) ? calories : "—"; + JLabel num = new JLabel(val + " kcal"); + num.putClientProperty("html.disable", Boolean.TRUE); + num.setFont(FoodSenseTheme.getFont(Font.BOLD, 26f)); + num.setForeground(FoodSenseTheme.getPrimaryAccent()); + left.add(num); + + hero.add(left, BorderLayout.WEST); + return hero; + } + + private JPanel buildMacroBar(Nutriments n) { + double carbs = parseDouble(n.getCarbohydrates()); + double fat = parseDouble(n.getFat()); + double protein = parseDouble(n.getProteins()); + double total = carbs + fat + protein; + + JPanel container = new JPanel(); + container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS)); + container.setOpaque(false); + container.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(); + g2.setColor(FoodSenseTheme.getCardBorder()); + g2.fill(new RoundRectangle2D.Float(0, 0, w, h, 8, 8)); + + if (total > 0) { + int carbW = (int) Math.round((carbs / total) * w); + int fatW = (int) Math.round((fat / total) * w); + int proteinW = w - carbW - fatW; + + int curX = 0; + // Carbs (Amber) + g2.setColor(new Color(245, 158, 11)); + g2.fill(new RoundRectangle2D.Float(curX, 0, carbW, h, 8, 8)); + curX += carbW; + + // Fat (Rose) + g2.setColor(new Color(244, 63, 94)); + g2.fillRect(curX, 0, fatW, h); + curX += fatW; + + // Protein (Emerald) + g2.setColor(new Color(16, 185, 129)); + g2.fill(new RoundRectangle2D.Float(curX, 0, proteinW, h, 8, 8)); + } + g2.dispose(); + } + }; + bar.setPreferredSize(new Dimension(Integer.MAX_VALUE, 10)); + bar.setMaximumSize(new Dimension(Integer.MAX_VALUE, 10)); + bar.setOpaque(false); + container.add(bar); + container.add(Box.createVerticalStrut(6)); + + // Legend row + JPanel legend = new JPanel(new FlowLayout(FlowLayout.LEFT, 16, 0)); + legend.setOpaque(false); + legend.setAlignmentX(Component.LEFT_ALIGNMENT); + legend.add(mkLegendItem("Carbs: " + fmt(carbs) + "g", new Color(245, 158, 11))); + legend.add(mkLegendItem("Fat: " + fmt(fat) + "g", new Color(244, 63, 94))); + legend.add(mkLegendItem("Protein: " + fmt(protein) + "g", new Color(16, 185, 129))); + container.add(legend); + + return container; + } + + private JLabel mkLegendItem(String text, Color color) { + JLabel l = new JLabel("● " + text); + l.setFont(FoodSenseTheme.getFont(Font.PLAIN, 12f)); + l.setForeground(color); + return l; + } + + 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)); + + Object[][] rows = { + { "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 }, + }; + + 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(10, sub ? 28 : 16, 10, 16)); + + JLabel left = new JLabel(name); + left.setFont(FoodSenseTheme.getFont(sub ? Font.PLAIN : Font.BOLD, sub ? 12f : 13f)); + left.setForeground(sub ? FoodSenseTheme.getTextMuted() : FoodSenseTheme.getTextPrimary()); + + String v = (value != null && !value.isBlank()) ? value : "—"; + JLabel right = new JLabel(v + " " + unit); + 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 double parseDouble(String str) { + if (str == null) return 0.0; + try { + return Double.parseDouble(str.trim()); + } catch (NumberFormatException e) { + return 0.0; + } + } + + private String fmt(double d) { + return String.format("%.1f", d); + } +} 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/NutriScoreSpectrumViewTest.java b/src/test/java/com/foodsense/NutriScoreSpectrumViewTest.java new file mode 100644 index 0000000..d44e9cf --- /dev/null +++ b/src/test/java/com/foodsense/NutriScoreSpectrumViewTest.java @@ -0,0 +1,45 @@ +/* + * 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()); + } + + @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/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..79fdb8e --- /dev/null +++ b/src/test/java/com/foodsense/SecurityValidatorTest.java @@ -0,0 +1,80 @@ +/* + * 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