UI Toolkit Controls and Rendering
Overview
This area is the shared UI toolkit used by Telegram Desktop feature screens for reusable widgets, modal boxes, row/list painting, chat visual helpers, inline-bot panels, poll composition helpers, and low-level image/text/effects rendering. The main entry points are the ui/** helpers themselves, modal box content in boxes/** and ui/boxes/**, layout primitives in layout/**, compose/context menu helpers in menu/**, inline bot result UI in inline_bots/**, and poll attachment/link widgets in poll/**.
Modal screens are normally built as Ui::BoxContent and shown through the layer system. boxes/abstract_box.h exposes the legacy Ui::show(object_ptr<BoxType>, LayerOptions, anim::type) wrapper; boxes/abstract_box.cpp resolves the active primary window and delegates to window->show(...), while Ui::hideLayer() calls window->hideLayer(...). For standalone contexts, ui/…/standalone_layer_stack.h and .cpp implement Ui::StandaloneLayerStack, which wraps each BoxContent in a BoxLayerWidget inside a top-level SeparatePanel, hides the previous panel when stacking, restores it on close, and returns a ShowFactory whose Show implementation supports boxes but explicitly ignores raw LayerWidget objects. Feature boxes compose common building blocks rather than painting everything directly: for example poll/poll_link_box.cpp adds a title, labels, skips, an Ui::InputField, and buttons into a Ui::GenericBox vertical layout.
Reusable box and list layout helpers live in ui/vertical_list.h and .cpp. They add fixed-height skips, divider bars, divider labels, and subsection titles to Ui::VerticalLayout, consistently using styles/style_layers.h defaults. Larger feature boxes such as boxes/create_poll_box.cpp build whole screens from these pieces plus Ui::InputField, Ui::Checkbox, Ui::SlideWrap, Ui::FadeWrapScaled, Ui::VerticalLayoutReorder, scroll areas, emoji panels, and send-menu details. boxes/create_poll_box.h exposes the box result as a PollData, caption text, and Api::SendOptions, while the implementation coordinates question/description/solution fields, option rows, drag/drop media, reorder handles, validation flags, and submit events.
Peer lists are the main reusable row abstraction for “choose people/chats” screens. boxes/peer_list_box.h defines PeerListRow, its painting hooks, checked/disabled state, right-action and multi-element hooks, search metadata, status refresh timing, and cached userpic fields. boxes/peer_list_box.cpp wires PeerListBox to a PeerListController, optional Ui::MultiSelect search/filter field, scroll skips, keyboard navigation, section headers, and section index. boxes/peer_list_widgets.h and .cpp provide a lighter PeerListWidgets adapter that renders rows as a vertical list of simple settings buttons; it reuses each row’s paintUserpic, name badge, status text, and right action paint hooks, but intentionally rejects full search/prepend/remove behavior through Unexpected(...) delegate methods.
Userpic rendering is centralized in ui/empty_userpic.h, ui/empty_userpic.cpp, ui/userpic_view.h, and ui/userpic_view.cpp. EmptyUserpic derives colors from stable color indices, extracts display initials, paints circle/rounded/square/monoforum placeholders, and also generates special Saved Messages, Replies, Hidden Author, My Notes, Currency, external, and inaccessible-account avatars. PeerUserpicView caches a prepared userpic image plus palette version, shape, and Ayu userpic state; ValidateUserpicCache(...) regenerates the cache when the cloud image, placeholder object, size, palette, or shape changes, applying circle, forum, monoforum, or override rounding. Peer-list helpers in boxes/peer_list_box.cpp expose PaintUserpicCallback(...) and ForceRoundUserpicCallback(...) so row renderers can defer peer photo loading/painting and still produce stable rounded output.
Badges and counters are similarly shared. ui/unread_badge.h and .cpp define UnreadBadge, PeerBadge, text scam/fake/direct badge helpers, and bot verification/custom emoji status painting. UnreadBadge::setText() sizes itself from Dialogs::Ui::UnreadBadgeStyle() and paints through ui/unread_badge_paint.h; ui/…/jump_down_button.cpp uses the same paint helper to draw the unread counter on top of the history jump-down button. PeerBadge composes verification icons, premium stars, custom emoji statuses, and text badges beside peer names, with repaint callbacks for animated custom emoji.
Rounded geometry and media layout are utility-level rendering contracts. ui/cached_round_corners.h and .cpp initialize cached corner pixmaps and masks in StartCachedCorners(), refresh palette-dependent corners on style::PaletteChanged(), and provide FillRoundRect(...), FillRoundShadow(...), PrepareCornerPixmaps(...), and CachedCornersMasks(...). ui/grouped_layout.h and .cpp implement Telegram-style grouped media layout: it classifies item aspect ratios, lays out groups of one through four with tailored cases, and switches to ComplexLayouter for five or more items or very wide media. The result carries both geometry and RectParts sides; GetCornersFromSides(...) maps exposed sides to rounded corners, and GetImageScaleSizeForGeometry(...) chooses crop scaling for each tile.
The generic layout layer in layout/** gives non-QWidget items dimensions, positions, click handling, and mosaic layout. layout/abstract_layout_item.h stores width/height/max/min, position, and shift values and implements point hit testing; layout/layout_item_base.h adds history-view text state and selection hooks. layout/layout_mosaic.h and .cpp arrange AbstractLayoutItem instances into rows with right skips and padding, support point-to-item lookup, item-rect lookup, clip-aware painting, and row validation for incremental result lists. This is used by inline-bot layout items and similar virtualized/non-widget UI.
Text rendering options are initialized in ui/…/text_options.cpp. Ui::InitTextOptions() derives dialog and webpage widths from chat style constants, then the getters in ui/…/text_options.h expose parse options for history text, bot commands, service messages, names, dialogs, and webpage titles/descriptions. ui/…/text_lottie_custom_emoji.h and .cpp bridge Lottie icons into Ui::Text::CustomEmoji: a LottieCustomEmoji chooses entity data from the descriptor name/path, starts animation if there is more than one frame, obeys paused/force-first/force-last context flags, and exposes helper functions for marked text contexts containing a single custom emoji.
Images and thumbnails flow through ui/image/** and ui/dynamic_* helpers. ui/…/image.h and .cpp wrap immutable QImage data with prepared QPixmap caches keyed by requested width, height, preparation options, and colorization; all sizes are scaled by style::DevicePixelRatio(), and Image::Empty() / BlankMedia() provide stable 1x1 fallback images. ui/…/image_location.h defines serializable storage locations for files and images, including file-reference refresh and cache keys. ui/…/image_source.cpp reads local paths or byte arrays under App::kImageSizeLimit and decodes them through App::readImage(...). Poll helpers reuse this abstraction: poll/poll_link_thumbnail.cpp implements a palette-versioned Ui::DynamicImage placeholder, while poll/poll_media_upload.cpp implements local image thumbnails and document previews for poll option media.
Chat-specific visual helpers live under ui/chat/**. ui/…/chat_style.h and .cpp build ChatStyle, MessageStyle, MessageImageStyle, quote/pre caches, colored palettes, and ChatPaintContext, combining global style resources, current palette, color indices, selected/outgoing state, bubble image style, and quote color caches. ui/…/message_bubble.h and .cpp paint message bubbles with configurable corner rounding, tails, shadows, selected intervals, torn-edge gaps, and optional wallpaper pattern masking. ui/…/message_bar.h and .cpp implement animated bars such as reply/pinned bars: they hold title/text Ui::Text::String, optional Ui::DynamicImage preview, count/index scroll bar state, and pixmap grabs for tweening body/text/image/title changes.
Controls under ui/controls/** are reusable chat and screen widgets. ui/…/send_button.h and .cpp implement a ripple button whose state switches among send, stop, schedule, save, record, round, cancel, slowmode, and edit-price modes; it captures old/new content pixmaps for animated transitions, uses Lottie for voice/round transitions, formats slowmode countdowns and star counts, and updates accessible names per state. ui/…/tabbed_search.h and .cpp implement emoji/sticker search with a text field, search/back/cancel buttons, horizontal emoji group strip, wheel/drag scrolling, selected group state, and debounced query producer. ui/…/jump_down_button.h and .cpp paint the two-layer history jump-down icon, ripple mask, and unread badge. Other controls in this directory follow the same pattern: small RpWidget/RippleButton wrappers using style resources, reactive producers, and shared paint helpers.
Inline bot UI composes the virtual layout and rounded-panel helpers. inline_bots/inline_results_widget.h and .cpp define InlineBots::Layout::Widget, a scrollable panel anchored above the compose area that queries inline bots with a 350ms timer, caches results by query, resizes based on available bottom space, animates show/hide with Ui::PanelAnimation, paints rounded corners and shadow through Ui::PrepareCornerPixmaps() / Ui::FillRoundRect(), and uses a transparent overlay to keep animated GIFs repainting during scroll. inline_bots/inline_bot_layout_item.h and .cpp define ItemBase, its Context callbacks, click-handler marker types, preview accessors, preloading, layout-change/repaint notifications, thumbnail loading, contact avatar generation through EmptyUserpic, and type-to-layout dispatch for photo, file, video, sticker, GIF, article, game, contact, and forced gallery/list modes.
Menu helpers under menu/** attach reusable popup actions to feature controls. menu/menu_send.h defines SendMenu::Details, action types, FillSendMenu(...), AttachSendMenuEffect(...), and SetupMenuAndShortcuts(...). menu/menu_send.cpp builds send/schedule/spoiler/caption/quality/effect actions, and its EffectPreview is itself a composed UI widget: it creates a temporary ChatStyle, generated history preview items, a PathShiftGradient, Lottie player, loading radial animation, rounded bottom button, shadow, and cached background to preview message effects before sending.
Effects under ui/effects/** provide optional animation widgets and painters. ui/…/skeleton_animation.h and .cpp installs a paint event filter on a Ui::FlatLabel, measures line widths, and replaces normal text painting with rounded placeholder bars plus a sliding gradient while active. ui/…/premium_star.h and .cpp wrap a 3D star renderer in an RpWidget, creating a QRhi-backed GL surface when supported, freezing to an image when paused, tracking yaw/pitch/bob/shimmer/fade, responding to drag/fling gestures, and driving idle gestures through Ui::Animations::Basic. These effects should be treated as paint-layer widgets: callers own placement and lifetime, while the effect owns frame scheduling and repaint requests.
Poll helpers under poll/** are a cross-section of how feature screens compose the toolkit. poll/poll_media_upload.h and .cpp define PollMediaState, PollMediaButton, file validation and preparation helpers, upload context, and PollMediaUploader. PollMediaButton is a RippleButton that paints attach icons, thumbnails, link overlays, upload radial progress, and cancel/view transitions from a shared PollMediaState; the uploader converts drag/drop or file-picker data into prepared media, uploads via MTProto/API helpers, then updates PollMediaState so the UI repaint path stays declarative. boxes/create_poll_box.cpp imports these helpers to add media buttons to option rows and to refresh stale media before submit.
Coupling
- If a style constant, palette color, or generated style resource changes, verify cached painters that subscribe to
style::PaletteChanged()are updated or invalidated: ui/cached_round_corners.cpp refreshes global corner pixmaps, inline_bots/inline_results_widget.cpp refreshes inline panel rounding, poll/poll_link_thumbnail.cpp checksstyle::PaletteVersion(), and ui/…/message_bar.cpp clears cached gradients. Missing an invalidation produces stale colors until restart. - If the device-pixel-ratio or image preparation contract changes, verify all image caches continue to key by physical size and options: ui/…/image.cpp, ui/cached_round_corners.cpp, ui/empty_userpic.cpp, ui/userpic_view.cpp, and poll/poll_media_upload.cpp all multiply logical sizes by
style::DevicePixelRatio()before caching or painting. A mismatch will show blurry or incorrectly sized pixmaps on high-DPI displays. - If
PeerListRowpainting, geometry, or state hooks change in boxes/peer_list_box.h, verify both fullPeerListBoxcontent and the lighterPeerListWidgetsadapter in boxes/peer_list_widgets.cpp. The adapter calls the same row hooks but does not implement search/prepend/remove/hidden behavior, so adding a required row lifecycle callback can crash there viaUnexpected(...). - If userpic shape, palette, or override behavior changes, update both placeholder and cloud-image paths: ui/userpic_view.cpp caches shape/palette/Ayu state, ui/empty_userpic.cpp paints placeholder shapes and special avatars, and boxes/peer_list_box.cpp may force-circle peer photos for row callbacks. Updating only one path makes placeholders and loaded photos disagree.
- If text parse options or chat width constants change, call paths that depend on
Ui::InitTextOptions()must be checked: ui/…/text_options.cpp computes dialog and webpage limits from styles/style_chat.h, while ui/…/message_bar.cpp usesUi::DialogTextOptions()for bar bodies and peer-list rows use name/dialog text options. Wrong limits cause inconsistent elision, wrapping, or custom emoji placement. - If
PollMediaStatefields or upload semantics change, verify all mutators call the state update callback: poll/poll_media_upload.cpp setsPollMediaState::updatefromPollMediaButton, and boxes/create_poll_box.cpp relies on sharedPollMediaStateobjects to keep option-row buttons, validation, and stale-media refresh in sync. - If inline result item dimensions or positions change, keep layout/layout_mosaic.cpp and inline_bots/inline_bot_layout_item.cpp in sync with repaint/layout callbacks.
ItemBase::update()andlayoutChanged()only notify the inline widget when_position >= 0; clearing rows inAbstractMosaicLayout::clearRows(false)marks items removed by setting position to-1. - If layer presentation is changed, check both main-window and standalone paths: boxes/abstract_box.cpp delegates to
Core::App().activePrimaryWindow(), while ui/…/standalone_layer_stack.cpp creates separate top-level panels and intentionally supports onlyBoxContent, not arbitraryLayerWidgetinstances.
Risks
- ui/cached_round_corners.cpp, ui/…/message_bubble.cpp, and inline_bots/inline_results_widget.cpp duplicate rounded-corner assumptions across cached corner pixmaps, bubble masks, and panel painting. If a radius or corner ordering changes in one path, bubbles/panels can develop visible seams or wrong-tail masks.
- boxes/peer_list_widgets.cpp implements many
PeerListDelegatemethods asUnexpected(...). If a controller used withPeerListWidgetsbegins using search rows, prepends, removal, hidden rows, or multi-select callbacks, the UI will terminate instead of degrading gracefully. - ui/…/standalone_layer_stack.cpp logs and ignores attempts to show a raw
LayerWidget. A feature that works throughUi::Showin the main window can silently do nothing in standalone mode if it sends a non-box layer. - poll/poll_media_upload.cpp stores UI repaint/reupload callbacks inside shared
PollMediaState. If multiplePollMediaButtoninstances share the same state or a state outlives its button unexpectedly, the last installed callback wins and older buttons may stop updating. - ui/…/premium_star.cpp depends on Qt 6.7 QRhi support and freezes by grabbing the GL framebuffer. On unsupported Qt/backend combinations
Star::Supported()is false andensureSurface()creates no surface, so callers must provide fallback layout/visibility rather than assuming a rendered star.