Skip to content

TOPPView: fixes a few error messages boxes (im IM frames, and 2D projections) - #8047

Merged
timosachsenberg merged 5 commits into
OpenMS:developfrom
cbielow:fix_im_tv2
May 15, 2025
Merged

timosachsenberg merged 5 commits into
OpenMS:developfrom
cbielow:fix_im_tv2

Conversation

@cbielow

@cbielow cbielow commented May 15, 2025 •

Copy link
Copy Markdown
Contributor

Description

fixes #8046

Checklist

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

How can I get additional information on failed tests during CI

Click to expand If your PR is failing you can check out

Advanced commands (admins / reviewer only)

Click to expand
  • /reformat (experimental) applies the clang-format style changes as additional commit. Note: your branch must have a different name (e.g., yourrepo:feature/XYZ) than the receiving branch (e.g., OpenMS:develop). Otherwise, reformat fails to push.
  • setting the label "NoJenkins" will skip tests for this PR on jenkins (saves resources e.g., on edits that do not affect tests)
  • commenting with rebuild jenkins will retrigger Jenkins-based CI builds

⚠️ Note: Once you opened a PR try to minimize the number of pushes to it as every push will trigger CI (automated builds and test) and is rather heavy on our infrastructure (e.g., if several pushes per day are performed).

Summary by CodeRabbit

  • New Features

    • Added an option in the context menu to switch to ion mobility view when relevant data is available.
  • Bug Fixes

    • Improved handling of empty RT ranges in context menus to prevent invalid entries.
  • Refactor

    • Simplified context menu actions for survey and fragment scans, enabling more direct and reliable user interactions.

@coderabbitai

coderabbitai Bot commented May 15, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes refactor context menu handling in the 2D plot view, update the method signature for collecting fragment scans, and add exception safety for projections. The context menu logic now uses lambda callbacks for actions, skips invalid RT neighbor entries, and adds support for ion mobility view switching. Exception handling prevents InvalidRange errors during projections.

Changes

File(s) Change Summary
src/openms_gui/include/OpenMS/VISUAL/Plot2DCanvas.h Updated collectFragmentScansInArea_ method signature by removing the QAction* parameter and updating its documentation.
src/openms_gui/source/VISUAL/Plot2DCanvas.cpp Refactored context menu logic to use lambdas for actions, improved neighbor scan selection, added ion mobility view action, and updated collectFragmentScansInArea_ to match new signature.
src/openms_gui/source/VISUAL/LayerDataPeak.cpp Wrapped projection boundary assignments in try-catch blocks to handle InvalidRange exceptions and prevent crashes. Cached experiment reference for efficiency.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Plot2DCanvas
    participant LayerDataPeak
    participant QMenu

    User->>Plot2DCanvas: Right-click (context menu event)
    Plot2DCanvas->>LayerDataPeak: Query for RT/mz area and spectrum info
    Plot2DCanvas->>QMenu: Create context menu with survey/fragment scan actions (using lambdas)
    alt Ion mobility data present
        Plot2DCanvas->>QMenu: Add ion mobility view switch action
    end
    User->>QMenu: Selects action
    QMenu->>Plot2DCanvas: Lambda callback executes action directly
Loading

Assessment against linked issues

Objective Addressed Explanation
Prevent InvalidRange exception when activating projections in 2D view or right-clicking context menu in IM-frame view (#8046) ✅

Poem

A menu appears with a hop and a cheer,
No more exceptions for users to fear!
With lambdas and checks, the bugs disappear,
Ion mobility views now switch in high gear.
The rabbit approves, with a wiggle and grin—
Refactored and safe, let the clicking begin!
🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@cbielow
cbielow requested a review from timosachsenberg May 15, 2025 09:15

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
src/openms_gui/include/OpenMS/VISUAL/Plot2DCanvas.h (1)

112-114: Clarify return-value semantics in the header comment

collectFragmentScansInArea_() now returns a bool, yet the doxygen comment only states that the method “adds them to the menus”. Please extend the comment to explain what the boolean indicates (e.g. “true if at least one scan was added, false otherwise”).

src/openms_gui/source/VISUAL/LayerDataPeak.cpp (1)

108-143: Over-broad catch (...) hides real errors

The three projection blocks swallow all exceptions and continue silently.
While avoiding pop-ups is desirable, catching every exception type makes debugging
hard and may mask unrelated bugs.

Consider catching the specific exception thrown by operator[] / push_back
(e.g. Exception::InvalidRange) and log others:

try
{
  …
}
catch (const Exception::InvalidRange&) { /* ignore – projection outside area */ }
catch (...)
{
  OPENMS_LOG_ERROR << "Unexpected error while building projection.\n";
}
src/openms_gui/source/VISUAL/Plot2DCanvas.cpp (1)

1526-1544: Iterator captured in lambda – prefer stable index

Each lambda copies the iterator it. Although that works, computing the
index once makes the capture lighter and avoids surprises if const_iterator
internals change:

- msn_scans->addAction(QString("RT: ") + …,
-                      [=]() { emit showSpectrumAsNew1D(it - layer.getPeakData()->begin()); });
+ const int spec_idx = static_cast<int>(it - layer.getPeakData()->begin());
+ msn_scans->addAction(QString("RT: ") + …,
+                      [=]() { emit showSpectrumAsNew1D(spec_idx); });

Same remark for the meta-data action.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 4a57f59 and a99aa5c.

📒 Files selected for processing (3)
  • src/openms_gui/include/OpenMS/VISUAL/Plot2DCanvas.h (1 hunks)
  • src/openms_gui/source/VISUAL/LayerDataPeak.cpp (2 hunks)
  • src/openms_gui/source/VISUAL/Plot2DCanvas.cpp (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)

Comment on lines +887 to +915
// in a IM-frame (IM vs. m/z), the RT is empty in `e_units`, and showing neighbouring RT scans is not possible (this layer only has this IM frame)
// --> skip entries for RT neighbours.
if (!e_units.RangeRT::isEmpty())
{
current = std::max(SignedSize{0}, size - 1); // we want the rightmost valid scan index
}

SignedSize i = 0;
while (current + i < size || current - i >= 0)
{
if (current + i < size && (*lp->getPeakData())[current + i].getMSLevel() == 1)
{
current += i;
break;
}
if (current - i >= 0 && (*lp->getPeakData())[current - i].getMSLevel() == 1)
// add surrounding survey scans
// find nearest survey scan
SignedSize size = lp->getPeakData()->size();
Int current = lp->getPeakData()->RTBegin(e_units.getMinRT()) - lp->getPeakData()->begin();
if (current == size) // if the user clicked right of the last MS1 scan
{
current -= i;
break;
current = std::max(SignedSize {0}, size - 1); // we want the rightmost valid scan index
}
++i;
}
// search for four scans in both directions
vector<Int> indices;
indices.push_back(current);
i = 1;
while (current - i >= 0 && indices.size() < 5)
{
if ((*lp->getPeakData())[current - i].getMSLevel() == 1)

SignedSize i = 0;
while (current + i < size || current - i >= 0)
{
indices.push_back(current - i);
if (current + i < size && (*lp->getPeakData())[current + i].getMSLevel() == 1)
{
current += i;
break;
}
if (current - i >= 0 && (*lp->getPeakData())[current - i].getMSLevel() == 1)
{
current -= i;
break;
}
++i;
}
++i;
}
i = 1;
while (current + i < size && indices.size() < 9)
{
if ((*lp->getPeakData())[current + i].getMSLevel() == 1)
// search for four scans in both directions

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

current calculation may dereference an empty experiment

If the peak map is empty (size == 0) the loop dereferences
(*lp->getPeakData())[current ± i], leading to UB.

Add a quick exit:

SignedSize size = lp->getPeakData()->size();
if (size == 0) return;                 // nothing to show – avoid crash

and/or move the dereference inside a bounds-checked helper.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// in a IM-frame (IM vs. m/z), the RT is empty in `e_units`, and showing neighbouring RT scans is not possible (this layer only has this IM frame)
// --> skip entries for RT neighbours.
if (!e_units.RangeRT::isEmpty())
{
current = std::max(SignedSize{0}, size - 1); // we want the rightmost valid scan index
}
SignedSize i = 0;
while (current + i < size || current - i >= 0)
{
if (current + i < size && (*lp->getPeakData())[current + i].getMSLevel() == 1)
{
current += i;
break;
}
if (current - i >= 0 && (*lp->getPeakData())[current - i].getMSLevel() == 1)
// add surrounding survey scans
// find nearest survey scan
SignedSize size = lp->getPeakData()->size();
Int current = lp->getPeakData()->RTBegin(e_units.getMinRT()) - lp->getPeakData()->begin();
if (current == size) // if the user clicked right of the last MS1 scan
{
current -= i;
break;
current = std::max(SignedSize {0}, size - 1); // we want the rightmost valid scan index
}
++i;
}
// search for four scans in both directions
vector<Int> indices;
indices.push_back(current);
i = 1;
while (current - i >= 0 && indices.size() < 5)
{
if ((*lp->getPeakData())[current - i].getMSLevel() == 1)
SignedSize i = 0;
while (current + i < size || current - i >= 0)
{
indices.push_back(current - i);
if (current + i < size && (*lp->getPeakData())[current + i].getMSLevel() == 1)
{
current += i;
break;
}
if (current - i >= 0 && (*lp->getPeakData())[current - i].getMSLevel() == 1)
{
current -= i;
break;
}
++i;
}
++i;
}
i = 1;
while (current + i < size && indices.size() < 9)
{
if ((*lp->getPeakData())[current + i].getMSLevel() == 1)
// search for four scans in both directions
// add surrounding survey scans
// find nearest survey scan
SignedSize size = lp->getPeakData()->size();
if (size == 0) return; // nothing to show – avoid crash
Int current = lp->getPeakData()->RTBegin(e_units.getMinRT()) - lp->getPeakData()->begin();
if (current == size) // if the user clicked right of the last MS1 scan
{
current = std::max(SignedSize{0}, size - 1); // we want the rightmost valid scan index
}
// …
🤖 Prompt for AI Agents
In src/openms_gui/source/VISUAL/Plot2DCanvas.cpp around lines 887 to 915, the
code calculates 'current' and then dereferences peak data without checking if
the peak map is empty, which can cause undefined behavior if size is zero. To
fix this, add a check right after obtaining 'size' to return early or skip
processing if size is zero, preventing any dereference on empty data.
Alternatively, ensure all dereferences of peak data are guarded by bounds checks
or moved inside a helper function that performs these checks.

@timosachsenberg timosachsenberg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good to me

@timosachsenberg
timosachsenberg merged commit 970bfbe into OpenMS:develop May 15, 2025
pjones added a commit that referenced this pull request May 19, 2025
Backport the following commits from `develop`:

  - 226fb60
  - 392d1cc
  - a99aa5c
pjones added a commit that referenced this pull request May 19, 2025
Backport the following commits from `develop`:

  - 226fb60
  - 392d1cc
  - a99aa5c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TOPPView: some actions throw an InvalidRange exception

2 participants