1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187
  188
  189
  190
  191
  192
  193
  194
  195
  196
  197
  198
  199
  200
  201
  202
  203
  204
  205
  206
  207
  208
  209
  210
  211
  212
  213
  214
  215
  216
  217
  218
  219
  220
  221
  222
  223
  224
  225
  226
  227
  228
  229
  230
  231
  232
  233
  234
  235
  236
  237
  238
  239
  240
  241
  242
  243
  244
  245
  246
  247
  248
  249
  250
  251
  252
  253
  254
  255
  256
  257
  258
  259
  260
  261
  262
  263
  264
  265
  266
  267
  268
  269
  270
  271
  272
  273
  274
  275
  276
  277
  278
  279
  280
  281
  282
  283
  284
  285
  286
  287
  288
  289
  290
  291
  292
  293
  294
  295
  296
  297
  298
  299
  300
  301
  302
  303
  304
  305
  306
  307
  308
  309
  310
  311
  312
  313
  314
  315
  316
  317
  318
  319
  320
  321
  322
  323
  324
  325
  326
  327
  328
  329
  330
  331
  332
  333
  334
  335
  336
  337
  338
  339
  340
  341
  342
  343
  344
  345
  346
  347
  348
  349
  350
  351
  352
  353
  354
  355
  356
  357
  358
  359
  360
  361
  362
  363
  364
  365
  366
  367
  368
  369
  370
  371
  372
  373
  374
  375
  376
  377
  378
  379
  380
  381
  382
  383
  384
  385
  386
  387
  388
  389
  390
  391
  392
  393
  394
  395
  396
  397
  398
  399
  400
  401
  402
  403
  404
  405
  406
  407
  408
  409
  410
  411
  412
  413
  414
  415
  416
  417
  418
  419
  420
  421
  422
  423
  424
  425
  426
  427
  428
  429
  430
  431
  432
  433
  434
  435
  436
  437
  438
  439
  440
  441
  442
  443
  444
  445
  446
  447
  448
  449
  450
  451
  452
  453
  454
  455
  456
  457
  458
  459
  460
  461
  462
  463
  464
  465
  466
  467
  468
  469
  470
  471
  472

ash / game_dashboard / game_dashboard_toolbar_view.cc [blame]

// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/game_dashboard/game_dashboard_toolbar_view.h"

#include <memory>

#include "ash/app_list/app_list_util.h"
#include "ash/capture_mode/capture_mode_controller.h"
#include "ash/capture_mode/capture_mode_util.h"
#include "ash/constants/ash_features.h"
#include "ash/game_dashboard/game_dashboard_context.h"
#include "ash/game_dashboard/game_dashboard_controller.h"
#include "ash/game_dashboard/game_dashboard_metrics.h"
#include "ash/game_dashboard/game_dashboard_utils.h"
#include "ash/public/cpp/window_properties.h"
#include "ash/resources/vector_icons/vector_icons.h"
#include "ash/strings/grit/ash_strings.h"
#include "ash/style/icon_button.h"
#include "ash/style/system_shadow.h"
#include "base/check.h"
#include "base/types/cxx23_to_underlying.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/chromeos/styles/cros_tokens_color_mappings.h"
#include "ui/color/color_id.h"
#include "ui/compositor/layer.h"
#include "ui/events/event_handler.h"
#include "ui/events/keycodes/keyboard_codes_posix.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/geometry/vector2d_conversions.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/highlight_border.h"
#include "ui/views/widget/widget.h"

namespace ash {

namespace {

// Corner radius of the toolbar view.
constexpr int kCornerRadius = 20;
// Horizontal inset for the border around the toolbar.
constexpr int kHorizontalInset = 4;
// Vertical inset for the border around the toolbar.
constexpr int kVerticalInset = 4;
// Padding between children in the toolbar.
constexpr int kBetweenChildSpacing = 4;

std::unique_ptr<IconButton> CreateIconButton(
    base::RepeatingClosure callback,
    const gfx::VectorIcon* icon,
    int view_id,
    const std::u16string& text,
    bool is_togglable,
    ui::ColorId icon_color = cros_tokens::kCrosSysOnSurface) {
  // TODO(b/290696780): Update logic so the toolbar can drag from icon buttons.
  auto button = std::make_unique<IconButton>(
      std::move(callback), IconButton::Type::kMedium, icon, text,
      /*is_togglable=*/is_togglable, /*has_border=*/true);
  button->SetID(view_id);
  button->SetIconColor(icon_color);
  button->SetBackgroundColor(SK_ColorTRANSPARENT);
  return button;
}

GameDashboardToolbarSnapLocation CalculateGameDashboardToolbarSnapLocation(
    const gfx::Point& toolbar_center_point,
    const gfx::Rect& game_window_screen_bounds) {
  const auto game_window_center = game_window_screen_bounds.CenterPoint();
  if (toolbar_center_point.x() < game_window_center.x()) {
    return toolbar_center_point.y() < game_window_center.y()
               ? GameDashboardToolbarSnapLocation::kTopLeft
               : GameDashboardToolbarSnapLocation::kBottomLeft;
  }
  return toolbar_center_point.y() < game_window_center.y()
             ? GameDashboardToolbarSnapLocation::kTopRight
             : GameDashboardToolbarSnapLocation::kBottomRight;
}

GameDashboardToolbarSnapLocation GetNextHorizontalSnapLocation(
    GameDashboardToolbarSnapLocation current,
    bool going_left) {
  switch (current) {
    case GameDashboardToolbarSnapLocation::kTopLeft:
      return going_left ? current : GameDashboardToolbarSnapLocation::kTopRight;
    case GameDashboardToolbarSnapLocation::kTopRight:
      return going_left ? GameDashboardToolbarSnapLocation::kTopLeft : current;
    case GameDashboardToolbarSnapLocation::kBottomLeft:
      return going_left ? current
                        : GameDashboardToolbarSnapLocation::kBottomRight;
    case GameDashboardToolbarSnapLocation::kBottomRight:
      return going_left ? GameDashboardToolbarSnapLocation::kBottomLeft
                        : current;
  }
}

GameDashboardToolbarSnapLocation GetNextVerticalSnapLocation(
    GameDashboardToolbarSnapLocation current,
    bool going_up) {
  switch (current) {
    case GameDashboardToolbarSnapLocation::kTopLeft:
      return going_up ? current : GameDashboardToolbarSnapLocation::kBottomLeft;
    case GameDashboardToolbarSnapLocation::kTopRight:
      return going_up ? current
                      : GameDashboardToolbarSnapLocation::kBottomRight;
    case GameDashboardToolbarSnapLocation::kBottomLeft:
      return going_up ? GameDashboardToolbarSnapLocation::kTopLeft : current;
    case GameDashboardToolbarSnapLocation::kBottomRight:
      return going_up ? GameDashboardToolbarSnapLocation::kTopRight : current;
  }
}

}  // namespace

// ToolbarDragHandler is an EventHandler that keeps track of touch and mouse
// input for the purposes of determining when dragging should occur. It also is
// responsible for passing along events to notify the toolbar when a button
// click has occurred.
class ToolbarDragHandler : public ui::EventHandler {
 public:
  explicit ToolbarDragHandler(GameDashboardToolbarView* toolbar_view)
      : toolbar_view_(toolbar_view) {}
  ~ToolbarDragHandler() override = default;

  // ui::EventHandler:
  void OnMouseEvent(ui::MouseEvent* event) override {
    const gfx::PointF event_location =
        capture_mode_util::GetEventScreenLocation(*event);

    switch (event->type()) {
      case ui::EventType::kMousePressed:
        is_dragging_ = false;
        previous_location_in_screen_ = event_location;
        break;
      case ui::EventType::kMouseDragged:
        if (!is_dragging_) {
          // It's confirmed that the user is trying to drag rather than press a
          // button in the toolbar.
          is_dragging_ = true;
        }
        DCHECK(is_dragging_)
            << "Received OnMouseDragged event but the toolbar isn't dragging.";
        toolbar_view_->RepositionToolbar(GetOffset(event_location));
        previous_location_in_screen_ = event_location;
        break;
      case ui::EventType::kMouseReleased:
        if (!is_dragging_) {
          // Allow the toolbar to receive this event so it can handle any button
          // clicks.
          return;
        }

        // The toolbar was dragged, so consume this event to ensure the toolbar
        // button doesn't process any button clicks.
        is_dragging_ = false;
        toolbar_view_->EndDraggingToolbar(GetOffset(event_location));
        previous_location_in_screen_.SetPoint(0, 0);
        break;
      default:
        // Don't stop events from being received on any other mouse events.
        return;
    }

    event->StopPropagation();
    event->SetHandled();
  }

  void OnGestureEvent(ui::GestureEvent* event) override {
    const gfx::PointF event_location =
        capture_mode_util::GetEventScreenLocation(*event);

    switch (event->type()) {
      case ui::EventType::kGestureScrollBegin:
        is_dragging_ = true;
        previous_location_in_screen_ = event_location;
        break;
      case ui::EventType::kGestureScrollUpdate:
        DCHECK(is_dragging_)
            << "Received EventType::kGestureScrollUpdate event but the "
               "toolbar isn't dragging.";
        toolbar_view_->RepositionToolbar(GetOffset(event_location));
        previous_location_in_screen_ = event_location;
        break;
      case ui::EventType::kGestureEnd:
        if (!is_dragging_) {
          // Pass along event if it occurred outside of a dragging instance.
          return;
        }
        // Treat dragging `ui::EventType::kGestureEnd` events the same as
        // `ui::EventType::kGestureScrollEnd` events.
        [[fallthrough]];
      case ui::EventType::kGestureScrollEnd:
        DCHECK(is_dragging_) << "Attempting to call end drag logic but the "
                                "toolbar wasn't dragging. Event = "
                             << base::to_underlying(event->type());
        is_dragging_ = false;
        toolbar_view_->EndDraggingToolbar(GetOffset(event_location));
        previous_location_in_screen_.SetPoint(0, 0);
        break;
      default:
        // Don't stop events from being received on any other gesture events.
        return;
    }

    event->StopPropagation();
    event->SetHandled();
  }

 private:
  // Determines the offset from the current event and the previous event
  // location.
  gfx::Vector2d GetOffset(const gfx::PointF& event_location) const {
    return gfx::ToRoundedVector2d(event_location -
                                  previous_location_in_screen_);
  }

  // Allows this class to access `GameDashboardToolbarView` owned functions.
  const raw_ptr<GameDashboardToolbarView> toolbar_view_;

  // The location of the previous drag event in screen coordinates.
  gfx::PointF previous_location_in_screen_;

  // If the toolbar view is in the dragging state.
  bool is_dragging_ = false;
};

GameDashboardToolbarView::GameDashboardToolbarView(
    GameDashboardContext* context)
    : context_(context) {
  DCHECK(context_);
  DCHECK(context_->game_window());

  drag_handler_ = std::make_unique<ToolbarDragHandler>(this);
  AddPreTargetHandler(drag_handler_.get(), ui::EventTarget::Priority::kSystem);

  SetOrientation(views::BoxLayout::Orientation::kVertical);
  SetInsideBorderInsets(gfx::Insets::VH(kVerticalInset, kHorizontalInset));
  SetBetweenChildSpacing(kBetweenChildSpacing);
  SetCrossAxisAlignment(views::BoxLayout::CrossAxisAlignment::kCenter);
  SetBackground(views::CreateThemedRoundedRectBackground(
      cros_tokens::kCrosSysSystemBaseElevatedOpaque, kCornerRadius));
  SetBorder(views::CreateThemedRoundedRectBorder(
      1, kCornerRadius, ui::ColorIds::kColorCrosSystemHighlightBorder));
  shadow_ = SystemShadow::CreateShadowOnNinePatchLayerForView(
      this, SystemShadow::Type::kElevation12);
  shadow_->SetRoundedCornerRadius(kCornerRadius);

  AddShortcutTiles();
}

GameDashboardToolbarView::~GameDashboardToolbarView() = default;

void GameDashboardToolbarView::OnRecordingStarted(
    bool is_recording_game_window) {
  UpdateRecordGameButton(is_recording_game_window);
}

void GameDashboardToolbarView::OnRecordingEnded() {
  UpdateRecordGameButton(/*is_recording_game_window=*/false);
}

void GameDashboardToolbarView::RepositionToolbar(const gfx::Vector2d& offset) {
  // Verify toolbar isn't outside game window bounds.
  auto* widget = GetWidget();
  gfx::Rect current_bounds = widget->GetWindowBoundsInScreen();
  // TODO(b/295536243): Update offset to handle dragging outside game window.
  current_bounds.Offset(offset);
  capture_mode_util::AdjustBoundsWithinConfinedBounds(
      context_->game_window()->GetBoundsInScreen(), current_bounds);
  widget->SetBounds(current_bounds);
}

void GameDashboardToolbarView::EndDraggingToolbar(const gfx::Vector2d& offset) {
  RepositionToolbar(offset);
  context_->SetGameDashboardToolbarSnapLocation(
      CalculateGameDashboardToolbarSnapLocation(
          GetWidget()->GetWindowBoundsInScreen().CenterPoint(),
          context_->game_window()->GetBoundsInScreen()));
}

void GameDashboardToolbarView::UpdateViewForGameControls(
    ArcGameControlsFlag flags) {
  DCHECK(game_controls_button_);

  auto* widget = GetWidget();
  if (game_dashboard_utils::IsFlagSet(flags, ArcGameControlsFlag::kEdit)) {
    CHECK(widget);
    widget->Hide();
  } else {
    // Show the widget in an inactive state.
    if (widget) {
      // `widget` is null when this function is indirectly called from the
      // constructor.
      widget->ShowInactive();
    }

    // Update game_controls_button_.
    game_dashboard_utils::UpdateGameControlsHintButton(game_controls_button_,
                                                       flags);
  }
}

bool GameDashboardToolbarView::OnKeyPressed(const ui::KeyEvent& event) {
  const auto current_snap_location = context_->toolbar_snap_location();
  const auto event_key_code = event.key_code();
  switch (event_key_code) {
    case ui::VKEY_LEFT:
    case ui::VKEY_RIGHT:
      context_->SetGameDashboardToolbarSnapLocation(
          GetNextHorizontalSnapLocation(
              current_snap_location,
              /*going_left=*/event_key_code == ui::VKEY_LEFT));
      return true;
    case ui::VKEY_UP:
    case ui::VKEY_DOWN:
      context_->SetGameDashboardToolbarSnapLocation(GetNextVerticalSnapLocation(
          current_snap_location, /*going_up=*/event_key_code == ui::VKEY_UP));
      return true;
    default:
      return false;
  }
}

bool GameDashboardToolbarView::OnKeyReleased(const ui::KeyEvent& event) {
  return IsArrowKeyEvent(event);
}

void GameDashboardToolbarView::OnGamepadButtonPressed() {
  is_expanded_ = !is_expanded_;
  for (View* child : children()) {
    if (child != gamepad_button_) {
      child->SetVisible(is_expanded_);
    }
  }
  UpdateGamepadButtonTooltipText();
  RecordGameDashboardToolbarClickToExpandState(context_->app_id(),
                                               is_expanded_);
  context_->MaybeUpdateToolbarWidgetBounds();
}

void GameDashboardToolbarView::OnGameControlsButtonPressed() {
  auto* game_window = context_->game_window();
  const bool was_toggled = game_controls_button_->toggled();
  game_window->SetProperty(
      kArcGameControlsFlagsKey,
      game_dashboard_utils::UpdateFlag(
          game_window->GetProperty(kArcGameControlsFlagsKey),
          static_cast<ArcGameControlsFlag>(ArcGameControlsFlag::kHint),
          /*enable_flag=*/!was_toggled));
  RecordGameDashboardControlsHintToggleSource(
      context_->app_id(), GameDashboardMenu::kToolbar, !was_toggled);
}

void GameDashboardToolbarView::OnRecordButtonPressed() {
  context_->set_recording_from_main_menu(false);

  if (record_game_button_->toggled()) {
    CaptureModeController::Get()->EndVideoRecording(
        EndRecordingReason::kGameToolbarStopRecordingButton);
  } else {
    GameDashboardController::Get()->StartCaptureSession(context_);
  }
}

void GameDashboardToolbarView::OnScreenshotButtonPressed() {
  CaptureModeController::Get()->CaptureScreenshotOfGivenWindow(
      context_->game_window());

  RecordGameDashboardScreenshotTakeSource(context_->app_id(),
                                          GameDashboardMenu::kToolbar);
}

void GameDashboardToolbarView::AddShortcutTiles() {
  // The gamepad button should always be the first icon added to the toolbar.
  gamepad_button_ = AddChildView(CreateIconButton(
      base::BindRepeating(&GameDashboardToolbarView::OnGamepadButtonPressed,
                          base::Unretained(this)),
      &kGdToolbarIcon, base::to_underlying(ToolbarViewId::kGamepadButton),
      l10n_util::GetStringUTF16(
          IDS_ASH_GAME_DASHBOARD_TOOLBAR_TILE_BUTTON_TITLE),
      /*is_togglable=*/false, /*icon_color=*/cros_tokens::kCrosSysPrimary));
  gamepad_button_->GetViewAccessibility().SetRole(ax::mojom::Role::kButton);

  UpdateGamepadButtonTooltipText();
  MayAddGameControlsTile();

  if (base::FeatureList::IsEnabled(
          features::kFeatureManagementGameDashboardRecordGame)) {
    record_game_button_ = AddChildView(CreateIconButton(
        base::BindRepeating(&GameDashboardToolbarView::OnRecordButtonPressed,
                            base::Unretained(this)),
        &kGdRecordGameIcon,
        base::to_underlying(ToolbarViewId::kScreenRecordButton),
        l10n_util::GetStringUTF16(
            IDS_ASH_GAME_DASHBOARD_RECORD_GAME_TILE_BUTTON_TITLE),
        /*is_togglable=*/true));
    record_game_button_->GetViewAccessibility().SetRole(
        ax::mojom::Role::kButton);
    record_game_button_->SetVectorIcon(kGdRecordGameIcon);
    record_game_button_->SetBackgroundToggledColor(cros_tokens::kCrosSysError);
    record_game_button_->SetToggledVectorIcon(kCaptureModeCircleStopIcon);
    record_game_button_->SetIconToggledColor(cros_tokens::kCrosSysOnError);
    UpdateRecordGameButton(
        GameDashboardController::Get()->active_recording_context() == context_);
  }

  auto* screenshot_button = AddChildView(CreateIconButton(
      base::BindRepeating(&GameDashboardToolbarView::OnScreenshotButtonPressed,
                          base::Unretained(this)),
      &kGdScreenshotIcon, base::to_underlying(ToolbarViewId::kScreenshotButton),
      l10n_util::GetStringUTF16(
          IDS_ASH_GAME_DASHBOARD_SCREENSHOT_TILE_BUTTON_TITLE),
      /*is_togglable=*/false));
  screenshot_button->SetTooltipText(l10n_util::GetStringUTF16(
      IDS_ASH_GAME_DASHBOARD_SCREENSHOT_TILE_BUTTON_TITLE));
}

void GameDashboardToolbarView::MayAddGameControlsTile() {
  auto flags =
      game_dashboard_utils::GetGameControlsFlag(context_->game_window());
  if (!flags) {
    return;
  }

  game_controls_button_ = AddChildView(CreateIconButton(
      base::BindRepeating(
          &GameDashboardToolbarView::OnGameControlsButtonPressed,
          base::Unretained(this)),
      /*icon=*/&kGdGameControlsIcon,
      base::to_underlying(ToolbarViewId::kGameControlsButton),
      l10n_util::GetStringUTF16(
          IDS_ASH_GAME_DASHBOARD_CONTROLS_TILE_BUTTON_TITLE),
      /*is_togglable=*/true));
  game_controls_button_->GetViewAccessibility().SetRole(
      ax::mojom::Role::kButton);

  UpdateViewForGameControls(*flags);
}

void GameDashboardToolbarView::UpdateRecordGameButton(
    bool is_recording_game_window) {
  if (!record_game_button_) {
    return;
  }

  record_game_button_->SetEnabled(
      is_recording_game_window ||
      CaptureModeController::Get()->can_start_new_recording());
  record_game_button_->SetToggled(is_recording_game_window);
  record_game_button_->SetTooltipText(l10n_util::GetStringUTF16(
      is_recording_game_window
          ? IDS_ASH_GAME_DASHBOARD_RECORD_GAME_TILE_TOOLTIPS_RECORD_STOP
          : IDS_ASH_GAME_DASHBOARD_RECORD_GAME_TILE_TOOLTIPS_RECORD_START));
}

void GameDashboardToolbarView::UpdateGamepadButtonTooltipText() {
  gamepad_button_->SetTooltipText(l10n_util::GetStringUTF16(
      is_expanded_
          ? IDS_ASH_GAME_DASHBOARD_TOOLBAR_TILE_TOOLTIPS_CLOSE_TOOLBAR
          : IDS_ASH_GAME_DASHBOARD_TOOLBAR_TILE_TOOLTIPS_OPEN_TOOLBAR));
}

BEGIN_METADATA(GameDashboardToolbarView)
END_METADATA

}  // namespace ash