Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/sdk 4030 updated: IncorrectContextViolation #763

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from

Conversation

Anush-Shand
Copy link
Contributor

@Anush-Shand Anush-Shand commented Mar 6, 2025

Summary by CodeRabbit

  • Refactor

    • Streamlined the process for calculating device dimensions and screen metrics, ensuring consistent and accurate results across different Android API levels.
  • Tests

    • Updated device simulations by removing hard-coded pixel values, aligning the tests with the improved measurement approach.

Fixes #674

CTLalit and others added 6 commits August 30, 2024 13:29
- uses version check and fixes windowmanager fetch
- removes redundant code for pixes which was unused
- reduces service fetches from context
- reduces version checks
- refactors code to add placeholder class
- returns window result as whole
- catches exception
- removes decimal adjustment which was done twice.
Copy link

coderabbitai bot commented Mar 6, 2025

Walkthrough

The changes refactor how device metrics are computed in the SDK. In the core module, separate pixel fields are replaced by a new method that calculates window dimensions and DPI via a unified WindowSize object. This method adapts its implementation based on the Android API level, using WindowMetrics for API 30+ and DisplayMetrics for lower versions. Additionally, a helper method for retrieving the WindowManager is added, and the appBucket field is updated to be final. Meanwhile, the mock implementation has removed outdated fixed pixel retrieval methods.

Changes

File Path Change Summary
clevertap-core/src/main/java/com/clevertap/android/sdk/DeviceInfo.java Removed heightPixels and widthPixels fields; introduced getWindowSizeData() to compute dimensions and DPI based on Android API level; added getWindowManager(); added inner class WindowSize; updated appBucket.
clevertap-core/src/test/java/com/clevertap/android/sdk/MockDeviceInfo.kt Removed overridden methods getHeightPixels() and getWidthPixels() from MockDeviceInfo to simplify the mock implementation.

Sequence Diagram(s)

sequenceDiagram
    participant DC as DeviceCachedInfo
    participant API as Android API
    participant WM as WindowManager
    participant WS as WindowSize

    DC->>DC: Invoke getWindowSizeData()

    alt API Level >= 30
        DC->>API: Retrieve window metrics (WindowMetrics)
    else API Level < 30
        DC->>API: Retrieve display metrics (DisplayMetrics)
    end

    API-->>DC: Return pixel dimensions and DPI
    DC->>WS: Create WindowSize (width, height, dpi)
    WS-->>DC: Return WindowSize object

    DC->>WM: Retrieve WindowManager instance via getWindowManager()
Loading

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b923bff and aed3a0e.

📒 Files selected for processing (1)
  • clevertap-core/src/main/java/com/clevertap/android/sdk/DeviceInfo.java (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: lint-staticChecks-test-build
  • GitHub Check: lint-staticChecks-test-build
🔇 Additional comments (5)
clevertap-core/src/main/java/com/clevertap/android/sdk/DeviceInfo.java (5)

91-91: Good: Made appBucket field final.

This improves code safety by ensuring the field is initialized during construction and cannot be modified afterward.


109-115: Improve code structure with WindowSize object.

The refactoring to use a WindowSize object to encapsulate related dimension data is a good improvement over separate fields.


127-175: Well-structured implementation for device metrics.

The getWindowSizeData() method is well-implemented with:

  • Proper API level detection (API 30+ vs older versions)
  • Good defensive coding with null checks
  • Correct handling of system gesture insets for newer Android versions
  • Appropriate use of DisplayMetrics for backward compatibility

One minor note: The comment on line 167 mentions "legacy code", which may indicate some technical debt, but the implementation is correct.


314-327: Good object encapsulation with WindowSize class.

Creating a dedicated class to encapsulate window dimensions and DPI is a clean design approach that improves code readability and maintenance.


329-351: Well-implemented WindowManager retrieval.

The getWindowManager() method:

  • Handles different Android API levels appropriately
  • Includes proper error handling with try-catch
  • Uses the recommended approach for API 30+ with displayContext and windowContext
  • Falls back gracefully to the older API

This is a robust implementation that follows Android best practices.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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.

@Anush-Shand Anush-Shand changed the title Feat/sdk 4030 updated Feat/sdk 4030 updated: Incorrect Context Violation Mar 6, 2025
@Anush-Shand Anush-Shand changed the title Feat/sdk 4030 updated: Incorrect Context Violation Feat/sdk 4030 updated: IncorrectContextViolation Mar 6, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
clevertap-core/src/main/java/com/clevertap/android/sdk/DeviceInfo.java (2)

107-122: Consider logging when WindowSize defaults to zero-size.
If getWindowManager() returns null, the resulting zero width/height might cause silent behavior. Logging that situation can aid troubleshooting.

             if (wm == null) {
+                Logger.v("DeviceInfo", "WindowManager is null, returning zero dimension for width/height");
                 return new WindowSize(0, 0, 0);
             }

326-340: Log the caught UnsupportedOperationException.
Catching the exception silently makes debugging harder if createWindowContext fails. Consider logging it for clarity.

} catch (UnsupportedOperationException e) {
-    wm = null;
+    Logger.d("DeviceInfo", "Creating WindowContext not supported: " + e.getMessage());
+    wm = null;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a4fcc5 and b923bff.

📒 Files selected for processing (2)
  • clevertap-core/src/main/java/com/clevertap/android/sdk/DeviceInfo.java (4 hunks)
  • clevertap-core/src/test/java/com/clevertap/android/sdk/MockDeviceInfo.kt (0 hunks)
💤 Files with no reviewable changes (1)
  • clevertap-core/src/test/java/com/clevertap/android/sdk/MockDeviceInfo.kt
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: lint-staticChecks-test-build
🔇 Additional comments (4)
clevertap-core/src/main/java/com/clevertap/android/sdk/DeviceInfo.java (4)

27-27: Import of NonNull looks good.
The addition of the @NonNull annotation is coherent with its subsequent usage.


88-88: Use of final for appBucket is appropriate.
Declaring appBucket as final enhances immutability and clarity by ensuring it's only assigned once.


123-172: Check for a non-zero DPI to avoid potential numeric anomalies.
Currently, there's no guard for zero or negative DPI values. While unlikely, adding a safety check prevents edge-case issues (e.g., xdpi=0 leading to division by zero).

 double doubleWidth = 0;
 double doubleHeight = 0;
 if (localXDpi > 0 && localYDpi > 0) {
     doubleWidth = localWidth / localXDpi;
     doubleHeight = localHeight / localYDpi;
 } else {
+    Logger.v("DeviceInfo", "Detected zero DPI; skipping dimension calculation or using fallback");
 }

311-325: Lightweight data holder approach is well-designed.
The new WindowSize class with final fields is straightforward, ensuring immutability.

@Anush-Shand Anush-Shand closed this Mar 6, 2025
@Anush-Shand Anush-Shand reopened this Mar 7, 2025
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.

2 participants