code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/test/mock_platform_window_delegate.h" namespace ui { MockPlatformWindowDelegate::MockPlatformWindowDelegate() {} MockPlatformWindowDelegate::~MockPlatformWindowDelegate() {} bool operator==(const PlatformWindowDelegate::BoundsChange& a, const PlatformWindowDelegate::BoundsChange& b) { return a.origin_changed == b.origin_changed; } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/ozone/test/mock_platform_window_delegate.cc
C++
unknown
538
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_OZONE_TEST_MOCK_PLATFORM_WINDOW_DELEGATE_H_ #define UI_OZONE_TEST_MOCK_PLATFORM_WINDOW_DELEGATE_H_ #include "testing/gmock/include/gmock/gmock.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/owned_window_anchor.h" #include "ui/base/ui_base_types.h" #include "ui/gfx/geometry/rect.h" #include "ui/platform_window/platform_window_delegate.h" namespace ui { class MockPlatformWindowDelegate : public PlatformWindowDelegate { public: MockPlatformWindowDelegate(); MockPlatformWindowDelegate(const MockPlatformWindowDelegate&) = delete; MockPlatformWindowDelegate& operator=(const MockPlatformWindowDelegate&) = delete; ~MockPlatformWindowDelegate() override; MOCK_METHOD1(OnBoundsChanged, void(const BoundsChange& change)); MOCK_METHOD1(OnDamageRect, void(const gfx::Rect& damaged_region)); MOCK_METHOD1(DispatchEvent, void(Event* event)); MOCK_METHOD0(OnCloseRequest, void()); MOCK_METHOD0(OnClosed, void()); MOCK_METHOD2(OnWindowStateChanged, void(PlatformWindowState old_state, PlatformWindowState new_state)); #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) MOCK_METHOD1(OnWindowTiledStateChanged, void(WindowTiledEdges new_tiled_edges)); #endif MOCK_METHOD0(OnLostCapture, void()); MOCK_METHOD1(OnAcceleratedWidgetAvailable, void(gfx::AcceleratedWidget widget)); MOCK_METHOD0(OnWillDestroyAcceleratedWidget, void()); MOCK_METHOD0(OnAcceleratedWidgetDestroyed, void()); MOCK_METHOD1(OnActivationChanged, void(bool active)); MOCK_METHOD0(GetMinimumSizeForWindow, absl::optional<gfx::Size>()); MOCK_METHOD0(GetMaximumSizeForWindow, absl::optional<gfx::Size>()); MOCK_METHOD0(GetMenuType, absl::optional<MenuType>()); MOCK_METHOD0(GetOwnedWindowAnchorAndRectInDIP, absl::optional<OwnedWindowAnchor>()); MOCK_METHOD0(OnMouseEnter, void()); MOCK_METHOD1(OnImmersiveModeChanged, void(bool immersive)); }; bool operator==(const PlatformWindowDelegate::BoundsChange& a, const PlatformWindowDelegate::BoundsChange& b); } // namespace ui #endif // UI_OZONE_TEST_MOCK_PLATFORM_WINDOW_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/ozone/test/mock_platform_window_delegate.h
C++
unknown
2,336
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" #include "mojo/core/embedder/configuration.h" #include "mojo/core/embedder/embedder.h" int main(int argc, char** argv) { base::TestSuite test_suite(argc, argv); mojo::core::Init(mojo::core::Configuration()); return base::LaunchUnitTestsSerially( argc, argv, base::BindOnce(&base::TestSuite::Run, base::Unretained(&test_suite))); }
Zhao-PengFei35/chromium_src_4
ui/ozone/test/ozone_integration_tests_main.cc
C++
unknown
580
include_rules = [ "+gmock", ]
Zhao-PengFei35/chromium_src_4
ui/ozone/testhelpers/DEPS
Python
unknown
32
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_OZONE_TESTHELPERS_MOCK_GESTURE_PROPERTIES_SERVICE_H_ #define UI_OZONE_TESTHELPERS_MOCK_GESTURE_PROPERTIES_SERVICE_H_ #include "gmock/gmock.h" #include "ui/ozone/public/mojom/gesture_properties_service.mojom.h" // Mock of GesturePropertiesService's C++ bindings, useful for tests. class MockGesturePropertiesService : public ui::ozone::mojom::GesturePropertiesService { public: MockGesturePropertiesService(); ~MockGesturePropertiesService() override; MOCK_METHOD1(ListDevices, void(ListDevicesCallback)); MOCK_METHOD2(ListProperties, void(int32_t, ListPropertiesCallback)); MOCK_METHOD3(GetProperty, void(int32_t, const std::string&, GetPropertyCallback)); MOCK_METHOD4(SetProperty, void(int32_t, const std::string&, ui::ozone::mojom::GesturePropValuePtr, SetPropertyCallback)); }; // Work around the compile error '[chromium-style] Complex class/struct needs an // explicit out-of-line constructor.' inline MockGesturePropertiesService::MockGesturePropertiesService() = default; inline MockGesturePropertiesService::~MockGesturePropertiesService() = default; #endif // UI_OZONE_TESTHELPERS_MOCK_GESTURE_PROPERTIES_SERVICE_H_
Zhao-PengFei35/chromium_src_4
ui/ozone/testhelpers/mock_gesture_properties_service.h
C++
unknown
1,394
include_rules = [ "+third_party/skia/include", "+ui/base", "+ui/display", "+ui/gfx", ]
Zhao-PengFei35/chromium_src_4
ui/platform_window/DEPS
Python
unknown
95
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/common/platform_window_defaults.h" namespace ui { namespace { bool g_use_test_config = false; } // namespace bool UseTestConfigForPlatformWindows() { return g_use_test_config; } namespace test { void EnableTestConfigForPlatformWindows() { g_use_test_config = true; } } // namespace test } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/common/platform_window_defaults.cc
C++
unknown
492
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_COMMON_PLATFORM_WINDOW_DEFAULTS_H_ #define UI_PLATFORM_WINDOW_COMMON_PLATFORM_WINDOW_DEFAULTS_H_ #include "base/component_export.h" namespace ui { // Returns true if PlatformWindow should use test configuration. Will return // false by default, unless test::EnableTestConfigForPlatformWindows() has been // called, then it will return true. COMPONENT_EXPORT(PLATFORM_WINDOW_COMMON) bool UseTestConfigForPlatformWindows(); namespace test { // Sets that PlatformWindow should use test configuration. This can safely be // called on all platforms but only has an effect for X11 and Wayland. // For X11 this sets the value of the |override_redirect| attribute used when // creating an X11 window to true. It is necessary to set this flag on for // various tests, otherwise the call to Show() blocks because it never receives // the MapNotify event. It is unclear why this is necessary, but might be // related to calls to XInitThreads(). // // For Wayland, forces visual size updates on every configuration event. COMPONENT_EXPORT(PLATFORM_WINDOW_COMMON) void EnableTestConfigForPlatformWindows(); } // namespace test } // namespace ui #endif // UI_PLATFORM_WINDOW_COMMON_PLATFORM_WINDOW_DEFAULTS_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/common/platform_window_defaults.h
C++
unknown
1,378
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/extensions/desk_extension.h" #include "ui/base/class_property.h" #include "ui/platform_window/platform_window.h" DEFINE_UI_CLASS_PROPERTY_TYPE(ui::DeskExtension*) namespace ui { DEFINE_UI_CLASS_PROPERTY_KEY(DeskExtension*, kDeskExtensionKey, nullptr) DeskExtension::~DeskExtension() = default; void DeskExtension::SetDeskExtension(PlatformWindow* window, DeskExtension* extension) { window->SetProperty(kDeskExtensionKey, extension); } DeskExtension* GetDeskExtension(const PlatformWindow& window) { return window.GetProperty(kDeskExtensionKey); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/desk_extension.cc
C++
unknown
789
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_EXTENSIONS_DESK_EXTENSION_H_ #define UI_PLATFORM_WINDOW_EXTENSIONS_DESK_EXTENSION_H_ #include <string> #include "base/component_export.h" namespace ui { class PlatformWindow; // A desk extension that platforms can use to add support for virtual desktop. // The APIs currently match with what ash provides from desks_controller to // support "Move window to desk" menu in LaCrOS. // TODO(crbug.com/1214795): Support virtual desktop protocol for linux/wayland // as well. class COMPONENT_EXPORT(PLATFORM_WINDOW) DeskExtension { public: // Returns the current number of desks. virtual int GetNumberOfDesks() const = 0; // Returns the active desk index for window. virtual int GetActiveDeskIndex() const = 0; // Returns the name of the desk at |index|. virtual std::u16string GetDeskName(int index) const = 0; // Requests the underneath platform to send the window to a desk at |index|. // |index| must be valid. virtual void SendToDeskAtIndex(int index) = 0; protected: virtual ~DeskExtension(); // Sets the pointer to the extension as a property of the PlatformWindow. void SetDeskExtension(PlatformWindow* window, DeskExtension* extension); }; COMPONENT_EXPORT(PLATFORM_WINDOW) DeskExtension* GetDeskExtension(const PlatformWindow& window); } // namespace ui #endif // UI_PLATFORM_WINDOW_EXTENSIONS_DESK_EXTENSION_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/desk_extension.h
C++
unknown
1,528
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/extensions/pinned_mode_extension.h" #include "ui/base/class_property.h" #include "ui/platform_window/platform_window.h" DEFINE_UI_CLASS_PROPERTY_TYPE(ui::PinnedModeExtension*) namespace ui { DEFINE_UI_CLASS_PROPERTY_KEY(PinnedModeExtension*, kPinnedModeExtensionKey, nullptr) PinnedModeExtension::~PinnedModeExtension() = default; void PinnedModeExtension::SetPinnedModeExtension( PlatformWindow* window, PinnedModeExtension* extension) { window->SetProperty(kPinnedModeExtensionKey, extension); } PinnedModeExtension* GetPinnedModeExtension(const PlatformWindow& window) { return window.GetProperty(kPinnedModeExtensionKey); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/pinned_mode_extension.cc
C++
unknown
898
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_EXTENSIONS_PINNED_MODE_EXTENSION_H_ #define UI_PLATFORM_WINDOW_EXTENSIONS_PINNED_MODE_EXTENSION_H_ #include "base/component_export.h" namespace ui { class PlatformWindow; // A pinned mode extension that platforms can use to add support for pinned // mode operations which are used e.g. in EDU tests / quizzes. class COMPONENT_EXPORT(PLATFORM_WINDOW) PinnedModeExtension { public: // Pins/locks a window to the screen so that the user cannot do anything // else before the mode is released. If trusted is set, it is an invocation // from a trusted app like a school test mode app. virtual void Pin(bool trusted) = 0; // Releases the pinned mode and allows the user to do other things again. virtual void Unpin() = 0; protected: virtual ~PinnedModeExtension(); // Sets the pointer to the extension as a property of the PlatformWindow. static void SetPinnedModeExtension(PlatformWindow* window, PinnedModeExtension* extension); }; COMPONENT_EXPORT(PLATFORM_WINDOW) PinnedModeExtension* GetPinnedModeExtension(const PlatformWindow& window); } // namespace ui #endif // UI_PLATFORM_WINDOW_EXTENSIONS_PINNED_MODE_EXTENSION_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/pinned_mode_extension.h
C++
unknown
1,360
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/extensions/system_modal_extension.h" #include "ui/base/class_property.h" #include "ui/platform_window/platform_window.h" DEFINE_UI_CLASS_PROPERTY_TYPE(ui::SystemModalExtension*) namespace ui { DEFINE_UI_CLASS_PROPERTY_KEY(SystemModalExtension*, kSystemModalExtensionKey, nullptr) SystemModalExtension::~SystemModalExtension() = default; void SystemModalExtension::SetSystemModalExtension( PlatformWindow* window, SystemModalExtension* extension) { window->SetProperty(kSystemModalExtensionKey, extension); } SystemModalExtension* GetSystemModalExtension(const PlatformWindow& window) { return window.GetProperty(kSystemModalExtensionKey); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/system_modal_extension.cc
C++
unknown
911
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_EXTENSIONS_SYSTEM_MODAL_EXTENSION_H_ #define UI_PLATFORM_WINDOW_EXTENSIONS_SYSTEM_MODAL_EXTENSION_H_ #include "base/component_export.h" namespace ui { class PlatformWindow; class COMPONENT_EXPORT(PLATFORM_WINDOW) SystemModalExtension { public: virtual void SetSystemModal(bool modal) = 0; protected: virtual ~SystemModalExtension(); // Sets the pointer to the extension as a property of the PlatformWindow. static void SetSystemModalExtension(PlatformWindow* window, SystemModalExtension* extension); }; COMPONENT_EXPORT(PLATFORM_WINDOW) SystemModalExtension* GetSystemModalExtension(const PlatformWindow& window); } // namespace ui #endif // UI_PLATFORM_WINDOW_EXTENSIONS_SYSTEM_MODAL_EXTENSION_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/system_modal_extension.h
C++
unknown
928
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/extensions/wayland_extension.h" #include "ui/base/class_property.h" #include "ui/platform_window/platform_window.h" DEFINE_UI_CLASS_PROPERTY_TYPE(ui::WaylandExtension*) namespace ui { DEFINE_UI_CLASS_PROPERTY_KEY(WaylandExtension*, kWaylandExtensionKey, nullptr) WaylandExtension::~WaylandExtension() = default; void WaylandExtension::SetWaylandExtension(PlatformWindow* window, WaylandExtension* extension) { window->SetProperty(kWaylandExtensionKey, extension); } WaylandExtension* GetWaylandExtension(const PlatformWindow& window) { return window.GetProperty(kWaylandExtensionKey); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/wayland_extension.cc
C++
unknown
834
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_EXTENSIONS_WAYLAND_EXTENSION_H_ #define UI_PLATFORM_WINDOW_EXTENSIONS_WAYLAND_EXTENSION_H_ #include "base/component_export.h" #include "build/chromeos_buildflags.h" #include "ui/base/dragdrop/mojom/drag_drop_types.mojom-shared.h" namespace ui { class PlatformWindow; enum class WaylandWindowSnapDirection { kNone, kPrimary, kSecondary, }; enum class WaylandOrientationLockType { kAny, kNatural, kPortrait, kLandscape, kPortraitPrimary, kLandscapePrimary, kPortraitSecondary, kLandscapeSecondary, }; class COMPONENT_EXPORT(PLATFORM_WINDOW) WaylandExtension { public: // Starts a window dragging session from the owning platform window triggered // by `event_source` (kMouse or kTouch) if it is not running yet. Under // Wayland, window dragging is backed by a platform drag-and-drop session. // |allow_system_drag| indicates whether it is allowed to use a regular // drag-and-drop session if the compositor does not support the extended-drag // protocol needed to implement all window dragging features. virtual void StartWindowDraggingSessionIfNeeded( ui::mojom::DragEventSource event_source, bool allow_system_drag) = 0; #if BUILDFLAG(IS_CHROMEOS_LACROS) // Signals the underneath platform that browser is entering (or exiting) // 'immersive fullscreen mode'. // Under lacros, it controls for instance interaction with the system shelf // widget, when browser goes in fullscreen. virtual void SetImmersiveFullscreenStatus(bool status) = 0; #endif // Signals the underneath platform to shows a preview for the given window // snap direction. `allow_haptic_feedback` indicates if it should send haptic // feedback. virtual void ShowSnapPreview(WaylandWindowSnapDirection snap, bool allow_haptic_feedback) = 0; // Requests the underneath platform to snap the window in the given direction, // if not WaylandWindowSnapDirection::kNone, otherwise cancels the window // snapping. `snap_ratio` indicates the width of the work area to snap to in // landscape mode, or height in portrait mode. virtual void CommitSnap(WaylandWindowSnapDirection snap, float snap_ratio) = 0; // Signals the underneath platform whether the current tab of the browser // window can go back. The underneath platform might react, for example, // by minimizing the window upon a system wide back gesture. virtual void SetCanGoBack(bool value) = 0; // Requests the underneath platform to set the window to picture-in-picture // (PIP). virtual void SetPip() = 0; // Whether or not the underlying platform supports native pointer locking. virtual bool SupportsPointerLock() = 0; virtual void LockPointer(bool enabled) = 0; // Lock and unlock the window rotation. virtual void Lock(WaylandOrientationLockType lock_Type) = 0; virtual void Unlock() = 0; // Retrieve current layout state. virtual bool GetTabletMode() = 0; // Signals the underneath platform to float the browser window on top other // windows. virtual void SetFloat(bool value) = 0; protected: virtual ~WaylandExtension(); // Sets the pointer to the extension as a property of the PlatformWindow. void SetWaylandExtension(PlatformWindow* window, WaylandExtension* extension); }; COMPONENT_EXPORT(PLATFORM_WINDOW) WaylandExtension* GetWaylandExtension(const PlatformWindow& window); } // namespace ui #endif // UI_PLATFORM_WINDOW_EXTENSIONS_WAYLAND_EXTENSION_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/wayland_extension.h
C++
unknown
3,660
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/extensions/workspace_extension.h" #include "ui/base/class_property.h" #include "ui/platform_window/platform_window.h" DEFINE_UI_CLASS_PROPERTY_TYPE(ui::WorkspaceExtension*) namespace ui { DEFINE_UI_CLASS_PROPERTY_KEY(WorkspaceExtension*, kWorkspaceExtensionKey, nullptr) WorkspaceExtension::~WorkspaceExtension() = default; void WorkspaceExtension::SetWorkspaceExtension( PlatformWindow* platform_window, WorkspaceExtension* workspace_extension) { platform_window->SetProperty(kWorkspaceExtensionKey, workspace_extension); } WorkspaceExtension* GetWorkspaceExtension( const PlatformWindow& platform_window) { return platform_window.GetProperty(kWorkspaceExtensionKey); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/workspace_extension.cc
C++
unknown
945
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_EXTENSIONS_WORKSPACE_EXTENSION_H_ #define UI_PLATFORM_WINDOW_EXTENSIONS_WORKSPACE_EXTENSION_H_ #include <string> #include "base/component_export.h" namespace ui { class PlatformWindow; class WorkspaceExtensionDelegate; // A workspace extension that platforms can use to add support for workspaces. // This is intended to be used only in conjunction with a PlatformWindow and // owned by a PlatformWindow owner. To avoid casts from the PlatformWindow to // the WorkspaceExtension, a pointer to this interface must be set through // "SetWorkspaceExtension". class COMPONENT_EXPORT(PLATFORM_WINDOW) WorkspaceExtension { public: // Returns the workspace the PlatformWindow is located in. virtual std::string GetWorkspace() const = 0; // Sets the PlatformWindow to be visible on all workspaces. virtual void SetVisibleOnAllWorkspaces(bool always_visible) = 0; // Returns true if the PlatformWindow is visible on all // workspaces. virtual bool IsVisibleOnAllWorkspaces() const = 0; // Sets the delegate that is notified if the window has changed the workspace // it's located in. virtual void SetWorkspaceExtensionDelegate( WorkspaceExtensionDelegate* delegate) = 0; protected: virtual ~WorkspaceExtension(); // Sets the pointer to the extension as a property of the PlatformWindow. void SetWorkspaceExtension(PlatformWindow* platform_window, WorkspaceExtension* workspace_extension); }; COMPONENT_EXPORT(PLATFORM_WINDOW) WorkspaceExtension* GetWorkspaceExtension( const PlatformWindow& platform_window); } // namespace ui #endif // UI_PLATFORM_WINDOW_EXTENSIONS_WORKSPACE_EXTENSION_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/workspace_extension.h
C++
unknown
1,834
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_EXTENSIONS_WORKSPACE_EXTENSION_DELEGATE_H_ #define UI_PLATFORM_WINDOW_EXTENSIONS_WORKSPACE_EXTENSION_DELEGATE_H_ #include "base/component_export.h" namespace ui { // Notifies the delegate about changed workspace. The delegate must be set in // WorkspaceExtension to be able to receive these changes. class COMPONENT_EXPORT(PLATFORM_WINDOW) WorkspaceExtensionDelegate { public: // Notifies the delegate if the window has changed the workspace it is // located in. virtual void OnWorkspaceChanged() = 0; protected: virtual ~WorkspaceExtensionDelegate() = default; }; } // namespace ui #endif // UI_PLATFORM_WINDOW_EXTENSIONS_WORKSPACE_EXTENSION_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/workspace_extension_delegate.h
C++
unknown
843
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/extensions/x11_extension.h" #include "ui/base/class_property.h" #include "ui/platform_window/platform_window.h" DEFINE_UI_CLASS_PROPERTY_TYPE(ui::X11Extension*) namespace ui { DEFINE_UI_CLASS_PROPERTY_KEY(X11Extension*, kX11ExtensionKey, nullptr) X11Extension::~X11Extension() = default; void X11Extension::SetX11Extension(PlatformWindow* platform_window, X11Extension* x11_extension) { platform_window->SetProperty(kX11ExtensionKey, x11_extension); } X11Extension* GetX11Extension(const PlatformWindow& platform_window) { return platform_window.GetProperty(kX11ExtensionKey); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/x11_extension.cc
C++
unknown
818
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_EXTENSIONS_X11_EXTENSION_H_ #define UI_PLATFORM_WINDOW_EXTENSIONS_X11_EXTENSION_H_ #include "base/component_export.h" #include "ui/gfx/geometry/rect.h" namespace ui { class PlatformWindow; class X11ExtensionDelegate; // Linux extensions that linux platforms can use to extend the platform windows // APIs. Please refer to README for more details. // // The extension mustn't be called until PlatformWindow is initialized. class COMPONENT_EXPORT(PLATFORM_WINDOW) X11Extension { public: // Returns whether an XSync extension is available at the current platform. virtual bool IsSyncExtensionAvailable() const = 0; // Returns a best-effort guess as to whether the WM is tiling (true) or // stacking (false). virtual bool IsWmTiling() const = 0; // Handles CompleteSwapAfterResize event coming from the compositor observer. virtual void OnCompleteSwapAfterResize() = 0; // Returns the current bounds in terms of the X11 Root Window including the // borders provided by the window manager (if any). virtual gfx::Rect GetXRootWindowOuterBounds() const = 0; // Asks X11 to lower the Xwindow down the stack so that it does not obscure // any sibling windows. virtual void LowerXWindow() = 0; // Forces this window to be unmanaged by the window manager if // |override_redirect| is true. virtual void SetOverrideRedirect(bool override_redirect) = 0; // Returns true if SetOverrideRedirect() would be compatible with the WM. virtual bool CanResetOverrideRedirect() const = 0; virtual void SetX11ExtensionDelegate(X11ExtensionDelegate* delegate) = 0; protected: virtual ~X11Extension(); // Sets the pointer to the extension as a property of the PlatformWindow. void SetX11Extension(PlatformWindow* platform_window, X11Extension* x11_extensions); }; COMPONENT_EXPORT(PLATFORM_WINDOW) X11Extension* GetX11Extension(const PlatformWindow& platform_window); } // namespace ui #endif // UI_PLATFORM_WINDOW_EXTENSIONS_X11_EXTENSION_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/x11_extension.h
C++
unknown
2,175
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_EXTENSIONS_X11_EXTENSION_DELEGATE_H_ #define UI_PLATFORM_WINDOW_EXTENSIONS_X11_EXTENSION_DELEGATE_H_ #include "base/component_export.h" #include "ui/base/buildflags.h" #include "ui/gfx/geometry/rect.h" #if BUILDFLAG(USE_ATK) using AtkKeyEventStruct = struct _AtkKeyEventStruct; #endif namespace ui { class COMPONENT_EXPORT(PLATFORM_WINDOW) X11ExtensionDelegate { public: // Notifies if the PlatformWindow looses a mouse grab. This can be useful // for Wayland or X11. Both of them provide pointer enter and leave // notifications, which non-ozone X11 (just an example) use to be using to // notify about lost pointer grab along with explicit grabs. Wayland also // has this technique. However, explicit grab is available only for popup // (menu) windows. virtual void OnLostMouseGrab() = 0; #if BUILDFLAG(USE_ATK) // Notifies an ATK key event to be processed. The transient parameter will be // true if the event target is a transient window (e.g. a modal dialog) // "hanging" from our window. Return true to stop propagation of the original // key event. virtual bool OnAtkKeyEvent(AtkKeyEventStruct* atk_key_event, bool transient) = 0; #endif // Returns true if this window should be in a forced override-redirect state // (not managed by the window manager). virtual bool IsOverrideRedirect() const = 0; // Returns guessed size we will have after the switch to/from fullscreen: // - (may) avoid transient states // - works around Flash content which expects to have the size updated // synchronously. // See https://crbug.com/361408 // TODO(1096425): remove this and let this managed by X11ScreenOzone that // Ozone's X11Window should be able to access instead. This delegate method // is required as non-Ozone/X11 is not able to determine matching display // as it requires to know bounds in dip. virtual gfx::Rect GetGuessedFullScreenSizeInPx() const = 0; protected: virtual ~X11ExtensionDelegate() = default; }; } // namespace ui #endif // UI_PLATFORM_WINDOW_EXTENSIONS_X11_EXTENSION_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/extensions/x11_extension_delegate.h
C++
unknown
2,270
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "ui/platform_window/fuchsia/initialize_presenter_api_view.h" #include <lib/sys/cpp/component_context.h> #include <lib/ui/scenic/cpp/view_ref_pair.h> #include <lib/ui/scenic/cpp/view_token_pair.h> #include <zircon/rights.h> #include <utility> #include "base/fuchsia/fuchsia_logging.h" #include "base/fuchsia/process_context.h" #include "base/no_destructor.h" namespace ui { namespace fuchsia { namespace { ScenicPresentViewCallback& GetScenicViewPresenterInternal() { static base::NoDestructor<ScenicPresentViewCallback> view_presenter; return *view_presenter; } FlatlandPresentViewCallback& GetFlatlandViewPresenterInternal() { static base::NoDestructor<FlatlandPresentViewCallback> view_presenter; return *view_presenter; } } // namespace void SetScenicViewPresenter(ScenicPresentViewCallback view_presenter) { GetScenicViewPresenterInternal() = std::move(view_presenter); } const ScenicPresentViewCallback& GetScenicViewPresenter() { return GetScenicViewPresenterInternal(); } void SetFlatlandViewPresenter(FlatlandPresentViewCallback view_presenter) { GetFlatlandViewPresenterInternal() = std::move(view_presenter); } const FlatlandPresentViewCallback& GetFlatlandViewPresenter() { return GetFlatlandViewPresenterInternal(); } void IgnorePresentCallsForTest() { SetScenicViewPresenter( base::BindRepeating([](::fuchsia::ui::views::ViewHolderToken view_holder, ::fuchsia::ui::views::ViewRef view_ref) -> ::fuchsia::element::ViewControllerPtr { DCHECK(view_holder.value); DCHECK(view_ref.reference); DVLOG(1) << "Present call ignored for test."; return nullptr; })); SetFlatlandViewPresenter(base::BindRepeating( [](::fuchsia::ui::views::ViewportCreationToken viewport_creation_token) -> ::fuchsia::element::ViewControllerPtr { DCHECK(viewport_creation_token.value); DVLOG(1) << "Present call ignored for test."; return nullptr; })); } } // namespace fuchsia } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/fuchsia/initialize_presenter_api_view.cc
C++
unknown
2,218
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_FUCHSIA_INITIALIZE_PRESENTER_API_VIEW_H_ #define UI_PLATFORM_WINDOW_FUCHSIA_INITIALIZE_PRESENTER_API_VIEW_H_ #include <fuchsia/element/cpp/fidl.h> #include <fuchsia/ui/views/cpp/fidl.h> #include "base/component_export.h" #include "base/functional/callback.h" #include "ui/platform_window/platform_window_init_properties.h" namespace ui { namespace fuchsia { using ScenicPresentViewCallback = base::RepeatingCallback<::fuchsia::element::ViewControllerPtr( ::fuchsia::ui::views::ViewHolderToken, ::fuchsia::ui::views::ViewRef)>; using FlatlandPresentViewCallback = base::RepeatingCallback<::fuchsia::element::ViewControllerPtr( ::fuchsia::ui::views::ViewportCreationToken)>; // Register and exposes an API that let OzonePlatformScenic present new views. // TODO(1241868): Once workstation offers the right FIDL API to open new // windows, this can be removed. COMPONENT_EXPORT(PLATFORM_WINDOW) void SetScenicViewPresenter(ScenicPresentViewCallback view_presenter); COMPONENT_EXPORT(PLATFORM_WINDOW) const ScenicPresentViewCallback& GetScenicViewPresenter(); // Register and exposes an API that let OzonePlatformFlatland present new views. COMPONENT_EXPORT(PLATFORM_WINDOW) void SetFlatlandViewPresenter(FlatlandPresentViewCallback view_presenter); COMPONENT_EXPORT(PLATFORM_WINDOW) const FlatlandPresentViewCallback& GetFlatlandViewPresenter(); // Ignores presentation requests, for tests which don't rely on a functioning // Presenter service. COMPONENT_EXPORT(PLATFORM_WINDOW) void IgnorePresentCallsForTest(); } // namespace fuchsia } // namespace ui #endif // UI_PLATFORM_WINDOW_FUCHSIA_INITIALIZE_PRESENTER_API_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/fuchsia/initialize_presenter_api_view.h
C++
unknown
1,840
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_FUCHSIA_SCENIC_WINDOW_DELEGATE_H_ #define UI_PLATFORM_WINDOW_FUCHSIA_SCENIC_WINDOW_DELEGATE_H_ namespace ui { // Interface use by ScenicWindow to notify the client about Scenic-specific // events. class COMPONENT_EXPORT(PLATFORM_WINDOW) ScenicWindowDelegate { public: // Called to notify about logical pixel scale changes. virtual void OnScenicPixelScale(PlatformWindow* window, float scale) = 0; protected: virtual ~ScenicWindowDelegate() {} }; } // namespace ui #endif // UI_PLATFORM_WINDOW_FUCHSIA_SCENIC_WINDOW_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/fuchsia/scenic_window_delegate.h
C++
unknown
713
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/platform_window.h" #include <string> #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" namespace ui { PlatformWindow::PlatformWindow() = default; PlatformWindow::~PlatformWindow() = default; bool PlatformWindow::ShouldWindowContentsBeTransparent() const { return false; } void PlatformWindow::SetZOrderLevel(ZOrderLevel order) {} ZOrderLevel PlatformWindow::GetZOrderLevel() const { return ZOrderLevel::kNormal; } void PlatformWindow::StackAbove(gfx::AcceleratedWidget widget) {} void PlatformWindow::StackAtTop() {} void PlatformWindow::FlashFrame(bool flash_frame) {} void PlatformWindow::SetShape(std::unique_ptr<ShapeRects> native_shape, const gfx::Transform& transform) {} void PlatformWindow::SetAspectRatio(const gfx::SizeF& aspect_ratio) {} void PlatformWindow::SetWindowIcons(const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) {} bool PlatformWindow::IsAnimatingClosed() const { return false; } bool PlatformWindow::IsTranslucentWindowOpacitySupported() const { return false; } void PlatformWindow::SetOpacity(float opacity) {} void PlatformWindow::SetVisibilityChangedAnimationsEnabled(bool enabled) {} std::string PlatformWindow::GetWindowUniqueId() const { return std::string(); } bool PlatformWindow::ShouldUpdateWindowShape() const { return false; } bool PlatformWindow::CanSetDecorationInsets() const { return false; } void PlatformWindow::SetDecorationInsets(const gfx::Insets* insets_px) {} void PlatformWindow::SetOpaqueRegion(const std::vector<gfx::Rect>* region_px) {} void PlatformWindow::SetInputRegion(const gfx::Rect* region_px) {} bool PlatformWindow::IsClientControlledWindowMovementSupported() const { return true; } void PlatformWindow::NotifyStartupComplete(const std::string& startup_id) {} } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/platform_window.cc
C++
unknown
2,058
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_PLATFORM_WINDOW_H_ #define UI_PLATFORM_WINDOW_PLATFORM_WINDOW_H_ #include <memory> #include <string> #include <vector> #include "base/component_export.h" #include "ui/base/class_property.h" #include "ui/base/ui_base_types.h" #include "ui/gfx/native_widget_types.h" #include "ui/platform_window/platform_window_delegate.h" template <class T> class scoped_refptr; namespace gfx { class ImageSkia; class Insets; class Point; class Rect; class SizeF; class Transform; } // namespace gfx namespace ui { class PlatformCursor; // Generic PlatformWindow interface. class COMPONENT_EXPORT(PLATFORM_WINDOW) PlatformWindow : public PropertyHandler { public: PlatformWindow(); ~PlatformWindow() override; // PlatformWindow may be called with the |inactive| set to true in some cases. // That means that the Window Manager must not activate the window when it is // shown. Most of PlatformWindow may ignore this value if not supported. virtual void Show(bool inactive = false) = 0; virtual void Hide() = 0; virtual void Close() = 0; virtual bool IsVisible() const = 0; // Informs the window it is going to be destroyed sometime soon. This is only // called for specific code paths, for example by Ash, so it shouldn't be // assumed this will get called before destruction. virtual void PrepareForShutdown() = 0; // Sets and gets the bounds of the platform-window. Note that the bounds is in // physical pixel coordinates. The implementation should use // `PlatformWindowDelegate::ConvertRectToPixels|DIP` if conversion is // necessary. virtual void SetBoundsInPixels(const gfx::Rect& bounds) = 0; virtual gfx::Rect GetBoundsInPixels() const = 0; // Sets and gets the bounds of the platform-window. Note that the bounds is in // device-independent-pixel (dip) coordinates. The implementation should use // `PlatformWindowDelegate::ConvertRectToPixels|DIP` if conversion is // necessary. virtual void SetBoundsInDIP(const gfx::Rect& bounds) = 0; virtual gfx::Rect GetBoundsInDIP() const = 0; virtual void SetTitle(const std::u16string& title) = 0; virtual void SetCapture() = 0; virtual void ReleaseCapture() = 0; virtual bool HasCapture() const = 0; // Enters or exits fullscreen when `fullscreen` is true or false respectively. // This operation may have no effect if the window is already in the specified // state. `target_display_id` indicates the display where the window should be // shown fullscreen when entering into fullscreen; display::kInvalidDisplayId // indicates that no display was specified, so the current display may be // used. virtual void SetFullscreen(bool fullscreen, int64_t target_display_id) = 0; virtual void Maximize() = 0; virtual void Minimize() = 0; virtual void Restore() = 0; virtual PlatformWindowState GetPlatformWindowState() const = 0; virtual void Activate() = 0; virtual void Deactivate() = 0; // Sets whether the window should have the standard title bar provided by the // underlying windowing system. For the main browser window, this may be // changed by the user at any time via 'Show system title bar' option in the // tab strip menu. virtual void SetUseNativeFrame(bool use_native_frame) = 0; virtual bool ShouldUseNativeFrame() const = 0; // This method sets the current cursor to `cursor`. Note that the platform // window should keep a copy of `cursor` and also avoid replacing it until the // new value has been set if any kind of platform-specific resources are // managed by the platform cursor, e.g. HCURSOR on Windows, which are // destroyed once the last copy of the platform cursor goes out of scope. virtual void SetCursor(scoped_refptr<PlatformCursor> cursor) = 0; // Moves the cursor to |location|. Location is in platform window coordinates. virtual void MoveCursorTo(const gfx::Point& location) = 0; // Confines the cursor to |bounds| when it is in the platform window. |bounds| // is in platform window coordinates. virtual void ConfineCursorToBounds(const gfx::Rect& bounds) = 0; // Sets and gets the restored bounds of the platform-window. virtual void SetRestoredBoundsInDIP(const gfx::Rect& bounds) = 0; virtual gfx::Rect GetRestoredBoundsInDIP() const = 0; // Sets the Window icons. |window_icon| is a 16x16 icon suitable for use in // a title bar. |app_icon| is a larger size for use in the host environment // app switching UI. virtual void SetWindowIcons(const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) = 0; // Notifies that size constraints of the host have been changed and the // PlatformWindow must react on them accordingly. virtual void SizeConstraintsChanged() = 0; // Tells if the content of the platform window should be transparent. By // default returns false. virtual bool ShouldWindowContentsBeTransparent() const; // Sets and gets ZOrderLevel of the PlatformWindow. Such platforms that do not // support ordering, should not implement these methods as the default // implementation always returns ZOrderLevel::kNormal value. virtual void SetZOrderLevel(ZOrderLevel order); virtual ZOrderLevel GetZOrderLevel() const; // Asks the PlatformWindow to stack itself on top of |widget|. virtual void StackAbove(gfx::AcceleratedWidget widget); virtual void StackAtTop(); // Flashes the frame of the window to draw attention to it. If |flash_frame| // is set, the PlatformWindow must draw attention to it. If |flash_frame| is // not set, flashing must be stopped. virtual void FlashFrame(bool flash_frame); using ShapeRects = std::vector<gfx::Rect>; // Sets shape of the PlatformWindow. ShapeRects corresponds to the // Widget::ShapeRects that is a vector of gfx::Rects that describe the shape. virtual void SetShape(std::unique_ptr<ShapeRects> native_shape, const gfx::Transform& transform); // Sets the aspect ratio of the Platform Window, which will be // maintained during interactive resizing. This size disregards title bar and // borders. Once set, some platforms ensure the content will only size to // integer multiples of |aspect_ratio|. virtual void SetAspectRatio(const gfx::SizeF& aspect_ratio); // Returns true if the window was closed but is still showing because of // animations. virtual bool IsAnimatingClosed() const; // Returns true if the window supports translucency. virtual bool IsTranslucentWindowOpacitySupported() const; // Sets opacity of the platform window. virtual void SetOpacity(float opacity); // Enables or disables platform provided animations of the PlatformWindow. // If |enabled| is set to false, animations are disabled. virtual void SetVisibilityChangedAnimationsEnabled(bool enabled); // Returns a unique ID for the window. The interpretation of the ID is // platform specific. Overriding this method is optional. virtual std::string GetWindowUniqueId() const; // Returns true if window shape should be updated in host, // otherwise false when platform window or specific frame views updates the // window shape. virtual bool ShouldUpdateWindowShape() const; // Returns true if the WM supports setting the frame extents for client side // decorations. This typically requires a compositor and an extension for // specifying the decoration insets. virtual bool CanSetDecorationInsets() const; // Lets the WM know which portion of the window is the frame decoration. The // WM may use this to eg. snap windows to each other starting where the window // begins rather than starting where the shadow begins. If |insets_px| is // nullptr, then any existing insets will be reset. virtual void SetDecorationInsets(const gfx::Insets* insets_px); // Sets a hint for the compositor so it can avoid unnecessarily redrawing // occluded portions of windows. If |region_px| is nullptr, then any existing // region will be reset. virtual void SetOpaqueRegion(const std::vector<gfx::Rect>* region_px); // Sets the clickable region of a window. This is useful for trimming down a // potentially large (24px) hit area for window resizing on the window shadow // to a more reasonable (10px) area. If |region_px| is nullptr, then any // existing region will be reset. virtual void SetInputRegion(const gfx::Rect* region_px); // Whether the platform supports client-controlled window movement. Under // Wayland, for example, this returns false, unless the required protocol // extension is supported by the compositor. virtual bool IsClientControlledWindowMovementSupported() const; // Notifies the DE that the app is done loading, so that it can dismiss any // loading animations. virtual void NotifyStartupComplete(const std::string& startup_id); // Shows tooltip with this platform window as a parent window. // `position` is relative to this platform window. // `show_delay` and `hide_delay` specify the delay before showing or hiding // tooltip on server side. `show_delay` may be set to zero only for testing. // If `hide_delay` is zero, the tooltip will not be hidden by timer on server // side. virtual void ShowTooltip(const std::u16string& text, const gfx::Point& position, const PlatformWindowTooltipTrigger trigger, const base::TimeDelta show_delay, const base::TimeDelta hide_delay) {} // Hides tooltip. virtual void HideTooltip() {} }; } // namespace ui #endif // UI_PLATFORM_WINDOW_PLATFORM_WINDOW_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/platform_window.h
C++
unknown
9,799
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/platform_window_delegate.h" #include <sstream> #include "base/notreached.h" #include "third_party/skia/include/core/SkPath.h" #include "ui/base/owned_window_anchor.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/size.h" namespace ui { bool PlatformWindowDelegate::State::ProducesFrameOnUpdateFrom( const State& old) const { // Changing the bounds origin won't produce a new frame. Anything else will. return old.bounds_dip.size() != bounds_dip.size() || old.size_px != size_px || old.window_scale != window_scale || old.raster_scale != raster_scale; } std::string PlatformWindowDelegate::State::ToString() const { std::stringstream result; result << "State {"; result << "bounds_dip = " << bounds_dip.ToString(); result << ", size_px = " << size_px.ToString(); result << ", window_scale = " << window_scale; result << ", raster_scale = " << raster_scale; result << "}"; return result.str(); } PlatformWindowDelegate::PlatformWindowDelegate() = default; PlatformWindowDelegate::~PlatformWindowDelegate() = default; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_OHOS) void PlatformWindowDelegate::OnWindowTiledStateChanged( WindowTiledEdges new_tiled_edges) {} #endif absl::optional<gfx::Size> PlatformWindowDelegate::GetMinimumSizeForWindow() { return absl::nullopt; } absl::optional<gfx::Size> PlatformWindowDelegate::GetMaximumSizeForWindow() { return absl::nullopt; } SkPath PlatformWindowDelegate::GetWindowMaskForWindowShapeInPixels() { return SkPath(); } void PlatformWindowDelegate::OnSurfaceFrameLockingChanged(bool lock) {} absl::optional<MenuType> PlatformWindowDelegate::GetMenuType() { return absl::nullopt; } void PlatformWindowDelegate::OnOcclusionStateChanged( PlatformWindowOcclusionState occlusion_state) {} int64_t PlatformWindowDelegate::OnStateUpdate(const State& old, const State& latest) { NOTREACHED(); return -1; } absl::optional<OwnedWindowAnchor> PlatformWindowDelegate::GetOwnedWindowAnchorAndRectInDIP() { return absl::nullopt; } void PlatformWindowDelegate::SetFrameRateThrottleEnabled(bool enabled) {} void PlatformWindowDelegate::OnTooltipShownOnServer(const std::u16string& text, const gfx::Rect& bounds) {} void PlatformWindowDelegate::OnTooltipHiddenOnServer() {} gfx::Rect PlatformWindowDelegate::ConvertRectToPixels( const gfx::Rect& rect_in_dip) const { return rect_in_dip; } gfx::Rect PlatformWindowDelegate::ConvertRectToDIP( const gfx::Rect& rect_in_pixels) const { return rect_in_pixels; } gfx::PointF PlatformWindowDelegate::ConvertScreenPointToLocalDIP( const gfx::Point& screen_in_pixels) const { return gfx::PointF(screen_in_pixels); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/platform_window_delegate.cc
C++
unknown
3,011
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_PLATFORM_WINDOW_DELEGATE_H_ #define UI_PLATFORM_WINDOW_PLATFORM_WINDOW_DELEGATE_H_ #include <string> #include "base/component_export.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/ui_base_types.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/native_widget_types.h" #if BUILDFLAG(IS_FUCHSIA) #include "ui/gfx/geometry/insets.h" #endif // BUILDFLAG(IS_FUCHSIA) namespace gfx { class Rect; class Size; class PointF; } // namespace gfx class SkPath; namespace ui { class Event; struct OwnedWindowAnchor; enum class PlatformWindowState { kUnknown, kMaximized, kMinimized, kNormal, kFullScreen, // Currently, only used by ChromeOS. kSnappedPrimary, kSnappedSecondary, kFloated, }; enum class PlatformWindowOcclusionState { kUnknown, kVisible, kOccluded, kHidden, }; enum class PlatformWindowTooltipTrigger { kCursor, kKeyboard, }; class COMPONENT_EXPORT(PLATFORM_WINDOW) PlatformWindowDelegate { public: struct COMPONENT_EXPORT(PLATFORM_WINDOW) BoundsChange { BoundsChange() = delete; constexpr BoundsChange(bool origin_changed) : origin_changed(origin_changed) {} ~BoundsChange() = default; // True if the bounds change resulted in the origin change. bool origin_changed : 1; #if BUILDFLAG(IS_FUCHSIA) // The widths of border regions which are obscured by overlapping // platform UI elements like onscreen keyboards. // // As an example, the overlap from an onscreen keyboard covering // the bottom of the Window would be represented like this: // // +------------------------+ --- // | | | // | content | | // | | | window // +------------------------+ --- | // | onscreen keyboard | | overlap | // +------------------------+ --- --- gfx::Insets system_ui_overlap; #endif // BUILDFLAG(IS_FUCHSIA) }; // State describes important data about this window, for example data that // needs to be synchronized and acked. We apply this state to the client // (us) and wait for a frame to be produced matching this state. That frame // is identified by the sequence id. // This is used by OnStateChanged and currently only by ozone/wayland. struct COMPONENT_EXPORT(PLATFORM_WINDOW) State { bool operator==(const State& rhs) const { return std::tie(bounds_dip, size_px, window_scale, raster_scale) == std::tie(rhs.bounds_dip, rhs.size_px, rhs.window_scale, rhs.raster_scale); } // Bounds in DIP. gfx::Rect bounds_dip; // Size in pixels. Note that it's required to keep information in both DIP // and pixels since it is not always possible to convert between them. gfx::Size size_px; // Current scale factor of the output where the window is located at. float window_scale = 1.0; // TODO(crbug.com/1395267): Add window states here. // Scale to raster the window at. float raster_scale = 1.0; // Returns true if updating from the given State |old| to this state // should produce a frame. bool ProducesFrameOnUpdateFrom(const State& old) const; std::string ToString() const; }; PlatformWindowDelegate(); virtual ~PlatformWindowDelegate(); virtual void OnBoundsChanged(const BoundsChange& change) = 0; // Note that |damaged_region| is in the platform-window's coordinates, in // physical pixels. virtual void OnDamageRect(const gfx::Rect& damaged_region) = 0; virtual void DispatchEvent(Event* event) = 0; virtual void OnCloseRequest() = 0; virtual void OnClosed() = 0; virtual void OnWindowStateChanged(PlatformWindowState old_state, PlatformWindowState new_state) = 0; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_OHOS) // Notifies the delegate that the tiled state of the window edges has changed. virtual void OnWindowTiledStateChanged(WindowTiledEdges new_tiled_edges); #endif #if BUILDFLAG(IS_CHROMEOS_LACROS) // TODO(ffred): We should just add kImmersiveFullscreen as a state. However, // that will require more refactoring in other places to understand that // kImmersiveFullscreen is a fullscreen status. // Sets the immersive mode for the window. This will only have an effect on // ChromeOS platforms. virtual void OnImmersiveModeChanged(bool immersive) {} #endif virtual void OnLostCapture() = 0; virtual void OnAcceleratedWidgetAvailable(gfx::AcceleratedWidget widget) = 0; // Notifies the delegate that the widget is about to be destroyed. virtual void OnWillDestroyAcceleratedWidget() = 0; // Notifies the delegate that the widget cannot be used anymore until // a new widget is made available through OnAcceleratedWidgetAvailable(). // Must not be called when the PlatformWindow is being destroyed. virtual void OnAcceleratedWidgetDestroyed() = 0; virtual void OnActivationChanged(bool active) = 0; // Requests size constraints for the PlatformWindow in DIP. virtual absl::optional<gfx::Size> GetMinimumSizeForWindow(); virtual absl::optional<gfx::Size> GetMaximumSizeForWindow(); // Returns a mask to be used to clip the window for the size of // |WindowTreeHost::GetBoundsInPixels|. // This is used to create the non-rectangular window shape. virtual SkPath GetWindowMaskForWindowShapeInPixels(); // Called while dragging maximized window when SurfaceFrame associated with // this window is locked to normal state or unlocked from previously locked // state. This function is used by chromeos for syncing // `chromeos::kFrameRestoreLookKey` window property // with lacros-chrome. virtual void OnSurfaceFrameLockingChanged(bool lock); // Returns a menu type of the window. Valid only for the menu windows. virtual absl::optional<MenuType> GetMenuType(); // Called when the location of mouse pointer entered the window. This is // different from ui::ET_MOUSE_ENTERED which may not be generated when mouse // is captured either by implicitly or explicitly. virtual void OnMouseEnter() = 0; // Called when the occlusion state changes, if the underlying platform // is providing us with occlusion information. virtual void OnOcclusionStateChanged( PlatformWindowOcclusionState occlusion_state); // Updates state for clients that need sequence point synchronized // PlatformWindowDelegate::State operations. In particular, this requests a // new LocalSurfaceId for the window tree of this platform window. It returns // the new parent ID. Calling code can compare this value with the // gfx::FrameData::seq value to see when viz has produced a frame at or after // the (conceptually) inserted sequence point. OnStateUpdate may return -1 if // the state update does not require a new frame to be considered // synchronized. For example, this can happen if the old and new states are // the same, or it only changes the origin of the bounds. virtual int64_t OnStateUpdate(const State& old, const State& latest); // Returns optional information for owned windows that require anchor for // positioning. Useful for such backends as Wayland as it provides flexibility // in positioning child windows, which must be repositioned if the originally // intended position caused the surface to be constrained. virtual absl::optional<OwnedWindowAnchor> GetOwnedWindowAnchorAndRectInDIP(); // Enables or disables frame rate throttling. virtual void SetFrameRateThrottleEnabled(bool enabled); // Called when tooltip is shown on server. // `bounds` is in screen coordinates. virtual void OnTooltipShownOnServer(const std::u16string& text, const gfx::Rect& bounds); // Called when tooltip is hidden on server. virtual void OnTooltipHiddenOnServer(); // Convert gfx::Rect in pixels to DIP in screen, and vice versa. virtual gfx::Rect ConvertRectToPixels(const gfx::Rect& rect_in_dp) const; virtual gfx::Rect ConvertRectToDIP(const gfx::Rect& rect_in_pixells) const; // Convert gfx::Point in screen pixels to dip in the window's local // coordinate. virtual gfx::PointF ConvertScreenPointToLocalDIP( const gfx::Point& screen_in_pixels) const; }; } // namespace ui #endif // UI_PLATFORM_WINDOW_PLATFORM_WINDOW_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/platform_window_delegate.h
C++
unknown
8,694
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/platform_window_init_properties.h" namespace ui { PlatformWindowInitProperties::PlatformWindowInitProperties() = default; PlatformWindowInitProperties::PlatformWindowInitProperties( const gfx::Rect& bounds) : bounds(bounds) {} PlatformWindowInitProperties::PlatformWindowInitProperties( PlatformWindowInitProperties&& props) = default; PlatformWindowInitProperties::~PlatformWindowInitProperties() = default; } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/platform_window_init_properties.cc
C++
unknown
619
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_PLATFORM_WINDOW_INIT_PROPERTIES_H_ #define UI_PLATFORM_WINDOW_PLATFORM_WINDOW_INIT_PROPERTIES_H_ #include <string> #include "base/component_export.h" #include "base/memory/raw_ptr.h" #include "build/build_config.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/ui_base_types.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/native_widget_types.h" #if BUILDFLAG(IS_FUCHSIA) #include <fuchsia/element/cpp/fidl.h> #include <fuchsia/ui/composition/cpp/fidl.h> #include <fuchsia/ui/views/cpp/fidl.h> #include <lib/ui/scenic/cpp/view_ref_pair.h> #endif namespace gfx { class ImageSkia; } namespace ui { enum class PlatformWindowType { kWindow, kPopup, kMenu, kTooltip, kDrag, kBubble, }; enum class PlatformWindowOpacity { kInferOpacity, kOpaqueWindow, kTranslucentWindow, }; enum class PlatformWindowShadowType { kDefault, kNone, kDrop, }; class WorkspaceExtensionDelegate; #if BUILDFLAG(IS_FUCHSIA) class ScenicWindowDelegate; #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_OHOS) class X11ExtensionDelegate; #endif // Initial properties which are passed to PlatformWindow to be initialized // with a desired set of properties. struct COMPONENT_EXPORT(PLATFORM_WINDOW) PlatformWindowInitProperties { PlatformWindowInitProperties(); // Initializes properties with the specified |bounds|. explicit PlatformWindowInitProperties(const gfx::Rect& bounds); PlatformWindowInitProperties(PlatformWindowInitProperties&& props); ~PlatformWindowInitProperties(); // Tells desired PlatformWindow type. It can be popup, menu or anything else. PlatformWindowType type = PlatformWindowType::kWindow; // Sets the desired initial bounds. Can be empty. gfx::Rect bounds; // Tells PlatformWindow which native widget its parent holds. It is usually // used to find a parent from internal list of PlatformWindows. gfx::AcceleratedWidget parent_widget = gfx::kNullAcceleratedWidget; // Tells the opacity type of a window. Check the comment in the // Widget::InitProperties::WindowOpacity. PlatformWindowOpacity opacity = PlatformWindowOpacity::kOpaqueWindow; #if BUILDFLAG(IS_FUCHSIA) // Scenic 3D API uses `view_token` for links, whereas Flatland // API uses `view_creation_token`. Therefore, at most one of these fields must // be set. If `allow_null_view_token_for_test` is true, they may both be // false. fuchsia::ui::views::ViewToken view_token; fuchsia::ui::views::ViewCreationToken view_creation_token; scenic::ViewRefPair view_ref_pair; // Used to coordinate window closure requests with the shell. fuchsia::element::ViewControllerPtr view_controller; // Specifies whether handling of keypress events from the system is enabled. bool enable_keyboard = false; // Specifies whether system virtual keyboard support is enabled. bool enable_virtual_keyboard = false; ScenicWindowDelegate* scenic_window_delegate = nullptr; #endif bool activatable = true; bool force_show_in_taskbar; bool keep_on_top = false; bool is_security_surface = false; bool visible_on_all_workspaces = false; bool remove_standard_frame = false; std::string workspace; ZOrderLevel z_order = ZOrderLevel::kNormal; raw_ptr<WorkspaceExtensionDelegate> workspace_extension_delegate = nullptr; PlatformWindowShadowType shadow_type = PlatformWindowShadowType::kDefault; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_OHOS) bool prefer_dark_theme = false; raw_ptr<gfx::ImageSkia> icon = nullptr; absl::optional<SkColor> background_color; // Specifies the res_name and res_class fields, // respectively, of the WM_CLASS window property. Controls window grouping // and desktop file matching in Linux window managers. std::string wm_role_name; std::string wm_class_name; std::string wm_class_class; raw_ptr<X11ExtensionDelegate> x11_extension_delegate = nullptr; // Wayland specific. Holds the application ID that is used by the window // manager to match the desktop entry and group windows. std::string wayland_app_id; // Specifies the unique session id and the restore window id. int32_t restore_session_id; absl::optional<int32_t> restore_window_id; // Specifies the source to get `restore_window_id` from. absl::optional<std::string> restore_window_id_source; #endif #if BUILDFLAG(IS_OZONE) // Specifies whether the current window requests key-events that matches // system shortcuts. bool inhibit_keyboard_shortcuts = false; #endif bool enable_compositing_based_throttling = false; size_t compositor_memory_limit_mb = 0; }; } // namespace ui #endif // UI_PLATFORM_WINDOW_PLATFORM_WINDOW_INIT_PROPERTIES_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/platform_window_init_properties.h
C++
unknown
4,940
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/stub/stub_window.h" #include "base/memory/scoped_refptr.h" #include "base/notreached.h" #include "ui/base/cursor/platform_cursor.h" #include "ui/display/types/display_constants.h" #include "ui/platform_window/platform_window_delegate.h" namespace ui { StubWindow::StubWindow(PlatformWindowDelegate* delegate, bool use_default_accelerated_widget, const gfx::Rect& bounds) : bounds_(bounds) { DCHECK(delegate); InitDelegate(delegate, use_default_accelerated_widget); } StubWindow::StubWindow(const gfx::Rect& bounds) : bounds_(bounds) {} StubWindow::~StubWindow() = default; void StubWindow::InitDelegate(PlatformWindowDelegate* delegate, bool use_default_accelerated_widget) { DCHECK(delegate); delegate_ = delegate; if (use_default_accelerated_widget) delegate_->OnAcceleratedWidgetAvailable(gfx::kNullAcceleratedWidget); } void StubWindow::Show(bool inactive) {} void StubWindow::Hide() {} void StubWindow::Close() { delegate_->OnClosed(); } bool StubWindow::IsVisible() const { return true; } void StubWindow::PrepareForShutdown() {} void StubWindow::SetBoundsInPixels(const gfx::Rect& bounds) { // Even if the pixel bounds didn't change this call to the delegate should // still happen. The device scale factor may have changed which effectively // changes the bounds. bool origin_changed = bounds_.origin() != bounds.origin(); bounds_ = bounds; delegate_->OnBoundsChanged({origin_changed}); } gfx::Rect StubWindow::GetBoundsInPixels() const { return bounds_; } void StubWindow::SetBoundsInDIP(const gfx::Rect& bounds) { SetBoundsInPixels(delegate_->ConvertRectToPixels(bounds)); } gfx::Rect StubWindow::GetBoundsInDIP() const { return delegate_->ConvertRectToDIP(bounds_); } void StubWindow::SetTitle(const std::u16string& title) {} void StubWindow::SetCapture() {} void StubWindow::ReleaseCapture() {} bool StubWindow::HasCapture() const { return false; } void StubWindow::SetFullscreen(bool fullscreen, int64_t target_display_id) { DCHECK_EQ(target_display_id, display::kInvalidDisplayId); window_state_ = fullscreen ? ui::PlatformWindowState::kFullScreen : ui::PlatformWindowState::kUnknown; } void StubWindow::Maximize() {} void StubWindow::Minimize() {} void StubWindow::Restore() {} PlatformWindowState StubWindow::GetPlatformWindowState() const { return window_state_; } void StubWindow::Activate() { if (activation_state_ != ActivationState::kActive) { activation_state_ = ActivationState::kActive; delegate_->OnActivationChanged(/*active=*/true); } } void StubWindow::Deactivate() { if (activation_state_ != ActivationState::kInactive) { activation_state_ = ActivationState::kInactive; delegate_->OnActivationChanged(/*active=*/false); } } void StubWindow::SetUseNativeFrame(bool use_native_frame) {} bool StubWindow::ShouldUseNativeFrame() const { NOTIMPLEMENTED_LOG_ONCE(); return false; } void StubWindow::SetCursor(scoped_refptr<PlatformCursor> cursor) {} void StubWindow::MoveCursorTo(const gfx::Point& location) {} void StubWindow::ConfineCursorToBounds(const gfx::Rect& bounds) {} void StubWindow::SetRestoredBoundsInDIP(const gfx::Rect& bounds) {} gfx::Rect StubWindow::GetRestoredBoundsInDIP() const { return gfx::Rect(); } void StubWindow::SetWindowIcons(const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) {} void StubWindow::SizeConstraintsChanged() {} } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/stub/stub_window.cc
C++
unknown
3,736
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_STUB_STUB_WINDOW_H_ #define UI_PLATFORM_WINDOW_STUB_STUB_WINDOW_H_ #include "base/memory/raw_ptr.h" #include "ui/gfx/geometry/rect.h" #include "ui/platform_window/platform_window.h" #include "ui/platform_window/platform_window_delegate.h" #include "ui/platform_window/stub/stub_window_export.h" namespace ui { // StubWindow is useful for tests, as well as implementations that only care // about bounds and activation state. class STUB_WINDOW_EXPORT StubWindow : public PlatformWindow { public: explicit StubWindow(PlatformWindowDelegate* delegate, bool use_default_accelerated_widget = true, const gfx::Rect& bounds = gfx::Rect()); explicit StubWindow(const gfx::Rect& bounds); StubWindow(const StubWindow&) = delete; StubWindow& operator=(const StubWindow&) = delete; ~StubWindow() override; void InitDelegate(PlatformWindowDelegate* delegate, bool use_default_accelerated_widget = true); protected: PlatformWindowDelegate* delegate() { return delegate_; } private: enum class ActivationState { kUnknown, kActive, kInactive, }; // PlatformWindow: void Show(bool inactive) override; void Hide() override; void Close() override; bool IsVisible() const override; void PrepareForShutdown() override; void SetBoundsInPixels(const gfx::Rect& bounds) override; gfx::Rect GetBoundsInPixels() const override; void SetBoundsInDIP(const gfx::Rect& bounds) override; gfx::Rect GetBoundsInDIP() const override; void SetTitle(const std::u16string& title) override; void SetCapture() override; void ReleaseCapture() override; void SetFullscreen(bool fullscreen, int64_t target_display_id) override; bool HasCapture() const override; void Maximize() override; void Minimize() override; void Restore() override; PlatformWindowState GetPlatformWindowState() const override; void Activate() override; void Deactivate() override; void SetUseNativeFrame(bool use_native_frame) override; bool ShouldUseNativeFrame() const override; void SetCursor(scoped_refptr<PlatformCursor> cursor) override; void MoveCursorTo(const gfx::Point& location) override; void ConfineCursorToBounds(const gfx::Rect& bounds) override; void SetRestoredBoundsInDIP(const gfx::Rect& bounds) override; gfx::Rect GetRestoredBoundsInDIP() const override; void SetWindowIcons(const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) override; void SizeConstraintsChanged() override; raw_ptr<PlatformWindowDelegate> delegate_ = nullptr; gfx::Rect bounds_; ui::PlatformWindowState window_state_ = ui::PlatformWindowState::kUnknown; ActivationState activation_state_ = ActivationState::kUnknown; }; } // namespace ui #endif // UI_PLATFORM_WINDOW_STUB_STUB_WINDOW_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/stub/stub_window.h
C++
unknown
2,995
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_STUB_STUB_WINDOW_EXPORT_H_ #define UI_PLATFORM_WINDOW_STUB_STUB_WINDOW_EXPORT_H_ #if defined(COMPONENT_BUILD) #if defined(WIN32) #if defined(STUB_WINDOW_IMPLEMENTATION) #define STUB_WINDOW_EXPORT __declspec(dllexport) #else #define STUB_WINDOW_EXPORT __declspec(dllimport) #endif // defined(STUB_WINDOW_IMPLEMENTATION) #else // defined(WIN32) #if defined(STUB_WINDOW_IMPLEMENTATION) #define STUB_WINDOW_EXPORT __attribute__((visibility("default"))) #else #define STUB_WINDOW_EXPORT #endif #endif #else // defined(COMPONENT_BUILD) #define STUB_WINDOW_EXPORT #endif #endif // UI_PLATFORM_WINDOW_STUB_STUB_WINDOW_EXPORT_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/stub/stub_window_export.h
C
unknown
800
include_rules = [ "+ui/events", "+ui/gfx", ]
Zhao-PengFei35/chromium_src_4
ui/platform_window/win/DEPS
Python
unknown
49
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/win/win_window.h" #include <windows.h> #include <algorithm> #include <memory> #include <string> #include "base/memory/scoped_refptr.h" #include "base/notreached.h" #include "base/strings/string_util_win.h" #include "ui/base/cursor/platform_cursor.h" #include "ui/base/win/win_cursor.h" #include "ui/events/event.h" #include "ui/events/event_utils.h" #include "ui/gfx/win/msg_util.h" namespace ui { namespace { bool use_popup_as_root_window_for_test = false; gfx::Rect GetWindowBoundsForClientBounds(DWORD style, DWORD ex_style, const gfx::Rect& bounds) { RECT wr; wr.left = bounds.x(); wr.top = bounds.y(); wr.right = bounds.x() + bounds.width(); wr.bottom = bounds.y() + bounds.height(); AdjustWindowRectEx(&wr, style, FALSE, ex_style); // Make sure to keep the window onscreen, as AdjustWindowRectEx() may have // moved part of it offscreen. gfx::Rect window_bounds(wr.left, wr.top, wr.right - wr.left, wr.bottom - wr.top); window_bounds.set_x(std::max(0, window_bounds.x())); window_bounds.set_y(std::max(0, window_bounds.y())); return window_bounds; } } // namespace WinWindow::WinWindow(PlatformWindowDelegate* delegate, const gfx::Rect& bounds) : delegate_(delegate) { CHECK(delegate_); DWORD window_style = WS_OVERLAPPEDWINDOW; if (use_popup_as_root_window_for_test) { set_window_style(WS_POPUP); window_style = WS_POPUP; } gfx::Rect window_bounds = GetWindowBoundsForClientBounds(window_style, window_ex_style(), bounds); gfx::WindowImpl::Init(NULL, window_bounds); SetWindowText(hwnd(), L"WinWindow"); } WinWindow::~WinWindow() {} void WinWindow::Destroy() { if (IsWindow(hwnd())) DestroyWindow(hwnd()); } void WinWindow::Show(bool inactive) { ShowWindow(hwnd(), inactive ? SW_SHOWNOACTIVATE : SW_SHOWNORMAL); } void WinWindow::Hide() { ShowWindow(hwnd(), SW_HIDE); } void WinWindow::Close() { Destroy(); } bool WinWindow::IsVisible() const { NOTIMPLEMENTED_LOG_ONCE(); return true; } void WinWindow::PrepareForShutdown() {} void WinWindow::SetBoundsInPixels(const gfx::Rect& bounds) { gfx::Rect window_bounds = GetWindowBoundsForClientBounds( GetWindowLong(hwnd(), GWL_STYLE), GetWindowLong(hwnd(), GWL_EXSTYLE), bounds); unsigned int flags = SWP_NOREPOSITION; if (!::IsWindowVisible(hwnd())) flags |= SWP_NOACTIVATE; SetWindowPos(hwnd(), NULL, window_bounds.x(), window_bounds.y(), window_bounds.width(), window_bounds.height(), flags); } gfx::Rect WinWindow::GetBoundsInPixels() const { RECT cr; GetClientRect(hwnd(), &cr); return gfx::Rect(cr); } void WinWindow::SetBoundsInDIP(const gfx::Rect& bounds) { // SetBounds should not be used on Windows tests. NOTREACHED(); } gfx::Rect WinWindow::GetBoundsInDIP() const { // GetBounds should not be used on Windows tests. NOTREACHED(); return GetBoundsInPixels(); } void WinWindow::SetTitle(const std::u16string& title) { SetWindowText(hwnd(), base::as_wcstr(title)); } void WinWindow::SetCapture() { if (!HasCapture()) ::SetCapture(hwnd()); } void WinWindow::ReleaseCapture() { if (HasCapture()) ::ReleaseCapture(); } bool WinWindow::HasCapture() const { return ::GetCapture() == hwnd(); } void WinWindow::SetFullscreen(bool fullscreen, int64_t target_display_id) {} void WinWindow::Maximize() {} void WinWindow::Minimize() {} void WinWindow::Restore() {} PlatformWindowState WinWindow::GetPlatformWindowState() const { return PlatformWindowState::kUnknown; } void WinWindow::Activate() { NOTIMPLEMENTED_LOG_ONCE(); } void WinWindow::Deactivate() { NOTIMPLEMENTED_LOG_ONCE(); } void WinWindow::SetUseNativeFrame(bool use_native_frame) {} bool WinWindow::ShouldUseNativeFrame() const { NOTIMPLEMENTED_LOG_ONCE(); return false; } void WinWindow::SetCursor(scoped_refptr<PlatformCursor> platform_cursor) { DCHECK(platform_cursor); auto cursor = WinCursor::FromPlatformCursor(platform_cursor); ::SetCursor(cursor->hcursor()); // The new cursor needs to be stored last to avoid deleting the old cursor // while it's still in use. cursor_ = cursor; } void WinWindow::MoveCursorTo(const gfx::Point& location) { ::SetCursorPos(location.x(), location.y()); } void WinWindow::ConfineCursorToBounds(const gfx::Rect& bounds) {} void WinWindow::SetRestoredBoundsInDIP(const gfx::Rect& bounds) {} gfx::Rect WinWindow::GetRestoredBoundsInDIP() const { return gfx::Rect(); } bool WinWindow::ShouldWindowContentsBeTransparent() const { // The window contents need to be transparent when the titlebar area is drawn // by the DWM rather than Chrome, so that area can show through. This // function does not describe the transparency of the whole window appearance, // but merely of the content Chrome draws, so even when the system titlebars // appear opaque, the content above them needs to be transparent, or they'll // be covered by a black (undrawn) region. return !IsFullscreen(); } void WinWindow::SetZOrderLevel(ZOrderLevel order) { NOTIMPLEMENTED_LOG_ONCE(); } ZOrderLevel WinWindow::GetZOrderLevel() const { NOTIMPLEMENTED_LOG_ONCE(); return ZOrderLevel::kNormal; } void WinWindow::StackAbove(gfx::AcceleratedWidget widget) { NOTIMPLEMENTED_LOG_ONCE(); } void WinWindow::StackAtTop() { NOTIMPLEMENTED_LOG_ONCE(); } void WinWindow::FlashFrame(bool flash_frame) { NOTIMPLEMENTED_LOG_ONCE(); } void WinWindow::SetVisibilityChangedAnimationsEnabled(bool enabled) { NOTIMPLEMENTED_LOG_ONCE(); } void WinWindow::SetShape(std::unique_ptr<ShapeRects> native_shape, const gfx::Transform& transform) { NOTIMPLEMENTED_LOG_ONCE(); } void WinWindow::SetAspectRatio(const gfx::SizeF& aspect_ratio) { NOTIMPLEMENTED_LOG_ONCE(); } void WinWindow::SetWindowIcons(const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) { NOTIMPLEMENTED_LOG_ONCE(); } void WinWindow::SizeConstraintsChanged() { NOTIMPLEMENTED_LOG_ONCE(); } bool WinWindow::IsAnimatingClosed() const { NOTIMPLEMENTED_LOG_ONCE(); return false; } bool WinWindow::IsTranslucentWindowOpacitySupported() const { NOTIMPLEMENTED_LOG_ONCE(); return false; } bool WinWindow::IsFullscreen() const { return GetPlatformWindowState() == PlatformWindowState::kFullScreen; } LRESULT WinWindow::OnMouseRange(UINT message, WPARAM w_param, LPARAM l_param) { CHROME_MSG msg = {hwnd(), message, w_param, l_param, static_cast<DWORD>(GetMessageTime()), {CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param)}}; std::unique_ptr<Event> event = EventFromNative(msg); if (IsMouseEventFromTouch(message)) event->set_flags(event->flags() | EF_FROM_TOUCH); if (!(event->flags() & ui::EF_IS_NON_CLIENT)) delegate_->DispatchEvent(event.get()); SetMsgHandled(event->handled()); return 0; } LRESULT WinWindow::OnCaptureChanged(UINT message, WPARAM w_param, LPARAM l_param) { delegate_->OnLostCapture(); return 0; } LRESULT WinWindow::OnKeyEvent(UINT message, WPARAM w_param, LPARAM l_param) { CHROME_MSG msg = {hwnd(), message, w_param, l_param}; KeyEvent event(msg); delegate_->DispatchEvent(&event); SetMsgHandled(event.handled()); return 0; } LRESULT WinWindow::OnNCActivate(UINT message, WPARAM w_param, LPARAM l_param) { delegate_->OnActivationChanged(!!w_param); return DefWindowProc(hwnd(), message, w_param, l_param); } void WinWindow::OnClose() { delegate_->OnCloseRequest(); } LRESULT WinWindow::OnCreate(CREATESTRUCT* create_struct) { delegate_->OnAcceleratedWidgetAvailable(hwnd()); return 0; } void WinWindow::OnDestroy() { delegate_->OnClosed(); } void WinWindow::OnPaint(HDC) { gfx::Rect damage_rect; RECT update_rect = {0}; if (GetUpdateRect(hwnd(), &update_rect, FALSE)) damage_rect = gfx::Rect(update_rect); delegate_->OnDamageRect(damage_rect); ValidateRect(hwnd(), NULL); } void WinWindow::OnWindowPosChanged(WINDOWPOS* window_pos) { if (!(window_pos->flags & SWP_NOSIZE) || !(window_pos->flags & SWP_NOMOVE)) { RECT cr; GetClientRect(hwnd(), &cr); delegate_->OnBoundsChanged({true}); } } namespace test { // static void SetUsePopupAsRootWindowForTest(bool use) { use_popup_as_root_window_for_test = use; } } // namespace test } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/win/win_window.cc
C++
unknown
8,708
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_WIN_WIN_WINDOW_H_ #define UI_PLATFORM_WINDOW_WIN_WIN_WINDOW_H_ #include "base/memory/raw_ptr.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "ui/gfx/win/msg_util.h" #include "ui/gfx/win/window_impl.h" #include "ui/platform_window/platform_window.h" #include "ui/platform_window/platform_window_delegate.h" #include "ui/platform_window/win/win_window_export.h" #include <windows.h> namespace ui { class WinCursor; class WIN_WINDOW_EXPORT WinWindow : public PlatformWindow, public gfx::WindowImpl { public: WinWindow(PlatformWindowDelegate* delegate, const gfx::Rect& bounds); WinWindow(const WinWindow&) = delete; WinWindow& operator=(const WinWindow&) = delete; ~WinWindow() override; private: void Destroy(); // PlatformWindow: void Show(bool inactive) override; void Hide() override; void Close() override; bool IsVisible() const override; void PrepareForShutdown() override; void SetBoundsInPixels(const gfx::Rect& bounds) override; gfx::Rect GetBoundsInPixels() const override; void SetBoundsInDIP(const gfx::Rect& bounds) override; gfx::Rect GetBoundsInDIP() const override; void SetTitle(const std::u16string& title) override; void SetCapture() override; void ReleaseCapture() override; bool HasCapture() const override; void SetFullscreen(bool fullscreen, int64_t target_display_id) override; void Maximize() override; void Minimize() override; void Restore() override; PlatformWindowState GetPlatformWindowState() const override; void Activate() override; void Deactivate() override; void SetUseNativeFrame(bool use_native_frame) override; bool ShouldUseNativeFrame() const override; void SetCursor(scoped_refptr<PlatformCursor> cursor) override; void MoveCursorTo(const gfx::Point& location) override; void ConfineCursorToBounds(const gfx::Rect& bounds) override; void SetRestoredBoundsInDIP(const gfx::Rect& bounds) override; gfx::Rect GetRestoredBoundsInDIP() const override; bool ShouldWindowContentsBeTransparent() const override; void SetZOrderLevel(ZOrderLevel order) override; ZOrderLevel GetZOrderLevel() const override; void StackAbove(gfx::AcceleratedWidget widget) override; void StackAtTop() override; void FlashFrame(bool flash_frame) override; void SetVisibilityChangedAnimationsEnabled(bool enabled) override; void SetShape(std::unique_ptr<ShapeRects> native_shape, const gfx::Transform& transform) override; void SetAspectRatio(const gfx::SizeF& aspect_ratio) override; void SetWindowIcons(const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) override; void SizeConstraintsChanged() override; bool IsAnimatingClosed() const override; bool IsTranslucentWindowOpacitySupported() const override; bool IsFullscreen() const; CR_BEGIN_MSG_MAP_EX(WinWindow) CR_MESSAGE_RANGE_HANDLER_EX(WM_MOUSEFIRST, WM_MOUSELAST, OnMouseRange) CR_MESSAGE_RANGE_HANDLER_EX(WM_NCMOUSEMOVE, WM_NCXBUTTONDBLCLK, OnMouseRange) CR_MESSAGE_HANDLER_EX(WM_CAPTURECHANGED, OnCaptureChanged) CR_MESSAGE_HANDLER_EX(WM_KEYDOWN, OnKeyEvent) CR_MESSAGE_HANDLER_EX(WM_KEYUP, OnKeyEvent) CR_MESSAGE_HANDLER_EX(WM_SYSKEYDOWN, OnKeyEvent) CR_MESSAGE_HANDLER_EX(WM_SYSKEYUP, OnKeyEvent) CR_MESSAGE_HANDLER_EX(WM_CHAR, OnKeyEvent) CR_MESSAGE_HANDLER_EX(WM_SYSCHAR, OnKeyEvent) CR_MESSAGE_HANDLER_EX(WM_IME_CHAR, OnKeyEvent) CR_MESSAGE_HANDLER_EX(WM_NCACTIVATE, OnNCActivate) CR_MSG_WM_CLOSE(OnClose) CR_MSG_WM_CREATE(OnCreate) CR_MSG_WM_DESTROY(OnDestroy) CR_MSG_WM_PAINT(OnPaint) CR_MSG_WM_WINDOWPOSCHANGED(OnWindowPosChanged) CR_END_MSG_MAP() LRESULT OnMouseRange(UINT message, WPARAM w_param, LPARAM l_param); LRESULT OnCaptureChanged(UINT message, WPARAM w_param, LPARAM l_param); LRESULT OnKeyEvent(UINT message, WPARAM w_param, LPARAM l_param); LRESULT OnNCActivate(UINT message, WPARAM w_param, LPARAM l_param); void OnClose(); LRESULT OnCreate(CREATESTRUCT* create_struct); void OnDestroy(); void OnPaint(HDC); void OnWindowPosChanged(WINDOWPOS* window_pos); raw_ptr<PlatformWindowDelegate> delegate_; // Keep a reference to the current cursor to make sure the wrapped HCURSOR // isn't destroyed after the call to SetCursor(). scoped_refptr<WinCursor> cursor_; CR_MSG_MAP_CLASS_DECLARATIONS(WinWindow) }; namespace test { // Set true to let WindowTreeHostWin use a popup window // with no frame/title so that the window size and test's // expectations matches. WIN_WINDOW_EXPORT void SetUsePopupAsRootWindowForTest(bool use); } // namespace test } // namespace ui #endif // UI_PLATFORM_WINDOW_WIN_WIN_WINDOW_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/win/win_window.h
C++
unknown
4,945
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_WIN_WIN_WINDOW_EXPORT_H_ #define UI_PLATFORM_WINDOW_WIN_WIN_WINDOW_EXPORT_H_ #if defined(COMPONENT_BUILD) #if defined(WIN32) #if defined(WIN_WINDOW_IMPLEMENTATION) #define WIN_WINDOW_EXPORT __declspec(dllexport) #else #define WIN_WINDOW_EXPORT __declspec(dllimport) #endif // defined(WIN_WINDOW_IMPLEMENTATION) #else // defined(WIN32) #if defined(WIN_WINDOW_IMPLEMENTATION) #define WIN_WINDOW_EXPORT __attribute__((visibility("default"))) #else #define WIN_WINDOW_EXPORT #endif #endif #else // defined(COMPONENT_BUILD) #define WIN_WINDOW_EXPORT #endif #endif // UI_PLATFORM_WINDOW_WIN_WIN_WINDOW_EXPORT_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/win/win_window_export.h
C
unknown
786
include_rules = [ "+ui/base/class_property.h", "+ui/platform_window/platform_window.h", ]
Zhao-PengFei35/chromium_src_4
ui/platform_window/wm/DEPS
Python
unknown
94
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/wm/wm_drag_handler.h" #include "ui/base/class_property.h" #include "ui/platform_window/platform_window.h" DEFINE_UI_CLASS_PROPERTY_TYPE(ui::WmDragHandler*) namespace ui { DEFINE_UI_CLASS_PROPERTY_KEY(WmDragHandler*, kWmDragHandlerKey, nullptr) WmDragHandler::LocationDelegate::~LocationDelegate() = default; bool WmDragHandler::ShouldReleaseCaptureForDrag( ui::OSExchangeData* data) const { // Chrome normally expects starting drag and drop to release capture. return true; } void SetWmDragHandler(PlatformWindow* platform_window, WmDragHandler* drag_handler) { platform_window->SetProperty(kWmDragHandlerKey, drag_handler); } WmDragHandler* GetWmDragHandler(const PlatformWindow& platform_window) { return platform_window.GetProperty(kWmDragHandlerKey); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/wm/wm_drag_handler.cc
C++
unknown
992
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_WM_WM_DRAG_HANDLER_H_ #define UI_PLATFORM_WINDOW_WM_WM_DRAG_HANDLER_H_ #include "base/component_export.h" #include "base/functional/callback.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/native_widget_types.h" namespace gfx { class Point; } namespace ui { class PlatformWindow; class OSExchangeData; class COMPONENT_EXPORT(WM) WmDragHandler { public: // Notifies when the drag operation finished. using DragFinishedCallback = base::OnceCallback<void(mojom::DragOperation operation)>; // A delegate class for a platform on which chrome manages a drag image and // needs to receive the drag location. This can be null if the platform itself // manages the drag image. class LocationDelegate { public: // Called every time when the drag location has changed. virtual void OnDragLocationChanged(const gfx::Point& screen_point_px) = 0; // Called when the currently negotiated operation has changed. virtual void OnDragOperationChanged(mojom::DragOperation operation) = 0; // DragWidget (if any) should be ignored when finding top window and // dispatching mouse events. virtual absl::optional<gfx::AcceleratedWidget> GetDragWidget() = 0; protected: virtual ~LocationDelegate(); }; // Starts dragging |data|. Whereas, |operations| is a bitmask of // DragDropTypes::DragOperation values, which defines possible operations for // the drag source. The destination sets the resulting operation when the drop // action is performed. |source| indicates the source event type triggering // the drag, and |can_grab_pointer| indicates whether the implementation can // grab the mouse pointer (some platforms may need this).In progress updates // on the drag operation come back through the |location_delegate| on the // platform that chrome needs manages a drag image). This can be null if the // platform manages a drag image. |drag_finished_callback| is called when drag // operation finishes. // // This method runs a nested message loop, returning when the drag operation // is done. Care must be taken when calling this as it's entirely possible // that when this returns this object (and the calling object) have been // destroyed. // // Returns whether the operation ended well (i.e., had not been canceled). virtual bool StartDrag(const OSExchangeData& data, int operations, mojom::DragEventSource source, gfx::NativeCursor cursor, bool can_grab_pointer, DragFinishedCallback drag_finished_callback, LocationDelegate* location_delegate) = 0; // Cancels the drag. virtual void CancelDrag() = 0; // Updates the drag image. An empty |image| may be used to hide a previously // set non-empty drag image, and a non-empty |image| shows the drag image // again if it was previously hidden. // // This must be called during an active drag session. virtual void UpdateDragImage(const gfx::ImageSkia& image, const gfx::Vector2d& offset) = 0; // Returns whether capture should be released before a StartDrag() call. virtual bool ShouldReleaseCaptureForDrag(ui::OSExchangeData* data) const; }; COMPONENT_EXPORT(WM) void SetWmDragHandler(PlatformWindow* platform_window, WmDragHandler* drag_handler); COMPONENT_EXPORT(WM) WmDragHandler* GetWmDragHandler(const PlatformWindow& platform_window); } // namespace ui #endif // UI_PLATFORM_WINDOW_WM_WM_DRAG_HANDLER_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/wm/wm_drag_handler.h
C++
unknown
3,918
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/wm/wm_drop_handler.h" #include "ui/base/class_property.h" #include "ui/platform_window/platform_window.h" DEFINE_UI_CLASS_PROPERTY_TYPE(ui::WmDropHandler*) namespace ui { DEFINE_UI_CLASS_PROPERTY_KEY(WmDropHandler*, kWmDropHandlerKey, nullptr) void SetWmDropHandler(PlatformWindow* platform_window, WmDropHandler* drop_handler) { platform_window->SetProperty(kWmDropHandlerKey, drop_handler); } WmDropHandler* GetWmDropHandler(const PlatformWindow& platform_window) { return platform_window.GetProperty(kWmDropHandlerKey); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/wm/wm_drop_handler.cc
C++
unknown
750
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_WM_WM_DROP_HANDLER_H_ #define UI_PLATFORM_WINDOW_WM_WM_DROP_HANDLER_H_ #include <memory> #include "base/component_export.h" namespace gfx { class PointF; } namespace ui { class PlatformWindow; class OSExchangeData; class COMPONENT_EXPORT(WM) WmDropHandler { public: // Notifies that drag has entered the window. // |point| is in the coordinate space of the PlatformWindow in DIP. // |operation| contains bitmask of ui::DragDropTypes suggested by the source. // |modifiers| contains bitmask of ui::EventFlags that accompany the event. virtual void OnDragEnter(const gfx::PointF& point, std::unique_ptr<OSExchangeData> data, int operation, int modifiers) = 0; // Notifies that drag location has changed. // |point| is in the coordinate space of the PlatformWindow in DIP. // |operation| contains bitmask of ui::DragDropTypes suggested by the source. // |modifiers| contains bitmask of ui::EventFlags that accompany the event. // Returns one of ui::DragDropTypes values selected by the client. virtual int OnDragMotion(const gfx::PointF& point, int operation, int modifiers) = 0; // Notifies that dragged data is dropped. When it doesn't deliver // the dragged data on OnDragEnter, it should put it to |data|. The location // of the drop is the location of the latest DragEnter/DragMotion. If // OSExchangeData is provided on OnDragEnter, the |data| should be same as it. // |modifiers| contains bitmask of ui::EventFlags that accompany the event. virtual void OnDragDrop(std::unique_ptr<OSExchangeData> data, int modifiers) = 0; // Notifies that dragging is left. Must be called before // WmDragHandler::OnDragFinished when the drag session gets cancelled. virtual void OnDragLeave() = 0; protected: virtual ~WmDropHandler() = default; }; COMPONENT_EXPORT(WM) void SetWmDropHandler(PlatformWindow* platform_window, WmDropHandler* drop_handler); COMPONENT_EXPORT(WM) WmDropHandler* GetWmDropHandler(const PlatformWindow& platform_window); } // namespace ui #endif // UI_PLATFORM_WINDOW_WM_WM_DROP_HANDLER_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/wm/wm_drop_handler.h
C++
unknown
2,417
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/wm/wm_move_loop_handler.h" #include "ui/base/class_property.h" #include "ui/platform_window/platform_window.h" DEFINE_UI_CLASS_PROPERTY_TYPE(ui::WmMoveLoopHandler*) namespace ui { DEFINE_UI_CLASS_PROPERTY_KEY(WmMoveLoopHandler*, kWmMoveLoopHandlerKey, nullptr) void SetWmMoveLoopHandler(PlatformWindow* platform_window, WmMoveLoopHandler* drag_handler) { platform_window->SetProperty(kWmMoveLoopHandlerKey, drag_handler); } WmMoveLoopHandler* GetWmMoveLoopHandler(const PlatformWindow& platform_window) { return platform_window.GetProperty(kWmMoveLoopHandlerKey); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/wm/wm_move_loop_handler.cc
C++
unknown
795
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_WM_WM_MOVE_LOOP_HANDLER_H_ #define UI_PLATFORM_WINDOW_WM_WM_MOVE_LOOP_HANDLER_H_ #include "base/component_export.h" namespace gfx { class Vector2d; } namespace ui { class PlatformWindow; // Handler that starts interactive move loop for the PlatformWindow. class COMPONENT_EXPORT(WM) WmMoveLoopHandler { public: // Starts a move loop for tab drag controller. Returns true on success or // false on fail/cancel. virtual bool RunMoveLoop(const gfx::Vector2d& drag_offset) = 0; // Ends the move loop. virtual void EndMoveLoop() = 0; protected: virtual ~WmMoveLoopHandler() {} }; COMPONENT_EXPORT(WM) void SetWmMoveLoopHandler(PlatformWindow* platform_window, WmMoveLoopHandler* drag_handler); COMPONENT_EXPORT(WM) WmMoveLoopHandler* GetWmMoveLoopHandler(const PlatformWindow& platform_window); } // namespace ui #endif // UI_PLATFORM_WINDOW_WM_WM_MOVE_LOOP_HANDLER_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/wm/wm_move_loop_handler.h
C++
unknown
1,087
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/wm/wm_move_resize_handler.h" #include "ui/base/class_property.h" #include "ui/platform_window/platform_window.h" DEFINE_UI_CLASS_PROPERTY_TYPE(WmMoveResizeHandler*) namespace ui { DEFINE_UI_CLASS_PROPERTY_KEY(WmMoveResizeHandler*, kWmMoveResizeHandlerKey, nullptr) void SetWmMoveResizeHandler(PlatformWindow* platform_window, WmMoveResizeHandler* move_resize_handler) { platform_window->SetProperty(kWmMoveResizeHandlerKey, move_resize_handler); } WmMoveResizeHandler* GetWmMoveResizeHandler( const PlatformWindow& platform_window) { return platform_window.GetProperty(kWmMoveResizeHandlerKey); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/platform_window/wm/wm_move_resize_handler.cc
C++
unknown
890
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_PLATFORM_WINDOW_WM_WM_MOVE_RESIZE_HANDLER_H_ #define UI_PLATFORM_WINDOW_WM_WM_MOVE_RESIZE_HANDLER_H_ #include "base/component_export.h" namespace gfx { class Point; } // namespace gfx namespace ui { class PlatformWindow; class COMPONENT_EXPORT(WM) WmMoveResizeHandler { public: // A system window manager starts interactive drag or resize of a window based // on the |hittest| value. The |hittest| value identifies in which direction // the window should be resized or whether it should be moved. See // ui/base/hit_test.h for a concrete example with chromium symbolic names // defined. The |pointer_location_in_px| indicates the position of the button // press with respect to the platform window in screen pixel coordinates, // which is needed when sending a move/resize request in such backends as X11. // See _NET_WM_MOVERESIZE section in // https://specifications.freedesktop.org/wm-spec/1.4/ar01s04.html. // // There is no need to implement this by all the platforms except Ozone/X11 // and Ozone/Wayland, compositors of which support interactive move/resize. // // This API must be used on mouse or touch events, which are targeted for // non-client components (check ui/base/hit_test.h again) except the ones // targeted for components like HTMAXBUTTON. In that case, the mouse events // are used to identify clicks on maximize/minimize/restore buttons located in // the top non-client area of the chromium window. See // WindowEventFilter::OnMouseEvent for a concrete example of how mouse events // are identified as client or non-client. // // When the API is called, there is no way to know that the call was // successful or not. The browser continues performing as usual except that a // system compositor does not send any mouse/keyboard/etc events until user // releases a mouse button. Instead, the compositor sends new bounds, which a // client uses to recreate gpu buffers and redraw visual represantation of the // browser. virtual void DispatchHostWindowDragMovement( int hittest, const gfx::Point& pointer_location_in_px) = 0; protected: virtual ~WmMoveResizeHandler() {} }; COMPONENT_EXPORT(WM) void SetWmMoveResizeHandler(PlatformWindow* platform_window, WmMoveResizeHandler* move_resize_handler); COMPONENT_EXPORT(WM) WmMoveResizeHandler* GetWmMoveResizeHandler( const PlatformWindow& platform_window); } // namespace ui #endif // UI_PLATFORM_WINDOW_WM_WM_MOVE_RESIZE_HANDLER_H_
Zhao-PengFei35/chromium_src_4
ui/platform_window/wm/wm_move_resize_handler.h
C++
unknown
2,674
include_rules = [ "+cc/paint/paint_canvas.h", "+chrome/browser/themes/theme_properties.h", "+printing", "+third_party/skia", "+ui/base", "+ui/color", "+ui/gfx", "+ui/linux", "+ui/native_theme", "+ui/shell_dialogs", "+ui/views", ]
Zhao-PengFei35/chromium_src_4
ui/qt/DEPS
Python
unknown
252
#!/usr/bin/env bash # Copyright 2022 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. set -o nounset set -o errexit URL="http://archive.debian.org/debian/pool/main/q/qtbase-opensource-src" PACKAGE="qtbase5-dev-tools_5.3.2+dfsg-4+deb8u2_amd64.deb" SHA256="7703754f2c230ce6b8b6030b6c1e7e030899aa9f45a415498df04bd5ec061a76" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" TMP_DIR=$(mktemp -d -p "$SCRIPT_DIR") function cleanup { rm -rf "$TMP_DIR" } trap cleanup EXIT cd "$TMP_DIR" wget "$URL/$PACKAGE" echo "$SHA256 $PACKAGE" | shasum -a 256 -c dpkg -x "$PACKAGE" . cat > ../qt_shim_moc.cc <<EOF // Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. EOF cd "$SCRIPT_DIR/../.." "$TMP_DIR/usr/lib/x86_64-linux-gnu/qt5/bin/moc" ui/qt/qt_shim.h \ >> ui/qt/qt_shim_moc.cc git cl format ui/qt/qt_shim_moc.cc
Zhao-PengFei35/chromium_src_4
ui/qt/gen_qt_shim_moc.sh
Shell
unknown
987
#!/usr/bin/env python3 # Copyright 2022 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import subprocess import sys subprocess.check_call(["moc", sys.argv[1], "-o", sys.argv[2]])
Zhao-PengFei35/chromium_src_4
ui/qt/moc_wrapper.py
Python
unknown
280
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/qt/qt_interface.h" #include <cstdlib> #include <cstring> namespace qt { String::String() = default; String::String(const char* str) { if (str) str_ = strdup(str); } String::String(String&& other) { str_ = other.str_; other.str_ = nullptr; } String& String::operator=(String&& other) { free(str_); str_ = other.str_; other.str_ = nullptr; return *this; } String::~String() { free(str_); } Buffer::Buffer() = default; Buffer::Buffer(const uint8_t* data, size_t size) : data_(static_cast<uint8_t*>(malloc(size))), size_(size) { memcpy(data_, data, size); } Buffer::Buffer(Buffer&& other) { data_ = other.data_; size_ = other.size_; other.data_ = nullptr; other.size_ = 0; } Buffer& Buffer::operator=(Buffer&& other) { free(data_); data_ = other.data_; size_ = other.size_; other.data_ = nullptr; other.size_ = 0; return *this; } Buffer::~Buffer() { free(data_); } uint8_t* Buffer::Take() { uint8_t* data = data_; data_ = nullptr; size_ = 0; return data; } } // namespace qt
Zhao-PengFei35/chromium_src_4
ui/qt/qt_interface.cc
C++
unknown
1,199
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_QT_QT_INTERFACE_H_ #define UI_QT_QT_INTERFACE_H_ // This file shouldn't include any standard C++ headers (directly or indirectly) #if defined(__has_attribute) && __has_attribute(no_sanitize) #define DISABLE_CFI_VCALL __attribute__((no_sanitize("cfi-vcall"))) #else #define DISABLE_CFI_VCALL #endif #include <stdint.h> #include <stdlib.h> using SkColor = uint32_t; namespace qt { // std::string cannot be passed over the library boundary, so this class acts // as an interface between QT and Chrome. class String { public: String(); explicit String(const char* str); String(String&& other); String& operator=(String&& other); ~String(); // May be nullptr. const char* c_str() const { return str_; } private: char* str_ = nullptr; }; // A generic bag of bytes. class Buffer { public: Buffer(); // Creates a copy of `data`. Buffer(const uint8_t* data, size_t size); Buffer(Buffer&& other); Buffer& operator=(Buffer&& other); ~Buffer(); // Take ownership of the data in this buffer (resetting `this`). uint8_t* Take(); uint8_t* data() { return data_; } size_t size() const { return size_; } private: uint8_t* data_ = nullptr; size_t size_ = 0; }; enum class FontHinting { kDefault, kNone, kLight, kFull, }; enum class ColorType { kWindowBg, kWindowFg, kHighlightBg, kHighlightFg, kEntryBg, kEntryFg, kButtonBg, kButtonFg, kLight, kMidlight, kDark, kMidground, kShadow, }; enum class ColorState { kNormal, kDisabled, kInactive, }; struct FontRenderParams { bool antialiasing; bool use_bitmaps; FontHinting hinting; }; struct FontDescription { String family; int size_pixels; int size_points; bool is_italic; int weight; }; struct Image { int width = 0; int height = 0; float scale = 1.0f; // The data is stored as ARGB32 (premultiplied). Buffer data_argb; }; class QtInterface { public: class Delegate { public: virtual ~Delegate() = default; virtual void FontChanged() = 0; virtual void ThemeChanged() = 0; }; QtInterface() = default; QtInterface(const QtInterface&) = delete; QtInterface& operator=(const QtInterface&) = delete; virtual ~QtInterface() = default; virtual double GetScaleFactor() const = 0; virtual FontRenderParams GetFontRenderParams() const = 0; virtual FontDescription GetFontDescription() const = 0; virtual Image GetIconForContentType(const String& content_type, int size) const = 0; virtual SkColor GetColor(ColorType role, ColorState state) const = 0; virtual SkColor GetFrameColor(ColorState state, bool use_custom_frame) const = 0; virtual Image DrawHeader(int width, int height, SkColor default_color, ColorState state, bool use_custom_frame) const = 0; virtual int GetCursorBlinkIntervalMs() const = 0; virtual int GetAnimationDurationMs() const = 0; }; } // namespace qt // This should be the only thing exported from qt_shim. extern "C" __attribute__((visibility("default"))) qt::QtInterface* CreateQtInterface(qt::QtInterface::Delegate* delegate, int* argc, char** argv); #endif // UI_QT_QT_INTERFACE_H_
Zhao-PengFei35/chromium_src_4
ui/qt/qt_interface.h
C++
unknown
3,448
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // IMPORTANT NOTE: All QtShim members that use `delegate_` must be decorated // with DISABLE_CFI_VCALL. #include "ui/qt/qt_shim.h" #include <stdio.h> #include <QApplication> #include <QFont> #include <QIcon> #include <QMimeDatabase> #include <QMimeType> #include <QPainter> #include <QPalette> #include <QStyle> #include <QStyleOptionTitleBar> namespace qt { namespace { bool IsStyleItalic(QFont::Style style) { switch (style) { case QFont::Style::StyleNormal: return false; case QFont::Style::StyleItalic: // gfx::Font::FontStyle doesn't support oblique, so treat it as italic. case QFont::Style::StyleOblique: return true; } } FontHinting QtHintingToFontHinting(QFont::HintingPreference hinting) { switch (hinting) { case QFont::PreferDefaultHinting: return FontHinting::kDefault; case QFont::PreferNoHinting: return FontHinting::kNone; case QFont::PreferVerticalHinting: // QT treats vertical hinting as "light" for Freetype: // https://doc.qt.io/qt-5/qfont.html#HintingPreference-enum return FontHinting::kLight; case QFont::PreferFullHinting: return FontHinting::kFull; } } // Obtain the average color of a gradient. SkColor GradientColor(const QGradient& gradient) { QGradientStops stops = gradient.stops(); if (stops.empty()) return qRgba(0, 0, 0, 0); float a = 0; float r = 0; float g = 0; float b = 0; for (int i = 0; i < stops.size(); i++) { // Determine the extents of this stop. The whole gradient interval is [0, // 1], so extend to the endpoint if this is the first or last stop. float left_interval = i == 0 ? stops[i].first : (stops[i].first - stops[i - 1].first) / 2; float right_interval = i == stops.size() - 1 ? 1 - stops[i].first : (stops[i + 1].first - stops[i].first) / 2; float length = left_interval + right_interval; // alpha() returns a value in [0, 255] and alphaF() returns a value in // [0, 1]. The color values are not premultiplied so the RGB channels need // to be multiplied by the alpha (in range [0, 1]) before summing. The // alpha doesn't need to be multiplied, so we just sum color.alpha() in // range [0, 255] directly. const QColor& color = stops[i].second; a += color.alpha() * length; r += color.alphaF() * color.red() * length; g += color.alphaF() * color.green() * length; b += color.alphaF() * color.blue() * length; } return qRgba(r, g, b, a); } // Obtain the average color of a texture. SkColor TextureColor(QImage image) { size_t size = image.width() * image.height(); if (!size) return qRgba(0, 0, 0, 0); if (image.format() != QImage::Format_ARGB32_Premultiplied) image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); size_t a = 0; size_t r = 0; size_t g = 0; size_t b = 0; const auto* pixels = reinterpret_cast<QRgb*>(image.bits()); for (size_t i = 0; i < size; i++) { auto color = QColor::fromRgba(pixels[i]); a += color.alpha(); r += color.red(); g += color.green(); b += color.blue(); } return qRgba(r / size, g / size, b / size, a / size); } SkColor BrushColor(const QBrush& brush) { QColor color = brush.color(); auto alpha_blend = [&](uint8_t alpha) { QColor blended = color; blended.setAlpha(blended.alpha() * alpha / 255); return blended.rgba(); }; switch (brush.style()) { case Qt::SolidPattern: return alpha_blend(0xFF); case Qt::Dense1Pattern: return alpha_blend(0xE0); case Qt::Dense2Pattern: return alpha_blend(0xC0); case Qt::Dense3Pattern: return alpha_blend(0xA0); case Qt::Dense4Pattern: return alpha_blend(0x80); case Qt::Dense5Pattern: return alpha_blend(0x60); case Qt::Dense6Pattern: return alpha_blend(0x40); case Qt::Dense7Pattern: return alpha_blend(0x20); case Qt::NoBrush: return alpha_blend(0x00); case Qt::HorPattern: case Qt::VerPattern: return alpha_blend(0x20); case Qt::CrossPattern: return alpha_blend(0x40); case Qt::BDiagPattern: case Qt::FDiagPattern: return alpha_blend(0x20); case Qt::DiagCrossPattern: return alpha_blend(0x40); case Qt::LinearGradientPattern: case Qt::RadialGradientPattern: case Qt::ConicalGradientPattern: return GradientColor(*brush.gradient()); case Qt::TexturePattern: return TextureColor(brush.textureImage()); } } QPalette::ColorRole ColorTypeToColorRole(ColorType type) { switch (type) { case ColorType::kWindowBg: return QPalette::Window; case ColorType::kWindowFg: return QPalette::WindowText; case ColorType::kHighlightBg: return QPalette::Highlight; case ColorType::kHighlightFg: return QPalette::HighlightedText; case ColorType::kEntryBg: return QPalette::Base; case ColorType::kEntryFg: return QPalette::Text; case ColorType::kButtonBg: return QPalette::Button; case ColorType::kButtonFg: return QPalette::ButtonText; case ColorType::kLight: return QPalette::Light; case ColorType::kMidlight: return QPalette::Midlight; case ColorType::kMidground: return QPalette::Mid; case ColorType::kDark: return QPalette::Dark; case ColorType::kShadow: return QPalette::Shadow; } } QPalette::ColorGroup ColorStateToColorGroup(ColorState state) { switch (state) { case ColorState::kNormal: return QPalette::Normal; case ColorState::kDisabled: return QPalette::Disabled; case ColorState::kInactive: return QPalette::Inactive; } } } // namespace QtShim::QtShim(QtInterface::Delegate* delegate, int* argc, char** argv) : delegate_(delegate), app_(*argc, argv) { connect(&app_, SIGNAL(fontChanged(const QFont&)), this, SLOT(FontChanged(const QFont&))); connect(&app_, SIGNAL(paletteChanged(const QPalette&)), this, SLOT(PaletteChanged(const QPalette&))); } QtShim::~QtShim() = default; double QtShim::GetScaleFactor() const { return app_.devicePixelRatio(); } FontRenderParams QtShim::GetFontRenderParams() const { QFont font = app_.font(); auto style = font.styleStrategy(); return { .antialiasing = !(style & QFont::StyleStrategy::NoAntialias), .use_bitmaps = !!(style & QFont::StyleStrategy::PreferBitmap), .hinting = QtHintingToFontHinting(font.hintingPreference()), }; } FontDescription QtShim::GetFontDescription() const { QFont font = app_.font(); return { .family = String(font.family().toStdString().c_str()), .size_pixels = font.pixelSize(), .size_points = font.pointSize(), .is_italic = IsStyleItalic(font.style()), .weight = font.weight(), }; } Image QtShim::GetIconForContentType(const String& content_type, int size) const { QMimeDatabase db; for (const char* mime : {content_type.c_str(), "application/octet-stream"}) { auto mt = db.mimeTypeForName(mime); for (const auto& name : {mt.iconName(), mt.genericIconName()}) { auto icon = QIcon::fromTheme(name); auto pixmap = icon.pixmap(size); auto image = pixmap.toImage(); if (image.format() != QImage::Format_ARGB32_Premultiplied) image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); if (auto bytes = image.sizeInBytes()) { return {image.width(), image.height(), static_cast<float>(image.devicePixelRatio()), Buffer(image.bits(), bytes)}; } } } return {}; } SkColor QtShim::GetColor(ColorType role, ColorState state) const { return BrushColor(app_.palette().brush(ColorStateToColorGroup(state), ColorTypeToColorRole(role))); } SkColor QtShim::GetFrameColor(ColorState state, bool use_custom_frame) const { constexpr int kSampleSize = 32; return TextureColor(DrawHeaderImpl(kSampleSize, kSampleSize, GetColor(ColorType::kWindowBg, state), state, use_custom_frame)); } int QtShim::GetCursorBlinkIntervalMs() const { return app_.cursorFlashTime(); } int QtShim::GetAnimationDurationMs() const { return app_.style()->styleHint(QStyle::SH_Widget_Animation_Duration); } DISABLE_CFI_VCALL void QtShim::FontChanged(const QFont& font) { delegate_->FontChanged(); } DISABLE_CFI_VCALL void QtShim::PaletteChanged(const QPalette& palette) { delegate_->ThemeChanged(); } Image QtShim::DrawHeader(int width, int height, SkColor default_color, ColorState state, bool use_custom_frame) const { QImage image = DrawHeaderImpl(width, height, default_color, state, use_custom_frame); return {width, height, 1.0f, Buffer(image.bits(), image.sizeInBytes())}; } QImage QtShim::DrawHeaderImpl(int width, int height, SkColor default_color, ColorState state, bool use_custom_frame) const { QImage image(width, height, QImage::Format_ARGB32_Premultiplied); image.fill(default_color); QPainter painter(&image); if (use_custom_frame) { // Chrome renders it's own window border, so clip the border out by // rendering the titlebar larger than the image. constexpr int kBorderWidth = 5; QStyleOptionTitleBar opt; opt.rect = QRect(-kBorderWidth, -kBorderWidth, width + 2 * kBorderWidth, height + 2 * kBorderWidth); if (state == ColorState::kNormal) opt.titleBarState = QStyle::State_Active; app_.style()->drawComplexControl(QStyle::CC_TitleBar, &opt, &painter, nullptr); } else { painter.fillRect( 0, 0, width, height, app_.palette().brush(ColorStateToColorGroup(state), QPalette::Window)); } return image; } } // namespace qt qt::QtInterface* CreateQtInterface(qt::QtInterface::Delegate* delegate, int* argc, char** argv) { return new qt::QtShim(delegate, argc, argv); }
Zhao-PengFei35/chromium_src_4
ui/qt/qt_shim.cc
C++
unknown
10,455
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_QT_QT_SHIM_H_ #define UI_QT_QT_SHIM_H_ #include <QApplication> #include <QImage> #include <QObject> #include "ui/qt/qt_interface.h" namespace qt { // This class directly interacts with QT. It's required to be a QObject // to receive signals from QT via slots. class QtShim : public QObject, public QtInterface { Q_OBJECT public: QtShim(QtInterface::Delegate* delegate, int* argc, char** argv); ~QtShim() override; // QtInterface: double GetScaleFactor() const override; FontRenderParams GetFontRenderParams() const override; FontDescription GetFontDescription() const override; Image GetIconForContentType(const String& content_type, int size) const override; SkColor GetColor(ColorType role, ColorState state) const override; SkColor GetFrameColor(ColorState state, bool use_custom_frame) const override; Image DrawHeader(int width, int height, SkColor default_color, ColorState state, bool use_custom_frame) const override; int GetCursorBlinkIntervalMs() const override; int GetAnimationDurationMs() const override; private slots: void FontChanged(const QFont& font); void PaletteChanged(const QPalette& palette); private: QImage DrawHeaderImpl(int width, int height, SkColor default_color, ColorState state, bool use_custom_frame) const; QtInterface::Delegate* const delegate_; QApplication app_; }; } // namespace qt #endif // UI_QT_QT_SHIM_H_
Zhao-PengFei35/chromium_src_4
ui/qt/qt_shim.h
C++
unknown
1,759
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /**************************************************************************** ** Meta object code from reading C++ file 'qt_shim.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #include "ui/qt/qt_shim.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'qt_shim.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.3.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_qt__QtShim_t { QByteArrayData data[6]; char stringdata[52]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET( \ len, qptrdiff(offsetof(qt_meta_stringdata_qt__QtShim_t, stringdata) + \ ofs - idx * sizeof(QByteArrayData))) static const qt_meta_stringdata_qt__QtShim_t qt_meta_stringdata_qt__QtShim = { {QT_MOC_LITERAL(0, 0, 10), QT_MOC_LITERAL(1, 11, 11), QT_MOC_LITERAL(2, 23, 0), QT_MOC_LITERAL(3, 24, 4), QT_MOC_LITERAL(4, 29, 14), QT_MOC_LITERAL(5, 44, 7)}, "qt::QtShim\0FontChanged\0\0font\0" "PaletteChanged\0palette"}; #undef QT_MOC_LITERAL static const uint qt_meta_data_qt__QtShim[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 24, 2, 0x08 /* Private */, 4, 1, 27, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::QFont, 3, QMetaType::Void, QMetaType::QPalette, 5, 0 // eod }; void qt::QtShim::qt_static_metacall(QObject* _o, QMetaObject::Call _c, int _id, void** _a) { if (_c == QMetaObject::InvokeMetaMethod) { QtShim* _t = static_cast<QtShim*>(_o); switch (_id) { case 0: _t->FontChanged((*reinterpret_cast<const QFont(*)>(_a[1]))); break; case 1: _t->PaletteChanged((*reinterpret_cast<const QPalette(*)>(_a[1]))); break; default:; } } } const QMetaObject qt::QtShim::staticMetaObject = { {&QObject::staticMetaObject, qt_meta_stringdata_qt__QtShim.data, qt_meta_data_qt__QtShim, qt_static_metacall, 0, 0}}; const QMetaObject* qt::QtShim::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void* qt::QtShim::qt_metacast(const char* _clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_qt__QtShim.stringdata)) return static_cast<void*>(const_cast<QtShim*>(this)); if (!strcmp(_clname, "QtInterface")) return static_cast<QtInterface*>(const_cast<QtShim*>(this)); return QObject::qt_metacast(_clname); } int qt::QtShim::qt_metacall(QMetaObject::Call _c, int _id, void** _a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } QT_END_MOC_NAMESPACE
Zhao-PengFei35/chromium_src_4
ui/qt/qt_shim_moc.cc
C++
unknown
3,891
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // IMPORTANT NOTE: All QtUi members that use `shim_` must be decorated // with DISABLE_CFI_VCALL. #include "ui/qt/qt_ui.h" #include <dlfcn.h> #include <algorithm> #include "base/check.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/memory/raw_ptr.h" #include "base/notreached.h" #include "base/path_service.h" #include "base/time/time.h" #include "cc/paint/paint_canvas.h" #include "chrome/browser/themes/theme_properties.h" // nogncheck #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/ime/linux/linux_input_method_context.h" #include "ui/color/color_mixer.h" #include "ui/color/color_provider.h" #include "ui/color/color_recipe.h" #include "ui/color/color_transform.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/font.h" #include "ui/gfx/font_render_params.h" #include "ui/gfx/font_render_params_linux.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia_rep.h" #include "ui/gfx/image/image_skia_source.h" #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/native_theme/native_theme_aura.h" #include "ui/native_theme/native_theme_base.h" #include "ui/qt/qt_interface.h" #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/select_file_policy.h" #include "ui/views/controls/button/label_button_border.h" namespace qt { namespace { int QtWeightToCssWeight(int weight) { struct { int qt_weight; int css_weight; } constexpr kMapping[] = { // https://doc.qt.io/qt-5/qfont.html#Weight-enum {0, 100}, {12, 200}, {25, 300}, {50, 400}, {57, 500}, {63, 600}, {75, 700}, {81, 800}, {87, 900}, {99, 1000}, }; weight = std::clamp(weight, 0, 99); for (size_t i = 0; i < std::size(kMapping) - 1; i++) { const auto& lo = kMapping[i]; const auto& hi = kMapping[i + 1]; if (weight <= hi.qt_weight) { return (weight - lo.qt_weight) * (hi.css_weight - lo.css_weight) / (hi.qt_weight - lo.qt_weight) + lo.css_weight; } } NOTREACHED(); return kMapping[std::size(kMapping) - 1].css_weight; } gfx::FontRenderParams::Hinting QtHintingToGfxHinting( qt::FontHinting hinting, gfx::FontRenderParams::Hinting default_hinting) { switch (hinting) { case FontHinting::kDefault: return default_hinting; case FontHinting::kNone: return gfx::FontRenderParams::HINTING_NONE; case FontHinting::kLight: return gfx::FontRenderParams::HINTING_SLIGHT; case FontHinting::kFull: return gfx::FontRenderParams::HINTING_FULL; } } } // namespace class QtNativeTheme : public ui::NativeThemeAura { public: explicit QtNativeTheme(QtInterface* shim) : ui::NativeThemeAura(/*use_overlay_scrollbars=*/false, /*should_only_use_dark_colors=*/false, ui::SystemTheme::kQt), shim_(shim) {} QtNativeTheme(const QtNativeTheme&) = delete; QtNativeTheme& operator=(const QtNativeTheme&) = delete; ~QtNativeTheme() override = default; void ThemeChanged(bool prefer_dark_theme) { set_use_dark_colors(IsForcedDarkMode() || prefer_dark_theme); set_preferred_color_scheme(CalculatePreferredColorScheme()); NotifyOnNativeThemeUpdated(); } // ui::NativeTheme: DISABLE_CFI_VCALL void PaintFrameTopArea(cc::PaintCanvas* canvas, State state, const gfx::Rect& rect, const FrameTopAreaExtraParams& frame_top_area, ColorScheme color_scheme) const override { auto image = shim_->DrawHeader( rect.width(), rect.height(), frame_top_area.default_background_color, frame_top_area.is_active ? ColorState::kNormal : ColorState::kInactive, frame_top_area.use_custom_frame); SkImageInfo image_info = SkImageInfo::Make( image.width, image.height, kBGRA_8888_SkColorType, kPremul_SkAlphaType); SkBitmap bitmap; bitmap.installPixels( image_info, image.data_argb.Take(), image_info.minRowBytes(), [](void* data, void*) { free(data); }, nullptr); bitmap.setImmutable(); canvas->drawImage(cc::PaintImage::CreateFromBitmap(std::move(bitmap)), rect.x(), rect.y()); } private: raw_ptr<QtInterface> const shim_; }; QtUi::QtUi(ui::LinuxUi* fallback_linux_ui) : fallback_linux_ui_(fallback_linux_ui) {} QtUi::~QtUi() = default; std::unique_ptr<ui::LinuxInputMethodContext> QtUi::CreateInputMethodContext( ui::LinuxInputMethodContextDelegate* delegate) const { return fallback_linux_ui_ ? fallback_linux_ui_->CreateInputMethodContext(delegate) : nullptr; } gfx::FontRenderParams QtUi::GetDefaultFontRenderParams() const { return font_params_; } void QtUi::GetDefaultFontDescription(std::string* family_out, int* size_pixels_out, int* style_out, int* weight_out, gfx::FontRenderParams* params_out) const { if (family_out) *family_out = font_family_; if (size_pixels_out) *size_pixels_out = font_size_pixels_; if (style_out) *style_out = font_style_; if (weight_out) *weight_out = font_weight_; if (params_out) *params_out = font_params_; } ui::SelectFileDialog* QtUi::CreateSelectFileDialog( void* listener, std::unique_ptr<ui::SelectFilePolicy> policy) const { return fallback_linux_ui_ ? fallback_linux_ui_->CreateSelectFileDialog( listener, std::move(policy)) : nullptr; } DISABLE_CFI_DLSYM DISABLE_CFI_VCALL bool QtUi::Initialize() { base::FilePath path; if (!base::PathService::Get(base::DIR_MODULE, &path)) return false; path = path.Append("libqt5_shim.so"); void* libqt_shim = dlopen(path.value().c_str(), RTLD_NOW | RTLD_GLOBAL); if (!libqt_shim) return false; void* create_qt_interface = dlsym(libqt_shim, "CreateQtInterface"); DCHECK(create_qt_interface); cmd_line_ = CopyCmdLine(*base::CommandLine::ForCurrentProcess()); shim_.reset((reinterpret_cast<decltype(&CreateQtInterface)>( create_qt_interface)(this, &cmd_line_.argc, cmd_line_.argv.data()))); native_theme_ = std::make_unique<QtNativeTheme>(shim_.get()); ui::ColorProviderManager::Get().AppendColorProviderInitializer( base::BindRepeating(&QtUi::AddNativeColorMixer, base::Unretained(this))); FontChanged(); return true; } ui::NativeTheme* QtUi::GetNativeTheme() const { return native_theme_.get(); } bool QtUi::GetColor(int id, SkColor* color, bool use_custom_frame) const { auto value = GetColor(id, use_custom_frame); if (value) *color = *value; return value.has_value(); } bool QtUi::GetDisplayProperty(int id, int* result) const { switch (id) { case ThemeProperties::SHOULD_FILL_BACKGROUND_TAB_COLOR: *result = false; return true; default: return false; } } DISABLE_CFI_VCALL void QtUi::GetFocusRingColor(SkColor* color) const { *color = shim_->GetColor(ColorType::kHighlightBg, ColorState::kNormal); } DISABLE_CFI_VCALL void QtUi::GetActiveSelectionBgColor(SkColor* color) const { *color = shim_->GetColor(ColorType::kHighlightBg, ColorState::kNormal); } DISABLE_CFI_VCALL void QtUi::GetActiveSelectionFgColor(SkColor* color) const { *color = shim_->GetColor(ColorType::kHighlightFg, ColorState::kNormal); } DISABLE_CFI_VCALL void QtUi::GetInactiveSelectionBgColor(SkColor* color) const { *color = shim_->GetColor(ColorType::kHighlightBg, ColorState::kInactive); } DISABLE_CFI_VCALL void QtUi::GetInactiveSelectionFgColor(SkColor* color) const { *color = shim_->GetColor(ColorType::kHighlightFg, ColorState::kInactive); } DISABLE_CFI_VCALL base::TimeDelta QtUi::GetCursorBlinkInterval() const { return base::Milliseconds(shim_->GetCursorBlinkIntervalMs()); } DISABLE_CFI_VCALL gfx::Image QtUi::GetIconForContentType(const std::string& content_type, int size, float scale) const { Image image = shim_->GetIconForContentType(String(content_type.c_str()), size * scale); if (!image.data_argb.size()) return {}; SkImageInfo image_info = SkImageInfo::Make( image.width, image.height, kBGRA_8888_SkColorType, kPremul_SkAlphaType); SkBitmap bitmap; bitmap.installPixels( image_info, image.data_argb.Take(), image_info.minRowBytes(), [](void* data, void*) { free(data); }, nullptr); gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFromBitmap(bitmap, image.scale); image_skia.MakeThreadSafe(); return gfx::Image(image_skia); } QtUi::WindowFrameAction QtUi::GetWindowFrameAction( WindowFrameActionSource source) { // QT doesn't have settings for the window frame action since it prefers // server-side decorations. So use the hardcoded behavior of a QMdiSubWindow, // which also matches the default Chrome behavior when there's no LinuxUI. switch (source) { case WindowFrameActionSource::kDoubleClick: return WindowFrameAction::kToggleMaximize; case WindowFrameActionSource::kMiddleClick: return WindowFrameAction::kNone; case WindowFrameActionSource::kRightClick: return WindowFrameAction::kMenu; } } DISABLE_CFI_VCALL float QtUi::GetDeviceScaleFactor() const { return shim_->GetScaleFactor(); } DISABLE_CFI_VCALL bool QtUi::PreferDarkTheme() const { return color_utils::IsDark( shim_->GetColor(ColorType::kWindowBg, ColorState::kNormal)); } DISABLE_CFI_VCALL bool QtUi::AnimationsEnabled() const { return shim_->GetAnimationDurationMs() > 0; } void QtUi::AddWindowButtonOrderObserver( ui::WindowButtonOrderObserver* observer) { if (fallback_linux_ui_) fallback_linux_ui_->AddWindowButtonOrderObserver(observer); } void QtUi::RemoveWindowButtonOrderObserver( ui::WindowButtonOrderObserver* observer) { if (fallback_linux_ui_) fallback_linux_ui_->RemoveWindowButtonOrderObserver(observer); } std::unique_ptr<ui::NavButtonProvider> QtUi::CreateNavButtonProvider() { // QT prefers server-side decorations. return nullptr; } ui::WindowFrameProvider* QtUi::GetWindowFrameProvider(bool solid_frame) { // QT prefers server-side decorations. return nullptr; } base::flat_map<std::string, std::string> QtUi::GetKeyboardLayoutMap() { return fallback_linux_ui_ ? fallback_linux_ui_->GetKeyboardLayoutMap() : base::flat_map<std::string, std::string>{}; } std::string QtUi::GetCursorThemeName() { // This is only used on X11 where QT obtains the cursor theme from XSettings. // However, ui/base/x/x11_cursor_loader.cc already handles this. return std::string(); } int QtUi::GetCursorThemeSize() { // This is only used on X11 where QT obtains the cursor size from XSettings. // However, ui/base/x/x11_cursor_loader.cc already handles this. return 0; } bool QtUi::GetTextEditCommandsForEvent( const ui::Event& event, std::vector<ui::TextEditCommandAuraLinux>* commands) { // QT doesn't have "key themes" (eg. readline bindings) like GTK. return false; } #if BUILDFLAG(ENABLE_PRINTING) printing::PrintDialogLinuxInterface* QtUi::CreatePrintDialog( printing::PrintingContextLinux* context) { return fallback_linux_ui_ ? fallback_linux_ui_->CreatePrintDialog(context) : nullptr; } gfx::Size QtUi::GetPdfPaperSize(printing::PrintingContextLinux* context) { return fallback_linux_ui_ ? fallback_linux_ui_->GetPdfPaperSize(context) : gfx::Size(); } #endif DISABLE_CFI_VCALL void QtUi::FontChanged() { auto params = shim_->GetFontRenderParams(); auto desc = shim_->GetFontDescription(); font_family_ = desc.family.c_str(); if (desc.size_pixels > 0) { font_size_pixels_ = desc.size_pixels; font_size_points_ = font_size_pixels_ / GetDeviceScaleFactor(); } else { font_size_points_ = desc.size_points; font_size_pixels_ = font_size_points_ * GetDeviceScaleFactor(); } font_style_ = desc.is_italic ? gfx::Font::ITALIC : gfx::Font::NORMAL; font_weight_ = QtWeightToCssWeight(desc.weight); gfx::FontRenderParamsQuery query; query.families = {font_family_}; query.pixel_size = font_size_pixels_; query.point_size = font_size_points_; query.style = font_style_; query.weight = static_cast<gfx::Font::Weight>(font_weight_); gfx::FontRenderParams fc_params; gfx::QueryFontconfig(query, &fc_params, nullptr); font_params_ = gfx::FontRenderParams{ .antialiasing = params.antialiasing, .use_bitmaps = params.use_bitmaps, .hinting = QtHintingToGfxHinting(params.hinting, fc_params.hinting), // QT doesn't expose a subpixel rendering setting, so fall back to // fontconfig for it. .subpixel_rendering = fc_params.subpixel_rendering, }; } void QtUi::ThemeChanged() { native_theme_->ThemeChanged(PreferDarkTheme()); } DISABLE_CFI_VCALL void QtUi::AddNativeColorMixer(ui::ColorProvider* provider, const ui::ColorProviderManager::Key& key) { if (key.system_theme != ui::SystemTheme::kQt) return; ui::ColorMixer& mixer = provider->AddMixer(); // These color constants are required by native_chrome_color_mixer_linux.cc struct { ui::ColorId id; ColorType role; ColorState state = ColorState::kNormal; } const kMaps[] = { // Core colors {ui::kColorAccent, ColorType::kHighlightBg}, {ui::kColorDisabledForeground, ColorType::kWindowFg, ColorState::kDisabled}, {ui::kColorEndpointBackground, ColorType::kEntryBg}, {ui::kColorEndpointForeground, ColorType::kEntryFg}, {ui::kColorItemHighlight, ColorType::kHighlightBg}, {ui::kColorItemSelectionBackground, ColorType::kHighlightBg}, {ui::kColorMenuSelectionBackground, ColorType::kHighlightBg}, {ui::kColorMidground, ColorType::kMidground}, {ui::kColorPrimaryBackground, ColorType::kWindowBg}, {ui::kColorPrimaryForeground, ColorType::kWindowFg}, {ui::kColorSecondaryForeground, ColorType::kWindowFg, ColorState::kDisabled}, {ui::kColorSubtleAccent, ColorType::kHighlightBg, ColorState::kInactive}, {ui::kColorSubtleEmphasisBackground, ColorType::kWindowBg}, {ui::kColorTextSelectionBackground, ColorType::kHighlightBg}, {ui::kColorTextSelectionForeground, ColorType::kHighlightFg}, // UI element colors {ui::kColorMenuBackground, ColorType::kEntryBg}, {ui::kColorMenuItemBackgroundHighlighted, ColorType::kHighlightBg}, {ui::kColorMenuItemBackgroundSelected, ColorType::kHighlightBg}, {ui::kColorMenuItemForeground, ColorType::kEntryFg}, {ui::kColorMenuItemForegroundHighlighted, ColorType::kHighlightFg}, {ui::kColorMenuItemForegroundSelected, ColorType::kHighlightFg}, // Platform-specific UI elements {ui::kColorNativeButtonBorder, ColorType::kMidground}, {ui::kColorNativeHeaderButtonBorderActive, ColorType::kMidground}, {ui::kColorNativeHeaderButtonBorderInactive, ColorType::kMidground, ColorState::kInactive}, {ui::kColorNativeHeaderSeparatorBorderActive, ColorType::kMidground}, {ui::kColorNativeHeaderSeparatorBorderInactive, ColorType::kMidground, ColorState::kInactive}, {ui::kColorNativeLabelForeground, ColorType::kWindowFg}, {ui::kColorNativeTextfieldBorderUnfocused, ColorType::kMidground, ColorState::kInactive}, {ui::kColorNativeToolbarBackground, ColorType::kButtonBg}, }; for (const auto& map : kMaps) mixer[map.id] = {shim_->GetColor(map.role, map.state)}; const bool use_custom_frame = key.frame_type == ui::ColorProviderManager::FrameType::kChromium; mixer[ui::kColorFrameActive] = { shim_->GetFrameColor(ColorState::kNormal, use_custom_frame)}; mixer[ui::kColorFrameInactive] = { shim_->GetFrameColor(ColorState::kInactive, use_custom_frame)}; const SkColor button_fg = shim_->GetColor(ColorType::kButtonFg, ColorState::kNormal); mixer[ui::kColorNativeTabForegroundInactiveFrameActive] = ui::BlendForMinContrast({button_fg}, {ui::kColorFrameActive}); mixer[ui::kColorNativeTabForegroundInactiveFrameInactive] = ui::BlendForMinContrast({button_fg}, {ui::kColorFrameInactive}); } DISABLE_CFI_VCALL absl::optional<SkColor> QtUi::GetColor(int id, bool use_custom_frame) const { switch (id) { case ThemeProperties::COLOR_LOCATION_BAR_BORDER: return shim_->GetColor(ColorType::kEntryFg, ColorState::kNormal); case ThemeProperties::COLOR_TOOLBAR_CONTENT_AREA_SEPARATOR: return shim_->GetColor(ColorType::kButtonFg, ColorState::kNormal); case ThemeProperties::COLOR_TOOLBAR_VERTICAL_SEPARATOR: return shim_->GetColor(ColorType::kButtonFg, ColorState::kNormal); case ThemeProperties::COLOR_NTP_BACKGROUND: return shim_->GetColor(ColorType::kEntryBg, ColorState::kNormal); case ThemeProperties::COLOR_NTP_TEXT: return shim_->GetColor(ColorType::kEntryFg, ColorState::kNormal); case ThemeProperties::COLOR_NTP_HEADER: return shim_->GetColor(ColorType::kButtonFg, ColorState::kNormal); case ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON: return shim_->GetColor(ColorType::kWindowFg, ColorState::kNormal); case ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON_HOVERED: return shim_->GetColor(ColorType::kWindowFg, ColorState::kNormal); case ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON_PRESSED: return shim_->GetColor(ColorType::kWindowFg, ColorState::kNormal); case ThemeProperties::COLOR_TOOLBAR_TEXT: return shim_->GetColor(ColorType::kWindowFg, ColorState::kNormal); case ThemeProperties::COLOR_NTP_LINK: return shim_->GetColor(ColorType::kHighlightBg, ColorState::kNormal); case ThemeProperties::COLOR_FRAME_ACTIVE: return shim_->GetFrameColor(ColorState::kNormal, use_custom_frame); case ThemeProperties::COLOR_FRAME_INACTIVE: return shim_->GetFrameColor(ColorState::kInactive, use_custom_frame); case ThemeProperties::COLOR_FRAME_ACTIVE_INCOGNITO: return shim_->GetFrameColor(ColorState::kNormal, use_custom_frame); case ThemeProperties::COLOR_FRAME_INACTIVE_INCOGNITO: return shim_->GetFrameColor(ColorState::kInactive, use_custom_frame); case ThemeProperties::COLOR_TOOLBAR: return shim_->GetColor(ColorType::kButtonBg, ColorState::kNormal); case ThemeProperties::COLOR_TAB_BACKGROUND_ACTIVE_FRAME_ACTIVE: return shim_->GetColor(ColorType::kButtonBg, ColorState::kNormal); case ThemeProperties::COLOR_TAB_BACKGROUND_ACTIVE_FRAME_INACTIVE: return shim_->GetColor(ColorType::kButtonBg, ColorState::kInactive); case ThemeProperties::COLOR_TAB_FOREGROUND_INACTIVE_FRAME_ACTIVE: return color_utils::BlendForMinContrast( shim_->GetColor(ColorType::kButtonBg, ColorState::kNormal), shim_->GetFrameColor(ColorState::kNormal, use_custom_frame)) .color; case ThemeProperties::COLOR_TAB_FOREGROUND_INACTIVE_FRAME_INACTIVE: return color_utils::BlendForMinContrast( shim_->GetColor(ColorType::kButtonBg, ColorState::kInactive), shim_->GetFrameColor(ColorState::kInactive, use_custom_frame)) .color; case ThemeProperties::COLOR_TAB_STROKE_FRAME_ACTIVE: return color_utils::BlendForMinContrast( shim_->GetColor(ColorType::kButtonBg, ColorState::kNormal), shim_->GetColor(ColorType::kButtonBg, ColorState::kNormal), SK_ColorBLACK, 2.0) .color; case ThemeProperties::COLOR_TAB_STROKE_FRAME_INACTIVE: return color_utils::BlendForMinContrast( shim_->GetColor(ColorType::kButtonBg, ColorState::kInactive), shim_->GetColor(ColorType::kButtonBg, ColorState::kInactive), SK_ColorBLACK, 2.0) .color; default: return absl::nullopt; } } std::unique_ptr<ui::LinuxUiAndTheme> CreateQtUi( ui::LinuxUi* fallback_linux_ui) { return std::make_unique<QtUi>(fallback_linux_ui); } } // namespace qt
Zhao-PengFei35/chromium_src_4
ui/qt/qt_ui.cc
C++
unknown
20,377
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_QT_QT_UI_H_ #define UI_QT_QT_UI_H_ #include <memory> #include "base/component_export.h" #include "printing/buildflags/buildflags.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/color/color_provider.h" #include "ui/color/color_provider_manager.h" #include "ui/gfx/font_render_params.h" #include "ui/linux/linux_ui.h" #include "ui/qt/qt_interface.h" #if BUILDFLAG(ENABLE_PRINTING) #include "printing/printing_context_linux.h" // nogncheck #endif namespace qt { class QtNativeTheme; // Interface to QT desktop features. class QtUi : public ui::LinuxUiAndTheme, QtInterface::Delegate { public: explicit QtUi(ui::LinuxUi* fallback_linux_ui); QtUi(const QtUi&) = delete; QtUi& operator=(const QtUi&) = delete; ~QtUi() override; // ui::LinuxUi: bool Initialize() override; base::TimeDelta GetCursorBlinkInterval() const override; gfx::Image GetIconForContentType(const std::string& content_type, int size, float scale) const override; float GetDeviceScaleFactor() const override; base::flat_map<std::string, std::string> GetKeyboardLayoutMap() override; #if BUILDFLAG(ENABLE_PRINTING) printing::PrintDialogLinuxInterface* CreatePrintDialog( printing::PrintingContextLinux* context) override; gfx::Size GetPdfPaperSize(printing::PrintingContextLinux* context) override; #endif ui::SelectFileDialog* CreateSelectFileDialog( void* listener, std::unique_ptr<ui::SelectFilePolicy> policy) const override; std::string GetCursorThemeName() override; int GetCursorThemeSize() override; std::unique_ptr<ui::LinuxInputMethodContext> CreateInputMethodContext( ui::LinuxInputMethodContextDelegate* delegate) const override; bool GetTextEditCommandsForEvent( const ui::Event& event, std::vector<ui::TextEditCommandAuraLinux>* commands) override; gfx::FontRenderParams GetDefaultFontRenderParams() const override; void GetDefaultFontDescription( std::string* family_out, int* size_pixels_out, int* style_out, int* weight_out, gfx::FontRenderParams* params_out) const override; bool AnimationsEnabled() const override; void AddWindowButtonOrderObserver( ui::WindowButtonOrderObserver* observer) override; void RemoveWindowButtonOrderObserver( ui::WindowButtonOrderObserver* observer) override; WindowFrameAction GetWindowFrameAction( WindowFrameActionSource source) override; // ui::LinuxUiTheme: ui::NativeTheme* GetNativeTheme() const override; bool GetColor(int id, SkColor* color, bool use_custom_frame) const override; bool GetDisplayProperty(int id, int* result) const override; void GetFocusRingColor(SkColor* color) const override; void GetActiveSelectionBgColor(SkColor* color) const override; void GetActiveSelectionFgColor(SkColor* color) const override; void GetInactiveSelectionBgColor(SkColor* color) const override; void GetInactiveSelectionFgColor(SkColor* color) const override; bool PreferDarkTheme() const override; std::unique_ptr<ui::NavButtonProvider> CreateNavButtonProvider() override; ui::WindowFrameProvider* GetWindowFrameProvider(bool solid_frame) override; // QtInterface::Delegate: void FontChanged() override; void ThemeChanged() override; private: void AddNativeColorMixer(ui::ColorProvider* provider, const ui::ColorProviderManager::Key& key); absl::optional<SkColor> GetColor(int id, bool use_custom_frame) const; // TODO(https://crbug.com/1317782): This is a fallback for any unimplemented // functionality in the QT backend and should eventually be removed. ui::LinuxUi* const fallback_linux_ui_; // QT modifies argc and argv, and they must be kept alive while // `shim_` is alive. CmdLineArgs cmd_line_; // Cached default font settings. std::string font_family_; int font_size_pixels_ = 0; int font_size_points_ = 0; gfx::Font::FontStyle font_style_ = gfx::Font::NORMAL; int font_weight_; gfx::FontRenderParams font_params_; std::unique_ptr<QtInterface> shim_; std::unique_ptr<QtNativeTheme> native_theme_; }; // This should be the only symbol exported from this component. COMPONENT_EXPORT(QT) std::unique_ptr<ui::LinuxUiAndTheme> CreateQtUi(ui::LinuxUi* fallback_linux_ui); } // namespace qt #endif // UI_QT_QT_UI_H_
Zhao-PengFei35/chromium_src_4
ui/qt/qt_ui.h
C++
unknown
4,530
# Copyright 2012 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for Chromium UI resources. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools, and see https://chromium.googlesource.com/chromium/src/+/main/styleguide/web/web.md for the rules we're checking against here. """ USE_PYTHON3 = True def CheckChangeOnUpload(input_api, output_api): return _CommonChecks(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return _CommonChecks(input_api, output_api) def _CommonChecks(input_api, output_api): """Checks common to both upload and commit.""" results = [] resources = input_api.PresubmitLocalPath() # List of paths with their associated scale factor. This is used to verify # that the images modified in one are the correct scale of the other. path_scales = [ [(100, 'default_100_percent/'), (200, 'default_200_percent/')], ] import sys old_path = sys.path try: sys.path = [resources] + old_path from resource_check import resource_scale_factors for paths in path_scales: results.extend(resource_scale_factors.ResourceScaleFactors( input_api, output_api, paths).RunChecks()) finally: sys.path = old_path return results
Zhao-PengFei35/chromium_src_4
ui/resources/PRESUBMIT.py
Python
unknown
1,405
# Copyright 2016 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for Chromium browser resources. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools, and see https://chromium.googlesource.com/chromium/src/+/main/styleguide/web/web.md for the rules we're checking against here. """ import os import sys class IcoFiles(object): """Verifier of ICO files for Chromium resources. """ def __init__(self, input_api, output_api): """ Initializes IcoFiles with path.""" self.input_api = input_api self.output_api = output_api tool_path = input_api.os_path.join(input_api.PresubmitLocalPath(), '../../../tools/resources') sys.path.insert(0, tool_path) def RunChecks(self): """Verifies the correctness of the ICO files. Returns: An array of presubmit errors if any ICO files were broken in some way. """ results = [] affected_files = self.input_api.AffectedFiles(include_deletes=False) for f in affected_files: path = f.LocalPath() if os.path.splitext(path)[1].lower() != '.ico': continue # Import this module from here (to avoid importing it in the highly common # case where there are no ICO files being changed). import ico_tools repository_path = self.input_api.change.RepositoryRoot() with open(os.path.join(repository_path, path), 'rb') as ico_file: errors = list(ico_tools.LintIcoFile(ico_file)) if errors: error_string = '\n'.join(' * ' + e for e in errors) results.append(self.output_api.PresubmitError( '%s: This file does not meet the standards for Chromium ICO ' 'files.\n%s\n Please run ' 'tools/resources/optimize-ico-files.py on this file. See ' 'chrome/app/theme/README for details.' % (path, error_string))) return results
Zhao-PengFei35/chromium_src_4
ui/resources/resource_check/ico_files.py
Python
unknown
2,043
# Copyright 2012 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for Chromium browser resources. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools, and see https://chromium.googlesource.com/chromium/src/+/main/styleguide/web/web.md for the rules we're checking against here. """ import os import struct class InvalidPNGException(Exception): pass class ResourceScaleFactors(object): """Verifier of image dimensions for Chromium resources. This class verifies the image dimensions of resources in the various resource subdirectories. Attributes: paths: An array of tuples giving the folders to check and their relevant scale factors. For example: [(100, 'default_100_percent'), (200, 'default_200_percent')] """ def __init__(self, input_api, output_api, paths): """ Initializes ResourceScaleFactors with paths.""" self.input_api = input_api self.output_api = output_api self.paths = paths def RunChecks(self): """Verifies the scale factors of resources being added or modified. Returns: An array of presubmit errors if any images were detected not having the correct dimensions. """ def ImageSize(filename): with open(filename, 'rb', buffering=0) as f: data = f.read(24) if data[:8] != b'\x89PNG\r\n\x1A\n' or data[12:16] != b'IHDR': raise InvalidPNGException return struct.unpack('>ii', data[16:24]) # Returns a list of valid scaled image sizes. The valid sizes are the # floor and ceiling of (base_size * scale_percent / 100). This is equivalent # to requiring that the actual scaled size is less than one pixel away from # the exact scaled size. def ValidSizes(base_size, scale_percent): return sorted(set([(base_size * scale_percent) / 100, (base_size * scale_percent + 99) / 100])) repository_path = self.input_api.os_path.relpath( self.input_api.PresubmitLocalPath(), self.input_api.change.RepositoryRoot()) results = [] # Check for affected files in any of the paths specified. affected_files = self.input_api.AffectedFiles(include_deletes=False) files = [] for f in affected_files: for path_spec in self.paths: path_root = self.input_api.os_path.join( repository_path, path_spec[1]) if (f.LocalPath().endswith('.png') and f.LocalPath().startswith(path_root)): # Only save the relative path from the resource directory. relative_path = self.input_api.os_path.relpath(f.LocalPath(), path_root) if relative_path not in files: files.append(relative_path) corrupt_png_error = ('Corrupt PNG in file %s. Note that binaries are not ' 'correctly uploaded to the code review tool and must be directly ' 'submitted using the dcommit command.') for f in files: base_image = self.input_api.os_path.join(self.paths[0][1], f) if not os.path.exists(base_image): results.append(self.output_api.PresubmitError( 'Base image %s does not exist' % self.input_api.os_path.join( repository_path, base_image))) continue try: base_dimensions = ImageSize(base_image) except InvalidPNGException: results.append(self.output_api.PresubmitError(corrupt_png_error % self.input_api.os_path.join(repository_path, base_image))) continue # Find all scaled versions of the base image and verify their sizes. for i in range(1, len(self.paths)): image_path = self.input_api.os_path.join(self.paths[i][1], f) if not os.path.exists(image_path): continue # Ensure that each image for a particular scale factor is the # correct scale of the base image. try: scaled_dimensions = ImageSize(image_path) except InvalidPNGException: results.append(self.output_api.PresubmitError(corrupt_png_error % self.input_api.os_path.join(repository_path, image_path))) continue for dimension_name, base_size, scaled_size in zip( ('width', 'height'), base_dimensions, scaled_dimensions): valid_sizes = ValidSizes(base_size, self.paths[i][0]) if scaled_size not in valid_sizes: results.append(self.output_api.PresubmitError( 'Image %s has %s %d, expected to be %s' % ( self.input_api.os_path.join(repository_path, image_path), dimension_name, scaled_size, ' or '.join(map(str, valid_sizes))))) return results
Zhao-PengFei35/chromium_src_4
ui/resources/resource_check/resource_scale_factors.py
Python
unknown
4,848
include_rules = [ "+chromeos/crosapi", "+chromeos/lacros", "+components/dbus/thread_linux", "+components/remote_cocoa", "+dbus", "+mojo/core/embedder", "+mojo/public/cpp/bindings", "+ui/android/window_android.h", "+ui/aura", "+ui/base", "+ui/gfx", "+ui/linux", "+ui/platform_window", "+ui/strings/grit/ui_strings.h", ]
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/DEPS
Python
unknown
347
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/base_shell_dialog.h" namespace ui { BaseShellDialog::~BaseShellDialog() {} } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/base_shell_dialog.cc
C++
unknown
268
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_BASE_SHELL_DIALOG_H_ #define UI_SHELL_DIALOGS_BASE_SHELL_DIALOG_H_ #include "ui/gfx/native_widget_types.h" #include "ui/shell_dialogs/shell_dialogs_export.h" namespace ui { // A base class for shell dialogs. class SHELL_DIALOGS_EXPORT BaseShellDialog { public: // Returns true if a shell dialog box is currently being shown modally // to the specified owner. virtual bool IsRunning(gfx::NativeWindow owning_window) const = 0; // Notifies the dialog box that the listener has been destroyed and it should // no longer be sent notifications. virtual void ListenerDestroyed() = 0; protected: virtual ~BaseShellDialog(); }; } // namespace ui #endif // UI_SHELL_DIALOGS_BASE_SHELL_DIALOG_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/base_shell_dialog.h
C++
unknown
881
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/base_shell_dialog_win.h" #include <algorithm> #include "base/no_destructor.h" #include "base/task/single_thread_task_runner.h" #include "base/task/thread_pool.h" #include "base/win/scoped_com_initializer.h" namespace ui { namespace { // Creates a SingleThreadTaskRunner to run a shell dialog on. Each dialog // requires its own dedicated single-threaded sequence otherwise in some // situations where a singleton owns a single instance of this object we can // have a situation where a modal dialog in one window blocks the appearance // of a modal dialog in another. scoped_refptr<base::SingleThreadTaskRunner> CreateDialogTaskRunner() { return base::ThreadPool::CreateCOMSTATaskRunner( {base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, base::MayBlock()}, base::SingleThreadTaskRunnerThreadMode::DEDICATED); } // Enables the window |owner|. Can only be run from the UI thread. void SetOwnerEnabled(HWND owner, bool enabled) { if (IsWindow(owner)) EnableWindow(owner, enabled); } } // namespace BaseShellDialogImpl::RunState::RunState() = default; BaseShellDialogImpl::RunState::~RunState() = default; // static int BaseShellDialogImpl::instance_count_ = 0; BaseShellDialogImpl::BaseShellDialogImpl() { ++instance_count_; } BaseShellDialogImpl::~BaseShellDialogImpl() { // All runs should be complete by the time this is called! if (--instance_count_ == 0) DCHECK(GetOwners().empty()); } // static BaseShellDialogImpl::Owners& BaseShellDialogImpl::GetOwners() { static base::NoDestructor<BaseShellDialogImpl::Owners> owners; return *owners; } // static void BaseShellDialogImpl::DisableOwner(HWND owner) { if (owner) owner = GetAncestor(owner, GA_ROOT); SetOwnerEnabled(owner, false); } std::unique_ptr<BaseShellDialogImpl::RunState> BaseShellDialogImpl::BeginRun( HWND owner) { if (owner) owner = GetAncestor(owner, GA_ROOT); // Cannot run a modal shell dialog if one is already running for this owner. DCHECK(!IsRunningDialogForOwner(owner)); // The owner must be a top level window, otherwise we could end up with two // entries in our map for the same top level window. DCHECK(!owner || owner == GetAncestor(owner, GA_ROOT)); auto run_state = std::make_unique<RunState>(); run_state->dialog_task_runner = CreateDialogTaskRunner(); run_state->owner = owner; if (owner) { GetOwners().insert(owner); DisableOwner(owner); } return run_state; } void BaseShellDialogImpl::EndRun(std::unique_ptr<RunState> run_state) { if (run_state->owner) { DCHECK(IsRunningDialogForOwner(run_state->owner)); SetOwnerEnabled(run_state->owner, true); DCHECK(GetOwners().find(run_state->owner) != GetOwners().end()); GetOwners().erase(run_state->owner); } } bool BaseShellDialogImpl::IsRunningDialogForOwner(HWND owner) const { if (owner) owner = GetAncestor(owner, GA_ROOT); return (owner && GetOwners().find(owner) != GetOwners().end()); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/base_shell_dialog_win.cc
C++
unknown
3,183
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_BASE_SHELL_DIALOG_WIN_H_ #define UI_SHELL_DIALOGS_BASE_SHELL_DIALOG_WIN_H_ #include <shlobj.h> #include <memory> #include <set> #include "base/memory/scoped_refptr.h" #include "ui/shell_dialogs/base_shell_dialog.h" #include "ui/shell_dialogs/shell_dialogs_export.h" namespace base { class SingleThreadTaskRunner; } namespace ui { /////////////////////////////////////////////////////////////////////////////// // A base class for all shell dialog implementations that handles showing a // shell dialog modally on its own thread. class SHELL_DIALOGS_EXPORT BaseShellDialogImpl { public: BaseShellDialogImpl(); BaseShellDialogImpl(const BaseShellDialogImpl&) = delete; BaseShellDialogImpl& operator=(const BaseShellDialogImpl&) = delete; virtual ~BaseShellDialogImpl(); // Disables the window |owner|. Can be run from either the ui or the dialog // thread. This function is called on the dialog thread after the modal // Windows Common dialog functions return because Windows automatically // re-enables the owning window when those functions return, but we don't // actually want them to be re-enabled until the response of the dialog // propagates back to the UI thread, so we disable the owner manually after // the Common dialog function returns. static void DisableOwner(HWND owner); protected: // Represents a run of a dialog. class SHELL_DIALOGS_EXPORT RunState { public: RunState(); RunState(const RunState&) = delete; RunState& operator=(const RunState&) = delete; ~RunState(); // Owning HWND, may be null. HWND owner; // Dedicated sequence on which the dialog runs. scoped_refptr<base::SingleThreadTaskRunner> dialog_task_runner; }; // Called at the beginning of a modal dialog run. Disables the owner window // and tracks it. Returns the dedicated single-threaded sequence that the // dialog will be run on. std::unique_ptr<RunState> BeginRun(HWND owner); // Cleans up after a dialog run. If the run_state has a valid HWND this makes // sure that the window is enabled. This is essential because BeginRun // aggressively guards against multiple modal dialogs per HWND. Must be called // on the UI thread after the result of the dialog has been determined. void EndRun(std::unique_ptr<RunState> run_state); // Returns true if a modal shell dialog is currently active for the specified // owner. Must be called on the UI thread. bool IsRunningDialogForOwner(HWND owner) const; private: typedef std::set<HWND> Owners; // A list of windows that currently own active shell dialogs for this // instance. For example, if the DownloadManager owns an instance of this // object and there are two browser windows open both with Save As dialog // boxes active, this list will consist of the two browser windows' HWNDs. // The derived class must call EndRun once the dialog is done showing to // remove the owning HWND from this list. // This object is static since it is maintained for all instances of this // object - i.e. you can't have two file pickers open for the // same owner, even though they might be represented by different instances // of this object. // This set only contains non-null HWNDs. NULL hwnds are not added to this // list. static Owners& GetOwners(); static int instance_count_; }; } // namespace ui #endif // UI_SHELL_DIALOGS_BASE_SHELL_DIALOG_WIN_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/base_shell_dialog_win.h
C++
unknown
3,590
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/execute_select_file_win.h" #include <shlobj.h> #include <wrl/client.h> #include "base/files/file.h" #include "base/files/file_util.h" #include "base/functional/callback.h" #include "base/strings/string_util.h" #include "base/threading/hang_watcher.h" #include "base/win/com_init_util.h" #include "base/win/registry.h" #include "base/win/scoped_co_mem.h" #include "base/win/shortcut.h" #include "ui/base/l10n/l10n_util.h" #include "ui/shell_dialogs/base_shell_dialog_win.h" #include "ui/shell_dialogs/select_file_utils_win.h" #include "ui/strings/grit/ui_strings.h" namespace ui { namespace { // Distinguish directories from regular files. bool IsDirectory(const base::FilePath& path) { base::File::Info file_info; return base::GetFileInfo(path, &file_info) ? file_info.is_directory : path.EndsWithSeparator(); } // Sets which path is going to be open when the dialog will be shown. If // |default_path| is not only a directory, also sets the contents of the text // box equals to the basename of the path. bool SetDefaultPath(IFileDialog* file_dialog, const base::FilePath& default_path) { if (default_path.empty()) return true; base::FilePath default_folder; base::FilePath default_file_name; if (IsDirectory(default_path)) { default_folder = default_path; } else { default_folder = default_path.DirName(); std::wstring sanitized = RemoveEnvVarFromFileName<wchar_t>( default_path.BaseName().value(), std::wstring(L"%")); default_file_name = base::FilePath(sanitized); } // Do not fail the file dialog operation if the specified folder is invalid. Microsoft::WRL::ComPtr<IShellItem> default_folder_shell_item; if (SUCCEEDED(SHCreateItemFromParsingName( default_folder.value().c_str(), nullptr, IID_PPV_ARGS(&default_folder_shell_item)))) { if (FAILED(file_dialog->SetFolder(default_folder_shell_item.Get()))) return false; } return SUCCEEDED(file_dialog->SetFileName(default_file_name.value().c_str())); } // Sets the file extension filters on the dialog. bool SetFilters(IFileDialog* file_dialog, const std::vector<FileFilterSpec>& filter, int filter_index) { if (filter.empty()) return true; // A COMDLG_FILTERSPEC instance does not own any memory. |filter| must still // be alive at the time the dialog is shown. std::vector<COMDLG_FILTERSPEC> comdlg_filterspec(filter.size()); for (size_t i = 0; i < filter.size(); ++i) { comdlg_filterspec[i].pszName = base::as_wcstr(filter[i].description); comdlg_filterspec[i].pszSpec = base::as_wcstr(filter[i].extension_spec); } return SUCCEEDED(file_dialog->SetFileTypes(comdlg_filterspec.size(), comdlg_filterspec.data())) && SUCCEEDED(file_dialog->SetFileTypeIndex(filter_index)); } // Sets the requested |dialog_options|, making sure to keep the default values // when not overwritten. bool SetOptions(IFileDialog* file_dialog, DWORD dialog_options) { // First retrieve the default options for a file dialog. DWORD options; if (FAILED(file_dialog->GetOptions(&options))) return false; options |= dialog_options; return SUCCEEDED(file_dialog->SetOptions(options)); } // Configures a |file_dialog| object given the specified parameters. bool ConfigureDialog(IFileDialog* file_dialog, const std::u16string& title, const std::u16string& ok_button_label, const base::FilePath& default_path, const std::vector<FileFilterSpec>& filter, int filter_index, DWORD dialog_options) { // Set title. if (!title.empty()) { if (FAILED(file_dialog->SetTitle(base::as_wcstr(title)))) return false; } if (!ok_button_label.empty()) { if (FAILED(file_dialog->SetOkButtonLabel(base::as_wcstr(ok_button_label)))) return false; } return SetDefaultPath(file_dialog, default_path) && SetOptions(file_dialog, dialog_options) && SetFilters(file_dialog, filter, filter_index); } // Prompt the user for location to save a file. // Callers should provide the filter string, and also a filter index. // The parameter |index| indicates the initial index of filter description and // filter pattern for the dialog box. If |index| is zero or greater than the // number of total filter types, the system uses the first filter in the // |filter| buffer. |index| is used to specify the initial selected extension, // and when done contains the extension the user chose. The parameter |path| // returns the file name which contains the drive designator, path, file name, // and extension of the user selected file name. |def_ext| is the default // extension to give to the file if the user did not enter an extension. bool RunSaveFileDialog(HWND owner, const std::u16string& title, const base::FilePath& default_path, const std::vector<FileFilterSpec>& filter, DWORD dialog_options, const std::wstring& def_ext, int* filter_index, base::FilePath* path) { Microsoft::WRL::ComPtr<IFileSaveDialog> file_save_dialog; if (FAILED(::CoCreateInstance(CLSID_FileSaveDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&file_save_dialog)))) { return false; } if (!ConfigureDialog(file_save_dialog.Get(), title, std::u16string(), default_path, filter, *filter_index, dialog_options)) { return false; } file_save_dialog->SetDefaultExtension(def_ext.c_str()); // Never consider the current scope as hung. The hang watching deadline (if // any) is not valid since the user can take unbounded time to choose the // file. base::HangWatcher::InvalidateActiveExpectations(); HRESULT hr = file_save_dialog->Show(owner); BaseShellDialogImpl::DisableOwner(owner); if (FAILED(hr)) return false; UINT file_type_index; if (FAILED(file_save_dialog->GetFileTypeIndex(&file_type_index))) return false; *filter_index = static_cast<int>(file_type_index); Microsoft::WRL::ComPtr<IShellItem> result; if (FAILED(file_save_dialog->GetResult(&result))) return false; base::win::ScopedCoMem<wchar_t> display_name; if (FAILED(result->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING, &display_name))) { return false; } *path = base::FilePath(display_name.get()); return true; } // Runs an Open file dialog box, with similar semantics for input parameters as // RunSaveFileDialog. bool RunOpenFileDialog(HWND owner, const std::u16string& title, const std::u16string& ok_button_label, const base::FilePath& default_path, const std::vector<FileFilterSpec>& filter, DWORD dialog_options, int* filter_index, std::vector<base::FilePath>* paths) { Microsoft::WRL::ComPtr<IFileOpenDialog> file_open_dialog; if (FAILED(::CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&file_open_dialog)))) { return false; } // The FOS_FORCEFILESYSTEM option ensures that if the user enters a URL in the // "File name" box, it will be downloaded locally and its new file path will // be returned by the dialog. This was a default option in the deprecated // GetOpenFileName API. dialog_options |= FOS_FORCEFILESYSTEM; if (!ConfigureDialog(file_open_dialog.Get(), title, ok_button_label, default_path, filter, *filter_index, dialog_options)) { return false; } // Never consider the current scope as hung. The hang watching deadline (if // any) is not valid since the user can take unbounded time to choose the // file. base::HangWatcher::InvalidateActiveExpectations(); HRESULT hr = file_open_dialog->Show(owner); BaseShellDialogImpl::DisableOwner(owner); if (FAILED(hr)) return false; UINT file_type_index; if (FAILED(file_open_dialog->GetFileTypeIndex(&file_type_index))) return false; *filter_index = static_cast<int>(file_type_index); Microsoft::WRL::ComPtr<IShellItemArray> selected_items; if (FAILED(file_open_dialog->GetResults(&selected_items))) return false; DWORD result_count; if (FAILED(selected_items->GetCount(&result_count))) return false; DCHECK(result_count == 1 || (dialog_options & FOS_ALLOWMULTISELECT)); std::vector<base::FilePath> result(result_count); for (DWORD i = 0; i < result_count; ++i) { Microsoft::WRL::ComPtr<IShellItem> shell_item; if (FAILED(selected_items->GetItemAt(i, &shell_item))) return false; base::win::ScopedCoMem<wchar_t> display_name; if (FAILED(shell_item->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING, &display_name))) { return false; } result[i] = base::FilePath(display_name.get()); } // Only modify the out parameter if the enumeration didn't fail. *paths = std::move(result); return !paths->empty(); } // Runs a Folder selection dialog box, passes back the selected folder in |path| // and returns true if the user clicks OK. If the user cancels the dialog box // the value in |path| is not modified and returns false. Run on the dialog // thread. bool ExecuteSelectFolder(HWND owner, SelectFileDialog::Type type, const std::u16string& title, const base::FilePath& default_path, std::vector<base::FilePath>* paths) { DCHECK(paths); std::u16string new_title = title; if (new_title.empty() && type == SelectFileDialog::SELECT_UPLOAD_FOLDER) { // If it's for uploading don't use default dialog title to // make sure we clearly tell it's for uploading. new_title = l10n_util::GetStringUTF16(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE); } std::u16string ok_button_label; if (type == SelectFileDialog::SELECT_UPLOAD_FOLDER) { ok_button_label = l10n_util::GetStringUTF16( IDS_SELECT_UPLOAD_FOLDER_DIALOG_UPLOAD_BUTTON); } DWORD dialog_options = FOS_PICKFOLDERS; std::vector<FileFilterSpec> no_filter; int filter_index = 0; return RunOpenFileDialog(owner, new_title, ok_button_label, default_path, no_filter, dialog_options, &filter_index, paths); } bool ExecuteSelectSingleFile(HWND owner, const std::u16string& title, const base::FilePath& default_path, const std::vector<FileFilterSpec>& filter, int* filter_index, std::vector<base::FilePath>* paths) { return RunOpenFileDialog(owner, title, std::u16string(), default_path, filter, 0, filter_index, paths); } bool ExecuteSelectMultipleFile(HWND owner, const std::u16string& title, const base::FilePath& default_path, const std::vector<FileFilterSpec>& filter, int* filter_index, std::vector<base::FilePath>* paths) { DWORD dialog_options = FOS_ALLOWMULTISELECT; return RunOpenFileDialog(owner, title, std::u16string(), default_path, filter, dialog_options, filter_index, paths); } bool ExecuteSaveFile(HWND owner, const std::u16string& title, const base::FilePath& default_path, const std::vector<FileFilterSpec>& filter, const std::wstring& def_ext, int* filter_index, base::FilePath* path) { DCHECK(path); // Having an empty filter for a bad user experience. We should always // specify a filter when saving. DCHECK(!filter.empty()); DWORD dialog_options = FOS_OVERWRITEPROMPT; return RunSaveFileDialog(owner, title, default_path, filter, dialog_options, def_ext, filter_index, path); } } // namespace void ExecuteSelectFile( SelectFileDialog::Type type, const std::u16string& title, const base::FilePath& default_path, const std::vector<FileFilterSpec>& filter, int file_type_index, const std::wstring& default_extension, HWND owner, OnSelectFileExecutedCallback on_select_file_executed_callback) { base::win::AssertComInitialized(); std::vector<base::FilePath> paths; switch (type) { case SelectFileDialog::SELECT_FOLDER: case SelectFileDialog::SELECT_UPLOAD_FOLDER: case SelectFileDialog::SELECT_EXISTING_FOLDER: ExecuteSelectFolder(owner, type, title, default_path, &paths); break; case SelectFileDialog::SELECT_SAVEAS_FILE: { base::FilePath path; if (ExecuteSaveFile(owner, title, default_path, filter, default_extension, &file_type_index, &path)) { paths.push_back(std::move(path)); } break; } case SelectFileDialog::SELECT_OPEN_FILE: ExecuteSelectSingleFile(owner, title, default_path, filter, &file_type_index, &paths); break; case SelectFileDialog::SELECT_OPEN_MULTI_FILE: ExecuteSelectMultipleFile(owner, title, default_path, filter, &file_type_index, &paths); break; case SelectFileDialog::SELECT_NONE: NOTREACHED(); } std::move(on_select_file_executed_callback).Run(paths, file_type_index); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/execute_select_file_win.cc
C++
unknown
14,107
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_EXECUTE_SELECT_FILE_WIN_H_ #define UI_SHELL_DIALOGS_EXECUTE_SELECT_FILE_WIN_H_ #include <string> #include <utility> #include <vector> #include "base/functional/callback_forward.h" #include "base/win/windows_types.h" #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/shell_dialogs_export.h" namespace base { class FilePath; } namespace ui { // Describes a filter for a file dialog. struct FileFilterSpec { // A human readable description of this filter. E.g. "HTML Files." std::u16string description; // The different extensions that map to this spec. This is a semicolon- // separated list of extensions that contains a wildcard and the separator. // E.g. "*.html;*.htm" std::u16string extension_spec; }; using OnSelectFileExecutedCallback = base::OnceCallback<void(const std::vector<base::FilePath>&, int)>; // Shows the file selection dialog modal to |owner| returns the selected file(s) // and file type index using the |on_select_file_executed_callback|. The file // path vector will be empty on failure. SHELL_DIALOGS_EXPORT void ExecuteSelectFile( SelectFileDialog::Type type, const std::u16string& title, const base::FilePath& default_path, const std::vector<FileFilterSpec>& filter, int file_type_index, const std::wstring& default_extension, HWND owner, OnSelectFileExecutedCallback on_select_file_executed_callback); } // namespace ui #endif // UI_SHELL_DIALOGS_EXECUTE_SELECT_FILE_WIN_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/execute_select_file_win.h
C++
unknown
1,653
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/fake_select_file_dialog.h" #include "ui/shell_dialogs/select_file_policy.h" #include "url/gurl.h" namespace ui { FakeSelectFileDialog::Factory::Factory() = default; FakeSelectFileDialog::Factory::~Factory() = default; ui::SelectFileDialog* FakeSelectFileDialog::Factory::Create( ui::SelectFileDialog::Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) { FakeSelectFileDialog* dialog = new FakeSelectFileDialog(opened_callback_, listener, std::move(policy)); last_dialog_ = dialog->GetWeakPtr(); return dialog; } FakeSelectFileDialog* FakeSelectFileDialog::Factory::GetLastDialog() const { return last_dialog_.get(); } void FakeSelectFileDialog::Factory::SetOpenCallback( base::RepeatingClosure callback) { opened_callback_ = callback; } // static FakeSelectFileDialog::Factory* FakeSelectFileDialog::RegisterFactory() { Factory* factory = new Factory; ui::SelectFileDialog::SetFactory(factory); return factory; } FakeSelectFileDialog::FakeSelectFileDialog( const base::RepeatingClosure& opened, Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) : ui::SelectFileDialog(listener, std::move(policy)), opened_(opened) {} FakeSelectFileDialog::~FakeSelectFileDialog() = default; bool FakeSelectFileDialog::HasMultipleFileTypeChoicesImpl() { return true; } bool FakeSelectFileDialog::IsRunning(gfx::NativeWindow owning_window) const { return true; } void FakeSelectFileDialog::SelectFileImpl( Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) { title_ = title; params_ = params; if (file_types) file_types_ = *file_types; default_extension_ = base::FilePath(default_extension).MaybeAsASCII(); caller_ = caller; opened_.Run(); } bool FakeSelectFileDialog::CallFileSelected(const base::FilePath& file_path, base::StringPiece filter_text) { for (size_t index = 0; index < file_types_.extensions.size(); ++index) { for (const base::FilePath::StringType& ext : file_types_.extensions[index]) { if (base::FilePath(ext).MaybeAsASCII() == filter_text) { // FileSelected accepts a 1-based index. listener_->FileSelected(file_path, index + 1, params_); return true; } } } return false; } void FakeSelectFileDialog::CallMultiFilesSelected( const std::vector<base::FilePath>& files) { listener_->MultiFilesSelected(files, params_); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/fake_select_file_dialog.cc
C++
unknown
2,866
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_FAKE_SELECT_FILE_DIALOG_H_ #define UI_SHELL_DIALOGS_FAKE_SELECT_FILE_DIALOG_H_ #include <string> #include "base/functional/callback.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/strings/string_piece.h" #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/select_file_dialog_factory.h" #include "ui/shell_dialogs/shell_dialogs_export.h" namespace ui { // A test fake SelectFileDialog. Usage: // // FakeSelectFileDialog::Factory* factory = // FakeSelectFileDialog::RegisterFactory(); // factory->SetOpenCallback(open_callback); // // Now calls to SelectFileDialog::Create() will create a |FakeSelectFileDialog|, // and open_callback is invoked when the dialog is opened. // // Once the dialog is opened, use factory->GetLastDialog() to access the dialog // to query file information and select a file. class FakeSelectFileDialog : public SelectFileDialog { public: // A |FakeSelectFileDialog::Factory| which creates |FakeSelectFileDialog| // instances. class Factory : public SelectFileDialogFactory { public: Factory(); ~Factory() override; Factory(const Factory&) = delete; Factory& operator=(const Factory&) = delete; // SelectFileDialog::Factory. ui::SelectFileDialog* Create( ui::SelectFileDialog::Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) override; // Returns the last opened dialog, or null if one has not been opened yet. FakeSelectFileDialog* GetLastDialog() const; // Sets a callback to be called when a new fake dialog has been opened. void SetOpenCallback(base::RepeatingClosure callback); private: base::RepeatingClosure opened_callback_; base::WeakPtr<FakeSelectFileDialog> last_dialog_; }; // Creates a |Factory| and registers it with |SelectFileDialog::SetFactory|, // which owns the new factory. This factory will create new // |FakeSelectFileDialog| instances upon calls to // |SelectFileDialog::Create()|. static Factory* RegisterFactory(); FakeSelectFileDialog(const base::RepeatingClosure& opened, Listener* listener, std::unique_ptr<SelectFilePolicy> policy); FakeSelectFileDialog(const FakeSelectFileDialog&) = delete; FakeSelectFileDialog& operator=(const FakeSelectFileDialog&) = delete; // SelectFileDialog. void SelectFileImpl(Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) override; bool HasMultipleFileTypeChoicesImpl() override; bool IsRunning(gfx::NativeWindow owning_window) const override; void ListenerDestroyed() override {} // Returns the file title provided to the dialog. const std::u16string& title() const { return title_; } // Returns the file types provided to the dialog. const FileTypeInfo& file_types() const { return file_types_; } // Returns the default file extension provided to the dialog. const std::string& default_extension() const { return default_extension_; } // Returns the caller URL provided to the dialog. const GURL* caller() const { return caller_; } // Calls the |FileSelected()| method on listener(). |filter_text| selects // which file extension filter to report. [[nodiscard]] bool CallFileSelected(const base::FilePath& file_path, base::StringPiece filter_text); // Calls the |MultiFilesSelected()| method on listener(). void CallMultiFilesSelected(const std::vector<base::FilePath>& file_path); base::WeakPtr<FakeSelectFileDialog> GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } private: ~FakeSelectFileDialog() override; base::RepeatingClosure opened_; std::u16string title_; FileTypeInfo file_types_; std::string default_extension_; raw_ptr<void> params_; raw_ptr<const GURL> caller_; base::WeakPtrFactory<FakeSelectFileDialog> weak_ptr_factory_{this}; }; } // namespace ui #endif // UI_SHELL_DIALOGS_FAKE_SELECT_FILE_DIALOG_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/fake_select_file_dialog.h
C++
unknown
4,500
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/functional/bind.h" #include "base/path_service.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" #include "build/build_config.h" #include "mojo/core/embedder/embedder.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #if BUILDFLAG(IS_MAC) #include "base/test/mock_chrome_application_mac.h" #endif namespace { class ShellDialogsTestSuite : public base::TestSuite { public: ShellDialogsTestSuite(int argc, char** argv); ShellDialogsTestSuite(const ShellDialogsTestSuite&) = delete; ShellDialogsTestSuite& operator=(const ShellDialogsTestSuite&) = delete; protected: // base::TestSuite: void Initialize() override; void Shutdown() override; }; ShellDialogsTestSuite::ShellDialogsTestSuite(int argc, char** argv) : base::TestSuite(argc, argv) {} void ShellDialogsTestSuite::Initialize() { base::TestSuite::Initialize(); #if BUILDFLAG(IS_MAC) mock_cr_app::RegisterMockCrApp(); #endif // Setup resource bundle. ui::RegisterPathProvider(); base::FilePath ui_test_pak_path; base::PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path); ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); } void ShellDialogsTestSuite::Shutdown() { ui::ResourceBundle::CleanupSharedInstance(); base::TestSuite::Shutdown(); } } // namespace int main(int argc, char** argv) { ShellDialogsTestSuite test_suite(argc, argv); mojo::core::Init(); return base::LaunchUnitTests(argc, argv, base::BindOnce(&ShellDialogsTestSuite::Run, base::Unretained(&test_suite))); }
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/run_all_unittests.cc
C++
unknown
1,816
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/select_file_dialog.h" #include <stddef.h> #include <algorithm> #include "base/check.h" #include "base/functional/bind.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/sequence_checker.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversion_utils.h" #include "base/task/single_thread_task_runner.h" #include "base/third_party/icu/icu_utf.h" #include "build/build_config.h" #include "ui/shell_dialogs/select_file_dialog_factory.h" #include "ui/shell_dialogs/select_file_policy.h" #include "ui/shell_dialogs/selected_file_info.h" #include "url/gurl.h" namespace { // Optional dialog factory. Leaked. ui::SelectFileDialogFactory* dialog_factory_ = nullptr; void TruncateStringToSize(base::FilePath::StringType* string, size_t size) { if (string->size() <= size) return; #if BUILDFLAG(IS_WIN) const auto* c_str = base::as_u16cstr(string->c_str()); for (size_t i = 0; i < string->size(); ++i) { base_icu::UChar32 codepoint; size_t original_i = i; if (!base::ReadUnicodeCharacter(c_str, size, &i, &codepoint) || i >= size) { string->resize(original_i); return; } } #else base::TruncateUTF8ToByteSize(*string, size, string); #endif } } // namespace namespace ui { SelectFileDialog::FileTypeInfo::FileTypeInfo() = default; SelectFileDialog::FileTypeInfo::FileTypeInfo(const FileTypeInfo& other) = default; SelectFileDialog::FileTypeInfo::~FileTypeInfo() = default; void SelectFileDialog::Listener::FileSelectedWithExtraInfo( const ui::SelectedFileInfo& file, int index, void* params) { // Most of the dialogs need actual local path, so default to it. // If local path is empty, use file_path instead. FileSelected(file.local_path.empty() ? file.file_path : file.local_path, index, params); } void SelectFileDialog::Listener::MultiFilesSelectedWithExtraInfo( const std::vector<ui::SelectedFileInfo>& files, void* params) { std::vector<base::FilePath> file_paths; for (const ui::SelectedFileInfo& file : files) { file_paths.push_back(file.local_path.empty() ? file.file_path : file.local_path); } MultiFilesSelected(file_paths, params); } // static void SelectFileDialog::SetFactory(ui::SelectFileDialogFactory* factory) { delete dialog_factory_; dialog_factory_ = factory; } // static scoped_refptr<SelectFileDialog> SelectFileDialog::Create( Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy, bool run_from_cef) { // Avoid reentrancy of the CEF factory. if (dialog_factory_ && (!run_from_cef || !dialog_factory_->IsCefFactory())) return dialog_factory_->Create(listener, std::move(policy)); return CreateSelectFileDialog(listener, std::move(policy)); } base::FilePath SelectFileDialog::GetShortenedFilePath( const base::FilePath& path) { const size_t kMaxNameLength = 255; if (path.BaseName().value().length() <= kMaxNameLength) return path; base::FilePath filename = path.BaseName(); base::FilePath::StringType extension = filename.FinalExtension(); filename = filename.RemoveFinalExtension(); base::FilePath::StringType file_string = filename.value(); // 1 for . plus 12 for longest known extension. size_t max_extension_length = 13; if (file_string.length() < kMaxNameLength) { max_extension_length = std::max(max_extension_length, kMaxNameLength - file_string.length()); } // Take the first max_extension_length characters (this will be the // leading '.' plus the next max_extension_length - 1). TruncateStringToSize(&extension, max_extension_length); TruncateStringToSize(&file_string, kMaxNameLength - extension.length()); return path.DirName().Append(file_string).AddExtension(extension); } void SelectFileDialog::SelectFile( Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) { DCHECK(listener_); if (select_file_policy_.get() && !select_file_policy_->CanOpenSelectFileDialog()) { select_file_policy_->SelectFileDenied(); // Inform the listener that no file was selected. // Post a task rather than calling FileSelectionCanceled directly to ensure // that the listener is called asynchronously. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(&SelectFileDialog::CancelFileSelection, this, params)); return; } base::FilePath path = GetShortenedFilePath(default_path); // Call the platform specific implementation of the file selection dialog. SelectFileImpl(type, title, path, file_types, file_type_index, default_extension, owning_window, params, caller); } bool SelectFileDialog::HasMultipleFileTypeChoices() { return HasMultipleFileTypeChoicesImpl(); } SelectFileDialog::SelectFileDialog(Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) : listener_(listener), select_file_policy_(std::move(policy)) { DCHECK(listener_); } SelectFileDialog::~SelectFileDialog() {} void SelectFileDialog::CancelFileSelection(void* params) { if (listener_) listener_->FileSelectionCanceled(params); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog.cc
C++
unknown
5,613
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_H_ #include <memory> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/memory/raw_ptr.h" #include "base/memory/ref_counted.h" #include "ui/gfx/native_widget_types.h" #include "ui/shell_dialogs/base_shell_dialog.h" #include "ui/shell_dialogs/shell_dialogs_export.h" class GURL; namespace ui { class SelectFileDialogFactory; class SelectFilePolicy; struct SelectedFileInfo; // Shows a dialog box for selecting a file or a folder. class SHELL_DIALOGS_EXPORT SelectFileDialog : public base::RefCountedThreadSafe<SelectFileDialog>, public BaseShellDialog { public: enum Type { SELECT_NONE, // For opening a folder. SELECT_FOLDER, // Like SELECT_FOLDER, but the dialog UI should explicitly show it's // specifically for "upload". SELECT_UPLOAD_FOLDER, // Like SELECT_FOLDER, but folder creation is disabled, if possible. SELECT_EXISTING_FOLDER, // For saving into a file, allowing a nonexistent file to be selected. SELECT_SAVEAS_FILE, // For opening a file. SELECT_OPEN_FILE, // Like SELECT_OPEN_FILE, but allowing multiple files to open. SELECT_OPEN_MULTI_FILE }; // An interface implemented by a Listener object wishing to know about the // the result of the Select File/Folder action. These callbacks must be // re-entrant. class SHELL_DIALOGS_EXPORT Listener { public: // Notifies the Listener that a file/folder selection has been made. The // file/folder path is in |path|. |params| is contextual passed to // SelectFile. |index| specifies the index of the filter passed to the // the initial call to SelectFile. virtual void FileSelected(const base::FilePath& path, int index, void* params) = 0; // Similar to FileSelected() but takes SelectedFileInfo instead of // base::FilePath. Used for passing extra information (ex. display name). // // If not overridden, calls FileSelected() with path from |file|. virtual void FileSelectedWithExtraInfo(const SelectedFileInfo& file, int index, void* params); // Notifies the Listener that many files have been selected. The // files are in |files|. |params| is contextual passed to SelectFile. virtual void MultiFilesSelected(const std::vector<base::FilePath>& files, void* params) {} // Similar to MultiFilesSelected() but takes SelectedFileInfo instead of // base::FilePath. Used for passing extra information (ex. display name). // // If not overridden, calls MultiFilesSelected() with paths from |files|. virtual void MultiFilesSelectedWithExtraInfo( const std::vector<SelectedFileInfo>& files, void* params); // Notifies the Listener that the file/folder selection was aborted (via // the user canceling or closing the selection dialog box, for example). // |params| is contextual passed to SelectFile. virtual void FileSelectionCanceled(void* params) {} protected: virtual ~Listener() = default; }; // Sets the factory that creates SelectFileDialog objects, overriding default // behaviour. // // This is optional and should only be used by components that have to live // elsewhere in the tree due to layering violations. (For example, because of // a dependency on chrome's extension system.) static void SetFactory(SelectFileDialogFactory* factory); // Creates a dialog box helper. This is an inexpensive wrapper around the // platform-native file selection dialog. |policy| is an optional class that // can prevent showing a dialog. // // The lifetime of the Listener is not managed by this class. The calling // code should call always ListenerDestroyed() (on the base class // BaseShellDialog) when the listener is destroyed since the SelectFileDialog // is refcounted and uses a background thread. static scoped_refptr<SelectFileDialog> Create( Listener* listener, std::unique_ptr<SelectFilePolicy> policy, bool run_from_cef = false); SelectFileDialog(const SelectFileDialog&) = delete; SelectFileDialog& operator=(const SelectFileDialog&) = delete; // Holds information about allowed extensions on a file save dialog. struct SHELL_DIALOGS_EXPORT FileTypeInfo { FileTypeInfo(); FileTypeInfo(const FileTypeInfo& other); ~FileTypeInfo(); // A list of allowed extensions. For example, it might be // // { { "htm", "html" }, { "txt" } } // // Only pass more than one extension in the inner vector if the extensions // are equivalent. Do NOT include leading periods. std::vector<std::vector<base::FilePath::StringType>> extensions; // Overrides the system descriptions of the specified extensions. Entries // correspond to |extensions|; if left blank the system descriptions will // be used. std::vector<std::u16string> extension_description_overrides; // Specifies whether there will be a filter added for all files (i.e. *.*). bool include_all_files = false; // Some implementations by default hide the extension of a file, in // particular in a save file dialog. If this is set to true, where // supported, the save file dialog will instead keep the file extension // visible. bool keep_extension_visible = false; // Specifies which type of paths the caller can handle. enum AllowedPaths { // Any type of path, whether on a local/native volume or a remote/virtual // volume. Excludes files that can only be opened by URL; for those use // ANY_PATH_OR_URL below. ANY_PATH, // Set when the caller cannot handle virtual volumes (e.g. File System // Provider [FSP] volumes like "File System for Dropbox"). When opening // files, the dialog will create a native replica of the file and return // its path. When saving files, the dialog will hide virtual volumes. NATIVE_PATH, // Set when the caller can open files via URL. For example, when opening a // .gdoc file from Google Drive the file is opened by navigating to a // docs.google.com URL. ANY_PATH_OR_URL }; AllowedPaths allowed_paths = NATIVE_PATH; }; // Returns a file path with a base name at most 255 characters long. This // is the limit on Windows and Linux, and on Windows the system file // selection dialog will fail to open if the file name exceeds 255 characters. static base::FilePath GetShortenedFilePath(const base::FilePath& path); // Selects a File. // Before doing anything this function checks if FileBrowsing is forbidden // by Policy. If so, it tries to show an InfoBar and behaves as though no File // was selected (the user clicked `Cancel` immediately). // Otherwise it will start displaying the dialog box. This will also // block the calling window until the dialog box is complete. The listener // associated with this object will be notified when the selection is // complete. // |type| is the type of file dialog to be shown, see Type enumeration above. // |title| is the title to be displayed in the dialog. If this string is // empty, the default title is used. // |default_path| is the default path and suggested file name to be shown in // the dialog. This only works for SELECT_SAVEAS_FILE and SELECT_OPEN_FILE. // Can be an empty string to indicate the platform default. // |file_types| holds the information about the file types allowed. Pass NULL // to get no special behavior // |file_type_index| is the 1-based index into the file type list in // |file_types|. Specify 0 if you don't need to specify extension behavior. // |default_extension| is the default extension to add to the file if the // user doesn't type one. This should NOT include the '.'. On Windows, if // you specify this you must also specify |file_types|. // |owning_window| is the window the dialog is modal to, or NULL for a // modeless dialog. // |params| is data from the calling context which will be passed through to // the listener. Can be NULL. // |caller| is the URL of the dialog caller which can be used to check further // Policy restrictions, when applicable. Can be NULL. // NOTE: only one instance of any shell dialog can be shown per owning_window // at a time (for obvious reasons). void SelectFile(Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller = nullptr); bool HasMultipleFileTypeChoices(); // Match the types used by CefWindowHandle. #if BUILDFLAG(IS_MAC) using WidgetType = void*; static constexpr WidgetType kNullWidget = nullptr; #else using WidgetType = gfx::AcceleratedWidget; static constexpr WidgetType kNullWidget = gfx::kNullAcceleratedWidget; #endif void set_owning_widget(WidgetType widget) { owning_widget_ = widget; } protected: friend class base::RefCountedThreadSafe<SelectFileDialog>; explicit SelectFileDialog(Listener* listener, std::unique_ptr<SelectFilePolicy> policy); ~SelectFileDialog() override; // Displays the actual file-selection dialog. // This is overridden in the platform-specific descendants of FileSelectDialog // and gets called from SelectFile after testing the // AllowFileSelectionDialogs-Policy. virtual void SelectFileImpl( Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) = 0; // The listener to be notified of selection completion. raw_ptr<Listener, DanglingUntriaged> listener_; std::unique_ptr<SelectFilePolicy> select_file_policy_; // Support override of the |owning_window| value. WidgetType owning_widget_ = kNullWidget; private: // Tests if the file selection dialog can be displayed by // testing if the AllowFileSelectionDialogs-Policy is // either unset or set to true. bool CanOpenSelectFileDialog(); // Informs the |listener_| that the file selection dialog was canceled. Moved // to a function for being able to post it to the message loop. void CancelFileSelection(void* params); // Returns true if the dialog has multiple file type choices. virtual bool HasMultipleFileTypeChoicesImpl() = 0; }; SelectFileDialog* CreateSelectFileDialog( SelectFileDialog::Listener* listener, std::unique_ptr<SelectFilePolicy> policy); } // namespace ui #endif // UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog.h
C++
unknown
11,294
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "select_file_dialog_android.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/check.h" #include "base/notreached.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "ui/android/window_android.h" #include "ui/base/ui_base_jni_headers/SelectFileDialog_jni.h" #include "ui/shell_dialogs/select_file_policy.h" #include "ui/shell_dialogs/selected_file_info.h" #include "url/gurl.h" using base::android::ConvertJavaStringToUTF8; using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; namespace ui { // static SelectFileDialogImpl* SelectFileDialogImpl::Create( Listener* listener, std::unique_ptr<SelectFilePolicy> policy) { return new SelectFileDialogImpl(listener, std::move(policy)); } void SelectFileDialogImpl::OnFileSelected( JNIEnv* env, const JavaParamRef<jobject>& java_object, const JavaParamRef<jstring>& filepath, const JavaParamRef<jstring>& display_name) { if (!listener_) return; std::string path = ConvertJavaStringToUTF8(env, filepath); std::string file_name = ConvertJavaStringToUTF8(env, display_name); base::FilePath file_path = base::FilePath(path); ui::SelectedFileInfo file_info; file_info.file_path = file_path; file_info.local_path = file_path; if (!file_name.empty()) file_info.display_name = file_name; listener_->FileSelectedWithExtraInfo(file_info, 0, nullptr); } void SelectFileDialogImpl::OnMultipleFilesSelected( JNIEnv* env, const JavaParamRef<jobject>& java_object, const JavaParamRef<jobjectArray>& filepaths, const JavaParamRef<jobjectArray>& display_names) { if (!listener_) return; std::vector<ui::SelectedFileInfo> selected_files; jsize length = env->GetArrayLength(filepaths); DCHECK(length == env->GetArrayLength(display_names)); for (int i = 0; i < length; ++i) { ScopedJavaLocalRef<jstring> path_ref( env, static_cast<jstring>(env->GetObjectArrayElement(filepaths, i))); base::FilePath file_path = base::FilePath(ConvertJavaStringToUTF8(env, path_ref)); ScopedJavaLocalRef<jstring> display_name_ref( env, static_cast<jstring>(env->GetObjectArrayElement(display_names, i))); std::string display_name = ConvertJavaStringToUTF8(env, display_name_ref.obj()); ui::SelectedFileInfo file_info; file_info.file_path = file_path; file_info.local_path = file_path; file_info.display_name = display_name; selected_files.push_back(file_info); } listener_->MultiFilesSelectedWithExtraInfo(selected_files, nullptr); } void SelectFileDialogImpl::OnFileNotSelected( JNIEnv* env, const JavaParamRef<jobject>& java_object) { if (listener_) listener_->FileSelectionCanceled(nullptr); } void SelectFileDialogImpl::OnContactsSelected( JNIEnv* env, const JavaParamRef<jobject>& java_object, const JavaParamRef<jstring>& java_contacts) { std::string data = ConvertJavaStringToUTF8(env, java_contacts.obj()); listener_->FileSelectedWithExtraInfo(ui::SelectedFileInfo(), 0, (void*)data.c_str()); } bool SelectFileDialogImpl::IsRunning(gfx::NativeWindow) const { return listener_; } void SelectFileDialogImpl::ListenerDestroyed() { listener_ = nullptr; } void SelectFileDialogImpl::SelectFileImpl( SelectFileDialog::Type type, const std::u16string& title, const base::FilePath& default_path, const SelectFileDialog::FileTypeInfo* file_types, int file_type_index, const std::string& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) { JNIEnv* env = base::android::AttachCurrentThread(); // The first element in the pair is a list of accepted types, the second // indicates whether the device's capture capabilities should be used. typedef std::pair<std::vector<std::u16string>, bool> AcceptTypes; AcceptTypes accept_types = std::make_pair(std::vector<std::u16string>(), false); if (params) accept_types = *(reinterpret_cast<AcceptTypes*>(params)); ScopedJavaLocalRef<jobjectArray> accept_types_java = base::android::ToJavaArrayOfStrings(env, accept_types.first); bool accept_multiple_files = SelectFileDialog::SELECT_OPEN_MULTI_FILE == type; Java_SelectFileDialog_selectFile(env, java_object_, accept_types_java, accept_types.second, accept_multiple_files, owning_window->GetJavaObject()); } SelectFileDialogImpl::~SelectFileDialogImpl() { } SelectFileDialogImpl::SelectFileDialogImpl( Listener* listener, std::unique_ptr<SelectFilePolicy> policy) : SelectFileDialog(listener, std::move(policy)) { JNIEnv* env = base::android::AttachCurrentThread(); // TODO(crbug.com/1365766): The `intptr_t` to `this` might get stale. java_object_.Reset( Java_SelectFileDialog_create(env, reinterpret_cast<intptr_t>(this))); } bool SelectFileDialogImpl::HasMultipleFileTypeChoicesImpl() { NOTIMPLEMENTED(); return false; } SelectFileDialog* CreateSelectFileDialog( SelectFileDialog::Listener* listener, std::unique_ptr<SelectFilePolicy> policy) { return SelectFileDialogImpl::Create(listener, std::move(policy)); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_android.cc
C++
unknown
5,587
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_ANDROID_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_ANDROID_H_ #include <jni.h> #include "base/android/scoped_java_ref.h" #include "base/files/file_path.h" #include "ui/shell_dialogs/select_file_dialog.h" namespace ui { class SelectFileDialogImpl : public SelectFileDialog { public: static SelectFileDialogImpl* Create(Listener* listener, std::unique_ptr<SelectFilePolicy> policy); SelectFileDialogImpl(const SelectFileDialogImpl&) = delete; SelectFileDialogImpl& operator=(const SelectFileDialogImpl&) = delete; void OnFileSelected(JNIEnv* env, const base::android::JavaParamRef<jobject>& java_object, const base::android::JavaParamRef<jstring>& filepath, const base::android::JavaParamRef<jstring>& display_name); void OnMultipleFilesSelected( JNIEnv* env, const base::android::JavaParamRef<jobject>& java_object, const base::android::JavaParamRef<jobjectArray>& filepaths, const base::android::JavaParamRef<jobjectArray>& display_names); void OnFileNotSelected( JNIEnv* env, const base::android::JavaParamRef<jobject>& java_object); void OnContactsSelected( JNIEnv* env, const base::android::JavaParamRef<jobject>& java_object, const base::android::JavaParamRef<jstring>& contacts); // From SelectFileDialog bool IsRunning(gfx::NativeWindow) const override; void ListenerDestroyed() override; // Called when it is time to display the file picker. // params is expected to be a vector<string16> with accept_types first and // the capture value as the last element of the vector. void SelectFileImpl(SelectFileDialog::Type type, const std::u16string& title, const base::FilePath& default_path, const SelectFileDialog::FileTypeInfo* file_types, int file_type_index, const std::string& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) override; protected: ~SelectFileDialogImpl() override; private: SelectFileDialogImpl(Listener* listener, std::unique_ptr<SelectFilePolicy> policy); bool HasMultipleFileTypeChoicesImpl() override; base::android::ScopedJavaGlobalRef<jobject> java_object_; }; } // namespace ui #endif // UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_ANDROID_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_android.h
C++
unknown
2,709
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/select_file_dialog_factory.h" namespace ui { SelectFileDialogFactory::~SelectFileDialogFactory() {} } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_factory.cc
C++
unknown
293
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_FACTORY_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_FACTORY_H_ #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/shell_dialogs_export.h" namespace ui { class SelectFilePolicy; // Some chrome components want to create their own SelectFileDialog objects // (for example, using an extension to provide the select file dialog needs to // live in chrome/ due to the extension dependency.) // // They can implement a factory which creates their SelectFileDialog. class SHELL_DIALOGS_EXPORT SelectFileDialogFactory { public: virtual ~SelectFileDialogFactory(); virtual SelectFileDialog* Create( ui::SelectFileDialog::Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) = 0; virtual bool IsCefFactory() const { return false; } }; } // namespace ui #endif // UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_FACTORY_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_factory.h
C++
unknown
1,057
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/select_file_dialog.h" #include "base/notreached.h" #include "ui/shell_dialogs/select_file_policy.h" namespace ui { SelectFileDialog* CreateSelectFileDialog( SelectFileDialog::Listener* listener, std::unique_ptr<SelectFilePolicy> policy) { NOTREACHED(); return nullptr; } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_fuchsia.cc
C++
unknown
477
// 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. #ifndef UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_IOS_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_IOS_H_ #include <memory> #include "base/files/file_path.h" #include "base/functional/callback_forward.h" #include "base/mac/scoped_nsobject.h" #include "base/memory/weak_ptr.h" #include "ui/gfx/native_widget_types.h" #include "ui/shell_dialogs/select_file_dialog.h" @class NativeFileDialog; namespace ui { // Implementation of SelectFileDialog that shows iOS dialogs for choosing a // file or folder. class SelectFileDialogImpl : public SelectFileDialog { public: SelectFileDialogImpl(Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy); SelectFileDialogImpl(const SelectFileDialogImpl&) = delete; SelectFileDialogImpl& operator=(const SelectFileDialogImpl&) = delete; // BaseShellDialog: bool IsRunning(gfx::NativeWindow parent_window) const override; void ListenerDestroyed() override; void FileWasSelected(void* params, bool is_multi, bool was_cancelled, const std::vector<base::FilePath>& files, int index); protected: // SelectFileDialog: void SelectFileImpl(Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) override; bool HasMultipleFileTypeChoicesImpl() override; private: ~SelectFileDialogImpl() override; bool has_multiple_file_type_choices_ = false; base::scoped_nsobject<NativeFileDialog> native_file_dialog_; base::WeakPtrFactory<SelectFileDialogImpl> weak_factory_{this}; }; } // namespace ui #endif // UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_IOS_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_ios.h
Objective-C
unknown
2,149
// 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 "ui/shell_dialogs/select_file_dialog_ios.h" #import <UIKit/UIDocumentPickerViewController.h> #import <UIKit/UIKit.h> #import <UniformTypeIdentifiers/UniformTypeIdentifiers.h> #include "base/mac/foundation_util.h" #include "base/memory/weak_ptr.h" #include "base/notreached.h" #include "base/ranges/algorithm.h" #include "base/strings/sys_string_conversions.h" #include "ui/shell_dialogs/select_file_policy.h" @interface NativeFileDialog : NSObject <UIDocumentPickerDelegate> { @private base::WeakPtr<ui::SelectFileDialogImpl> _dialog; UIViewController* _viewController; bool _allowMultipleFiles; void* _params; base::scoped_nsobject<UIDocumentPickerViewController> _documentPickerController; base::scoped_nsobject<NSArray<UTType*>> _fileUTTypeLists; bool _allowsOtherFileTypes; } - (instancetype)initWithDialog:(base::WeakPtr<ui::SelectFileDialogImpl>)dialog viewController:(UIViewController*)viewController allowMultipleFiles:(bool)allowMultipleFiles params:(void*)params fileUTTypeLists:(NSArray<UTType*>*)fileUTTypeLists allowsOtherFileTypes:(bool)allowsOtherFileTypes; - (void)dealloc; - (void)showFilePickerMenu; - (void)documentPicker:(UIDocumentPickerViewController*)controller didPickDocumentsAtURLs:(NSArray<NSURL*>*)urls; - (void)documentPickerWasCancelled:(UIDocumentPickerViewController*)controller; @end @implementation NativeFileDialog - (instancetype)initWithDialog:(base::WeakPtr<ui::SelectFileDialogImpl>)dialog viewController:(UIViewController*)viewController allowMultipleFiles:(bool)allowMultipleFiles params:(void*)params fileUTTypeLists:(NSArray<UTType*>*)fileUTTypeLists allowsOtherFileTypes:(bool)allowsOtherFileTypes { if (!(self = [super init])) { return nil; } _dialog = dialog; _viewController = viewController; _allowMultipleFiles = allowMultipleFiles; _params = params; _fileUTTypeLists.reset([fileUTTypeLists retain]); _allowsOtherFileTypes = allowsOtherFileTypes; return self; } - (void)dealloc { [_documentPickerController setDelegate:nil]; [super dealloc]; } - (void)showFilePickerMenu { NSArray* documentTypes = _allowsOtherFileTypes ? @[ UTTypeItem ] : _fileUTTypeLists; _documentPickerController.reset([[UIDocumentPickerViewController alloc] initForOpeningContentTypes:documentTypes]); [_documentPickerController setAllowsMultipleSelection:_allowMultipleFiles]; [_documentPickerController setDelegate:self]; UIViewController* currentViewController = _viewController; [currentViewController presentViewController:_documentPickerController animated:true completion:nil]; } - (void)documentPicker:(UIDocumentPickerViewController*)controller didPickDocumentsAtURLs:(NSArray<NSURL*>*)urls { if (!_dialog) { return; } std::vector<base::FilePath> paths; for (NSURL* url : urls) { if (!url.isFileURL) { continue; } NSString* path = url.path; paths.push_back(base::mac::NSStringToFilePath(path)); } _dialog->FileWasSelected(_params, _allowMultipleFiles, false, paths, 0); } - (void)documentPickerWasCancelled:(UIDocumentPickerViewController*)controller { if (!_dialog) { return; } std::vector<base::FilePath> paths; _dialog->FileWasSelected(_params, _allowMultipleFiles, true, paths, 0); } @end namespace ui { SelectFileDialogImpl::SelectFileDialogImpl( Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) : SelectFileDialog(listener, std::move(policy)) {} bool SelectFileDialogImpl::IsRunning(gfx::NativeWindow parent_window) const { return listener_; } void SelectFileDialogImpl::ListenerDestroyed() { listener_ = nullptr; } void SelectFileDialogImpl::FileWasSelected( void* params, bool is_multi, bool was_cancelled, const std::vector<base::FilePath>& files, int index) { if (!listener_) { return; } if (was_cancelled || files.empty()) { listener_->FileSelectionCanceled(params); } else { if (is_multi) { listener_->MultiFilesSelected(files, params); } else { listener_->FileSelected(files[0], index, params); } } } void SelectFileDialogImpl::SelectFileImpl( SelectFileDialog::Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow gfx_window, void* params, const GURL* caller) { has_multiple_file_type_choices_ = SelectFileDialog::SELECT_OPEN_MULTI_FILE == type; bool allows_other_file_types = false; NSMutableArray /*<UTType*>*/* file_uttype_lists = [NSMutableArray array]; for (size_t i = 0; i < file_types->extensions.size(); ++i) { const std::vector<base::FilePath::StringType>& ext_list = file_types->extensions[i]; for (const base::FilePath::StringType& ext : ext_list) { UTType* uttype = [UTType typeWithFilenameExtension:base::SysUTF8ToNSString(ext)]; if (!uttype) { continue; } if (![file_uttype_lists containsObject:uttype]) { [file_uttype_lists addObject:uttype]; } } } if (file_types->include_all_files || file_types->extensions.empty()) { allows_other_file_types = true; } UIViewController* controller = gfx_window.rootViewController; native_file_dialog_.reset([[NativeFileDialog alloc] initWithDialog:weak_factory_.GetWeakPtr() viewController:controller allowMultipleFiles:has_multiple_file_type_choices_ params:params fileUTTypeLists:file_uttype_lists allowsOtherFileTypes:allows_other_file_types]); [native_file_dialog_ showFilePickerMenu]; } SelectFileDialogImpl::~SelectFileDialogImpl() { // Clear |weak_factory_| beforehand, to ensure that no callbacks will be made // when we cancel the NSSavePanels. weak_factory_.InvalidateWeakPtrs(); } bool SelectFileDialogImpl::HasMultipleFileTypeChoicesImpl() { return has_multiple_file_type_choices_; } SelectFileDialog* CreateSelectFileDialog( SelectFileDialog::Listener* listener, std::unique_ptr<SelectFilePolicy> policy) { return new SelectFileDialogImpl(listener, std::move(policy)); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_ios.mm
Objective-C++
unknown
6,603
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/select_file_dialog_lacros.h" #include <utility> #include "base/functional/bind.h" #include "base/notreached.h" #include "chromeos/crosapi/mojom/select_file.mojom-shared.h" #include "chromeos/crosapi/mojom/select_file.mojom.h" #include "chromeos/lacros/lacros_service.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/select_file_policy.h" #include "ui/shell_dialogs/selected_file_info.h" #include "url/gurl.h" namespace ui { namespace { crosapi::mojom::SelectFileDialogType GetMojoType(SelectFileDialog::Type type) { switch (type) { case SelectFileDialog::Type::SELECT_FOLDER: return crosapi::mojom::SelectFileDialogType::kFolder; case SelectFileDialog::Type::SELECT_UPLOAD_FOLDER: return crosapi::mojom::SelectFileDialogType::kUploadFolder; case SelectFileDialog::Type::SELECT_EXISTING_FOLDER: return crosapi::mojom::SelectFileDialogType::kExistingFolder; case SelectFileDialog::Type::SELECT_OPEN_FILE: return crosapi::mojom::SelectFileDialogType::kOpenFile; case SelectFileDialog::Type::SELECT_OPEN_MULTI_FILE: return crosapi::mojom::SelectFileDialogType::kOpenMultiFile; case SelectFileDialog::Type::SELECT_SAVEAS_FILE: return crosapi::mojom::SelectFileDialogType::kSaveAsFile; case SelectFileDialog::Type::SELECT_NONE: NOTREACHED(); return crosapi::mojom::SelectFileDialogType::kOpenFile; } } crosapi::mojom::AllowedPaths GetMojoAllowedPaths( SelectFileDialog::FileTypeInfo::AllowedPaths allowed_paths) { switch (allowed_paths) { case SelectFileDialog::FileTypeInfo::ANY_PATH: return crosapi::mojom::AllowedPaths::kAnyPath; case SelectFileDialog::FileTypeInfo::NATIVE_PATH: return crosapi::mojom::AllowedPaths::kNativePath; case SelectFileDialog::FileTypeInfo::ANY_PATH_OR_URL: return crosapi::mojom::AllowedPaths::kAnyPathOrUrl; } } SelectedFileInfo ConvertSelectedFileInfo( crosapi::mojom::SelectedFileInfoPtr mojo_file) { SelectedFileInfo file; file.file_path = std::move(mojo_file->file_path); file.local_path = std::move(mojo_file->local_path); file.display_name = std::move(mojo_file->display_name); file.url = std::move(mojo_file->url); return file; } // Returns the ID of the Wayland shell surface that contains `window`, or an // empty string if `window` is not associated with a top-level window. std::string GetShellWindowUniqueId(aura::Window* window) { DCHECK(window); // If the window is not associated with a root window, there's no top-level // window to use as a parent for the file picker. Return an empty ID so // ash-chrome will use a modeless dialog. aura::Window* root_window = window->GetRootWindow(); if (!root_window) return std::string(); // On desktop aura there is one WindowTreeHost per top-level window. aura::WindowTreeHost* window_tree_host = root_window->GetHost(); DCHECK(window_tree_host); return window_tree_host->GetUniqueId(); } } // namespace SelectFileDialogLacros::Factory::Factory() = default; SelectFileDialogLacros::Factory::~Factory() = default; ui::SelectFileDialog* SelectFileDialogLacros::Factory::Create( ui::SelectFileDialog::Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) { return new SelectFileDialogLacros(listener, std::move(policy)); } SelectFileDialogLacros::SelectFileDialogLacros( Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) : ui::SelectFileDialog(listener, std::move(policy)) {} SelectFileDialogLacros::~SelectFileDialogLacros() = default; bool SelectFileDialogLacros::HasMultipleFileTypeChoicesImpl() { return true; } bool SelectFileDialogLacros::IsRunning(gfx::NativeWindow owning_window) const { return !owning_shell_window_id_.empty() && GetShellWindowUniqueId(owning_window) == owning_shell_window_id_; } void SelectFileDialogLacros::ListenerDestroyed() { listener_ = nullptr; } void SelectFileDialogLacros::SelectFileImpl( Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) { params_ = params; crosapi::mojom::SelectFileOptionsPtr options = crosapi::mojom::SelectFileOptions::New(); options->type = GetMojoType(type); options->title = title; options->default_path = default_path; if (file_types) { options->file_types = crosapi::mojom::SelectFileTypeInfo::New(); options->file_types->extensions = file_types->extensions; options->file_types->extension_description_overrides = file_types->extension_description_overrides; // NOTE: Index is 1-based, 0 means "no selection". options->file_types->default_file_type_index = file_type_index; options->file_types->include_all_files = file_types->include_all_files; options->file_types->allowed_paths = GetMojoAllowedPaths(file_types->allowed_paths); } // Modeless file dialogs have no owning window. if (owning_window) { owning_shell_window_id_ = GetShellWindowUniqueId(owning_window); options->owning_shell_window_id = owning_shell_window_id_; } if (caller && caller->is_valid()) { options->caller = *caller; } // Send request to ash-chrome. chromeos::LacrosService::Get() ->GetRemote<crosapi::mojom::SelectFile>() ->Select(std::move(options), base::BindOnce(&SelectFileDialogLacros::OnSelected, this)); } void SelectFileDialogLacros::OnSelected( crosapi::mojom::SelectFileResult result, std::vector<crosapi::mojom::SelectedFileInfoPtr> mojo_files, int file_type_index) { owning_shell_window_id_.clear(); if (!listener_) return; if (mojo_files.empty()) { listener_->FileSelectionCanceled(params_); return; } if (mojo_files.size() == 1) { SelectedFileInfo file = ConvertSelectedFileInfo(std::move(mojo_files[0])); listener_->FileSelectedWithExtraInfo(file, file_type_index, params_); return; } std::vector<SelectedFileInfo> files; for (auto& mojo_file : mojo_files) { files.push_back(ConvertSelectedFileInfo(std::move(mojo_file))); } listener_->MultiFilesSelectedWithExtraInfo(files, params_); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_lacros.cc
C++
unknown
6,562
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_LACROS_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_LACROS_H_ #include <vector> #include "base/memory/raw_ptr.h" #include "chromeos/crosapi/mojom/select_file.mojom-forward.h" #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/select_file_dialog_factory.h" #include "ui/shell_dialogs/shell_dialogs_export.h" namespace ui { // SelectFileDialogLacros implements file open and save dialogs for the // lacros-chrome binary. The dialog itself is handled by the file manager in // ash-chrome. class SHELL_DIALOGS_EXPORT SelectFileDialogLacros : public SelectFileDialog { public: class SHELL_DIALOGS_EXPORT Factory : public SelectFileDialogFactory { public: Factory(); Factory(const Factory&) = delete; Factory& operator=(const Factory&) = delete; ~Factory() override; // SelectFileDialogFactory: ui::SelectFileDialog* Create( ui::SelectFileDialog::Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) override; }; SelectFileDialogLacros(Listener* listener, std::unique_ptr<SelectFilePolicy> policy); SelectFileDialogLacros(const SelectFileDialogLacros&) = delete; SelectFileDialogLacros& operator=(const SelectFileDialogLacros&) = delete; // SelectFileDialog: void SelectFileImpl(Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) override; bool HasMultipleFileTypeChoicesImpl() override; bool IsRunning(gfx::NativeWindow owning_window) const override; void ListenerDestroyed() override; private: // Private because SelectFileDialog is ref-counted. ~SelectFileDialogLacros() override; // Callback for file selection. void OnSelected(crosapi::mojom::SelectFileResult result, std::vector<crosapi::mojom::SelectedFileInfoPtr> files, int file_type_index); // Cached parameters from the call to SelectFileImpl. raw_ptr<void> params_ = nullptr; // The unique ID of the wayland shell surface that owns this dialog. std::string owning_shell_window_id_; }; } // namespace ui #endif // UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_LACROS_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_lacros.h
C++
unknown
2,674
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This file implements common select dialog functionality between GTK and KDE. #include "ui/shell_dialogs/select_file_dialog_linux.h" #include "base/files/file_util.h" #include "base/notreached.h" #include "base/threading/thread_restrictions.h" namespace ui { base::FilePath* SelectFileDialogLinux::last_saved_path_ = nullptr; base::FilePath* SelectFileDialogLinux::last_opened_path_ = nullptr; SelectFileDialogLinux::SelectFileDialogLinux( Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) : SelectFileDialog(listener, std::move(policy)) { if (!last_saved_path_) { last_saved_path_ = new base::FilePath(); last_opened_path_ = new base::FilePath(); } } SelectFileDialogLinux::~SelectFileDialogLinux() = default; void SelectFileDialogLinux::ListenerDestroyed() { listener_ = nullptr; } bool SelectFileDialogLinux::CallDirectoryExistsOnUIThread( const base::FilePath& path) { base::ScopedAllowBlocking scoped_allow_blocking; return base::DirectoryExists(path); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_linux.cc
C++
unknown
1,186
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This file implements common select dialog functionality between GTK and KDE. #ifndef UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_LINUX_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_LINUX_H_ #include <stddef.h> #include <memory> #include <set> #include "base/nix/xdg_util.h" #include "ui/aura/window.h" #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/select_file_policy.h" #include "ui/shell_dialogs/shell_dialogs_export.h" namespace ui { // Shared implementation SelectFileDialog used on Linux class SHELL_DIALOGS_EXPORT SelectFileDialogLinux : public SelectFileDialog { public: SelectFileDialogLinux(const SelectFileDialogLinux&) = delete; SelectFileDialogLinux& operator=(const SelectFileDialogLinux&) = delete; // Returns true if the SelectFileDialog class returned by // NewSelectFileDialogImplKDE will actually work. static bool CheckKDEDialogWorksOnUIThread(std::string& kdialog_version); // BaseShellDialog implementation. void ListenerDestroyed() override; protected: explicit SelectFileDialogLinux(Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy); ~SelectFileDialogLinux() override; // SelectFileDialog implementation. // |params| is user data we pass back via the Listener interface. void SelectFileImpl(Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) override = 0; // Wrapper for base::DirectoryExists() that allow access on the UI // thread. Use this only in the file dialog functions, where it's ok // because the file dialog has to do many stats anyway. One more won't // hurt too badly and it's likely already cached. bool CallDirectoryExistsOnUIThread(const base::FilePath& path); const FileTypeInfo& file_types() const { return file_types_; } void set_file_types(const FileTypeInfo& file_types) { file_types_ = file_types; } size_t file_type_index() const { return file_type_index_; } void set_file_type_index(size_t file_type_index) { file_type_index_ = file_type_index; } Type type() const { return type_; } void set_type(Type type) { type_ = type; } static const base::FilePath* last_saved_path() { return last_saved_path_; } static void set_last_saved_path(const base::FilePath& last_saved_path) { *last_saved_path_ = last_saved_path; } static const base::FilePath* last_opened_path() { return last_opened_path_; } static void set_last_opened_path(const base::FilePath& last_opened_path) { *last_opened_path_ = last_opened_path; } private: // The file filters. FileTypeInfo file_types_; // The index of the default selected file filter. // Note: This starts from 1, not 0. size_t file_type_index_ = 0; // The type of dialog we are showing the user. Type type_ = SELECT_NONE; // These two variables track where the user last saved a file or opened a // file so that we can display future dialogs with the same starting path. static base::FilePath* last_saved_path_; static base::FilePath* last_opened_path_; }; } // namespace ui #endif // UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_LINUX_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_linux.h
C++
unknown
3,628
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <cstddef> #include <memory> #include <set> #include "base/command_line.h" #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" #include "base/logging.h" #include "base/nix/mime_util_xdg.h" #include "base/nix/xdg_util.h" #include "base/process/launch.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/threading/thread_restrictions.h" #include "base/version.h" #include "ui/aura/window_tree_host.h" #include "ui/base/l10n/l10n_util.h" #include "ui/shell_dialogs/select_file_dialog_linux.h" #include "ui/strings/grit/ui_strings.h" #include "url/gurl.h" namespace { std::string GetTitle(const std::string& title, int message_id) { return title.empty() ? l10n_util::GetStringUTF8(message_id) : title; } const char kKdialogBinary[] = "kdialog"; } // namespace namespace ui { // Implementation of SelectFileDialog that shows a KDE common dialog for // choosing a file or folder. This acts as a modal dialog. class SelectFileDialogLinuxKde : public SelectFileDialogLinux { public: SelectFileDialogLinuxKde(Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy, base::nix::DesktopEnvironment desktop, const std::string& kdialog_version); SelectFileDialogLinuxKde(const SelectFileDialogLinuxKde&) = delete; SelectFileDialogLinuxKde& operator=(const SelectFileDialogLinuxKde&) = delete; protected: ~SelectFileDialogLinuxKde() override; // BaseShellDialog implementation: bool IsRunning(gfx::NativeWindow parent_window) const override; // SelectFileDialog implementation. // |params| is user data we pass back via the Listener interface. void SelectFileImpl(Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) override; private: bool HasMultipleFileTypeChoicesImpl() override; struct KDialogParams { KDialogParams(const std::string& type, const std::string& title, const base::FilePath& default_path, gfx::AcceleratedWidget parent, bool file_operation, bool multiple_selection) : type(type), title(title), default_path(default_path), parent(parent), file_operation(file_operation), multiple_selection(multiple_selection) {} std::string type; std::string title; base::FilePath default_path; gfx::AcceleratedWidget parent; bool file_operation; bool multiple_selection; }; struct KDialogOutputParams { std::string output; int exit_code; }; // Get the filters from |file_types_| and concatenate them into // |filter_string|. std::string GetMimeTypeFilterString(); // Get KDialog command line representing the Argv array for KDialog. void GetKDialogCommandLine(const std::string& type, const std::string& title, const base::FilePath& default_path, gfx::AcceleratedWidget parent, bool file_operation, bool multiple_selection, base::CommandLine* command_line); // Call KDialog on the FILE thread and return the results. std::unique_ptr<KDialogOutputParams> CallKDialogOutput( const KDialogParams& params); // Notifies the listener that a single file was chosen. void FileSelected(const base::FilePath& path, void* params); // Notifies the listener that multiple files were chosen. void MultiFilesSelected(const std::vector<base::FilePath>& files, void* params); // Notifies the listener that no file was chosen (the action was canceled). // Dialog is passed so we can find that |params| pointer that was passed to // us when we were told to show the dialog. void FileNotSelected(void* params); void CreateSelectFolderDialog(Type type, const std::string& title, const base::FilePath& default_path, gfx::AcceleratedWidget parent, void* params); void CreateFileOpenDialog(const std::string& title, const base::FilePath& default_path, gfx::AcceleratedWidget parent, void* params); void CreateMultiFileOpenDialog(const std::string& title, const base::FilePath& default_path, gfx::AcceleratedWidget parent, void* params); void CreateSaveAsDialog(const std::string& title, const base::FilePath& default_path, gfx::AcceleratedWidget parent, void* params); // Common function for OnSelectSingleFileDialogResponse and // OnSelectSingleFolderDialogResponse. void SelectSingleFileHelper(void* params, bool allow_folder, std::unique_ptr<KDialogOutputParams> results); void OnSelectSingleFileDialogResponse( gfx::AcceleratedWidget parent, void* params, std::unique_ptr<KDialogOutputParams> results); void OnSelectMultiFileDialogResponse( gfx::AcceleratedWidget parent, void* params, std::unique_ptr<KDialogOutputParams> results); void OnSelectSingleFolderDialogResponse( gfx::AcceleratedWidget parent, void* params, std::unique_ptr<KDialogOutputParams> results); // Should be either DESKTOP_ENVIRONMENT_KDE3, KDE4, KDE5, or KDE6. base::nix::DesktopEnvironment desktop_; // The set of all parent windows for which we are currently running // dialogs. This should only be accessed on the UI thread. std::set<gfx::AcceleratedWidget> parents_; // Set to true if the kdialog version is new enough to support passing // multiple extensions with descriptions, eliminating the need for the lossy // conversion of extensions to mime-types. bool kdialog_supports_multiple_extensions_ = false; // A task runner for blocking pipe reads. scoped_refptr<base::SequencedTaskRunner> pipe_task_runner_; SEQUENCE_CHECKER(sequence_checker_); }; // static bool SelectFileDialogLinux::CheckKDEDialogWorksOnUIThread( std::string& kdialog_version) { // No choice. UI thread can't continue without an answer here. Fortunately we // only do this once, the first time a file dialog is displayed. base::ScopedAllowBlocking scoped_allow_blocking; base::CommandLine::StringVector cmd_vector; cmd_vector.push_back(kKdialogBinary); cmd_vector.push_back("--version"); base::CommandLine command_line(cmd_vector); return base::GetAppOutput(command_line, &kdialog_version); } SelectFileDialog* NewSelectFileDialogLinuxKde( SelectFileDialog::Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy, base::nix::DesktopEnvironment desktop, const std::string& kdialog_version) { return new SelectFileDialogLinuxKde(listener, std::move(policy), desktop, kdialog_version); } SelectFileDialogLinuxKde::SelectFileDialogLinuxKde( Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy, base::nix::DesktopEnvironment desktop, const std::string& kdialog_version) : SelectFileDialogLinux(listener, std::move(policy)), desktop_(desktop), pipe_task_runner_(base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) { DCHECK(desktop_ == base::nix::DESKTOP_ENVIRONMENT_KDE3 || desktop_ == base::nix::DESKTOP_ENVIRONMENT_KDE4 || desktop_ == base::nix::DESKTOP_ENVIRONMENT_KDE5 || desktop_ == base::nix::DESKTOP_ENVIRONMENT_KDE6); // |kdialog_version| should be of the form "kdialog 1.2.3", so split on // whitespace and then try to parse a version from the second piece. If // parsing fails for whatever reason, we fall back to the behavior that works // with all currently known versions of kdialog. std::vector<base::StringPiece> version_pieces = base::SplitStringPiece( kdialog_version, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); if (version_pieces.size() >= 2) { base::Version parsed_version(version_pieces[1]); if (parsed_version.IsValid()) { kdialog_supports_multiple_extensions_ = parsed_version >= base::Version("19.12"); } } } SelectFileDialogLinuxKde::~SelectFileDialogLinuxKde() = default; bool SelectFileDialogLinuxKde::IsRunning( gfx::NativeWindow parent_window) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (parent_window && parent_window->GetHost()) { auto window = parent_window->GetHost()->GetAcceleratedWidget(); return parents_.find(window) != parents_.end(); } return false; } // We ignore |default_extension|. void SelectFileDialogLinuxKde::SelectFileImpl( Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); set_type(type); gfx::AcceleratedWidget window = gfx::kNullAcceleratedWidget; if (owning_window && owning_window->GetHost()) { // |owning_window| can be null when user right-clicks on a downloadable item // and chooses 'Open Link in New Tab' when 'Ask where to save each file // before downloading.' preference is turned on. (http://crbug.com/29213) window = owning_window->GetHost()->GetAcceleratedWidget(); parents_.insert(window); } std::string title_string = base::UTF16ToUTF8(title); set_file_type_index(file_type_index); if (file_types) { set_file_types(*file_types); } else { auto file_types_copy = SelectFileDialogLinux::file_types(); file_types_copy.include_all_files = true; set_file_types(file_types_copy); } switch (type) { case SELECT_FOLDER: case SELECT_UPLOAD_FOLDER: case SELECT_EXISTING_FOLDER: CreateSelectFolderDialog(type, title_string, default_path, window, params); return; case SELECT_OPEN_FILE: CreateFileOpenDialog(title_string, default_path, window, params); return; case SELECT_OPEN_MULTI_FILE: CreateMultiFileOpenDialog(title_string, default_path, window, params); return; case SELECT_SAVEAS_FILE: CreateSaveAsDialog(title_string, default_path, window, params); return; case SELECT_NONE: NOTREACHED(); return; } } bool SelectFileDialogLinuxKde::HasMultipleFileTypeChoicesImpl() { return file_types().extensions.size() > 1; } std::string SelectFileDialogLinuxKde::GetMimeTypeFilterString() { DCHECK(pipe_task_runner_->RunsTasksInCurrentSequence()); if (!kdialog_supports_multiple_extensions_) { // We need a filter set because the same mime type can appear multiple // times. std::set<std::string> filter_set; for (auto& extensions : file_types().extensions) { for (auto& extension : extensions) { if (!extension.empty()) { std::string mime_type = base::nix::GetFileMimeType( base::FilePath("name").ReplaceExtension(extension)); filter_set.insert(mime_type); } } } std::vector<std::string> filter_vector(filter_set.cbegin(), filter_set.cend()); // Add the *.* filter, but only if we have added other filters (otherwise it // is implied). It needs to be added last to avoid being picked as the // default filter. if (file_types().include_all_files && !file_types().extensions.empty()) { DCHECK(filter_set.find("application/octet-stream") == filter_set.end()); filter_vector.push_back("application/octet-stream"); } return base::JoinString(filter_vector, " "); } std::vector<std::string> filters; for (size_t i = 0; i < file_types().extensions.size(); ++i) { std::set<std::string> extension_filters; for (const auto& extension : file_types().extensions[i]) { if (extension.empty()) continue; extension_filters.insert(std::string("*.") + extension); } // We didn't find any non-empty extensions to filter on. if (extension_filters.empty()) continue; std::vector<std::string> extension_filters_vector(extension_filters.begin(), extension_filters.end()); std::string description; // The description vector may be blank, in which case we are supposed to // use some sort of default description based on the filter. if (i < file_types().extension_description_overrides.size()) { description = base::UTF16ToUTF8(file_types().extension_description_overrides[i]); // Filter out any characters that would mess up kdialog's parsing. base::ReplaceChars(description, "|()", "", &description); } else { // There is no system default filter description so we use // the extensions themselves if the description is blank. description = base::JoinString(extension_filters_vector, ","); } filters.push_back(description + " (" + base::JoinString(extension_filters_vector, " ") + ")"); } if (file_types().include_all_files && !file_types().extensions.empty()) filters.push_back(l10n_util::GetStringUTF8(IDS_SAVEAS_ALL_FILES) + " (*)"); return base::JoinString(filters, "|"); } std::unique_ptr<SelectFileDialogLinuxKde::KDialogOutputParams> SelectFileDialogLinuxKde::CallKDialogOutput(const KDialogParams& params) { DCHECK(pipe_task_runner_->RunsTasksInCurrentSequence()); base::CommandLine::StringVector cmd_vector; cmd_vector.push_back(kKdialogBinary); base::CommandLine command_line(cmd_vector); GetKDialogCommandLine(params.type, params.title, params.default_path, params.parent, params.file_operation, params.multiple_selection, &command_line); auto results = std::make_unique<KDialogOutputParams>(); // Get output from KDialog base::GetAppOutputWithExitCode(command_line, &results->output, &results->exit_code); if (!results->output.empty()) results->output.erase(results->output.size() - 1); return results; } void SelectFileDialogLinuxKde::GetKDialogCommandLine( const std::string& type, const std::string& title, const base::FilePath& path, gfx::AcceleratedWidget parent, bool file_operation, bool multiple_selection, base::CommandLine* command_line) { CHECK(command_line); // Attach to the current Chrome window. if (parent != gfx::kNullAcceleratedWidget) { command_line->AppendSwitchNative( desktop_ == base::nix::DESKTOP_ENVIRONMENT_KDE3 ? "--embed" : "--attach", base::NumberToString(static_cast<uint32_t>(parent))); } // Set the correct title for the dialog. if (!title.empty()) command_line->AppendSwitchNative("--title", title); // Enable multiple file selection if we need to. if (multiple_selection) { command_line->AppendSwitch("--multiple"); command_line->AppendSwitch("--separate-output"); } command_line->AppendSwitch(type); // The path should never be empty. If it is, set it to PWD. if (path.empty()) command_line->AppendArgPath(base::FilePath(".")); else command_line->AppendArgPath(path); // Depending on the type of the operation we need, get the path to the // file/folder and set up mime type filters. if (file_operation) command_line->AppendArg(GetMimeTypeFilterString()); VLOG(1) << "KDialog command line: " << command_line->GetCommandLineString(); } void SelectFileDialogLinuxKde::FileSelected(const base::FilePath& path, void* params) { if (type() == SELECT_SAVEAS_FILE) set_last_saved_path(path.DirName()); else if (type() == SELECT_OPEN_FILE) set_last_opened_path(path.DirName()); else if (type() == SELECT_FOLDER || type() == SELECT_UPLOAD_FOLDER || type() == SELECT_EXISTING_FOLDER) set_last_opened_path(path); else NOTREACHED(); if (listener_) { // What does the filter index actually do? // TODO(dfilimon): Get a reasonable index value from somewhere. listener_->FileSelected(path, 1, params); } } void SelectFileDialogLinuxKde::MultiFilesSelected( const std::vector<base::FilePath>& files, void* params) { set_last_opened_path(files[0].DirName()); if (listener_) listener_->MultiFilesSelected(files, params); } void SelectFileDialogLinuxKde::FileNotSelected(void* params) { if (listener_) listener_->FileSelectionCanceled(params); } void SelectFileDialogLinuxKde::CreateSelectFolderDialog( Type type, const std::string& title, const base::FilePath& default_path, gfx::AcceleratedWidget parent, void* params) { int title_message_id = (type == SELECT_UPLOAD_FOLDER) ? IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE : IDS_SELECT_FOLDER_DIALOG_TITLE; pipe_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce( &SelectFileDialogLinuxKde::CallKDialogOutput, this, KDialogParams( "--getexistingdirectory", GetTitle(title, title_message_id), default_path.empty() ? *last_opened_path() : default_path, parent, false, false)), base::BindOnce( &SelectFileDialogLinuxKde::OnSelectSingleFolderDialogResponse, this, parent, params)); } void SelectFileDialogLinuxKde::CreateFileOpenDialog( const std::string& title, const base::FilePath& default_path, gfx::AcceleratedWidget parent, void* params) { pipe_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce( &SelectFileDialogLinuxKde::CallKDialogOutput, this, KDialogParams( "--getopenfilename", GetTitle(title, IDS_OPEN_FILE_DIALOG_TITLE), default_path.empty() ? *last_opened_path() : default_path, parent, true, false)), base::BindOnce( &SelectFileDialogLinuxKde::OnSelectSingleFileDialogResponse, this, parent, params)); } void SelectFileDialogLinuxKde::CreateMultiFileOpenDialog( const std::string& title, const base::FilePath& default_path, gfx::AcceleratedWidget parent, void* params) { pipe_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce( &SelectFileDialogLinuxKde::CallKDialogOutput, this, KDialogParams( "--getopenfilename", GetTitle(title, IDS_OPEN_FILES_DIALOG_TITLE), default_path.empty() ? *last_opened_path() : default_path, parent, true, true)), base::BindOnce(&SelectFileDialogLinuxKde::OnSelectMultiFileDialogResponse, this, parent, params)); } void SelectFileDialogLinuxKde::CreateSaveAsDialog( const std::string& title, const base::FilePath& default_path, gfx::AcceleratedWidget parent, void* params) { pipe_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce( &SelectFileDialogLinuxKde::CallKDialogOutput, this, KDialogParams( "--getsavefilename", GetTitle(title, IDS_SAVE_AS_DIALOG_TITLE), default_path.empty() ? *last_saved_path() : default_path, parent, true, false)), base::BindOnce( &SelectFileDialogLinuxKde::OnSelectSingleFileDialogResponse, this, parent, params)); } void SelectFileDialogLinuxKde::SelectSingleFileHelper( void* params, bool allow_folder, std::unique_ptr<KDialogOutputParams> results) { VLOG(1) << "[kdialog] SingleFileResponse: " << results->output; if (results->exit_code || results->output.empty()) { FileNotSelected(params); return; } base::FilePath path(results->output); if (allow_folder) { FileSelected(path, params); return; } if (CallDirectoryExistsOnUIThread(path)) FileNotSelected(params); else FileSelected(path, params); } void SelectFileDialogLinuxKde::OnSelectSingleFileDialogResponse( gfx::AcceleratedWidget parent, void* params, std::unique_ptr<KDialogOutputParams> results) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); parents_.erase(parent); SelectSingleFileHelper(params, false, std::move(results)); } void SelectFileDialogLinuxKde::OnSelectSingleFolderDialogResponse( gfx::AcceleratedWidget parent, void* params, std::unique_ptr<KDialogOutputParams> results) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); parents_.erase(parent); SelectSingleFileHelper(params, true, std::move(results)); } void SelectFileDialogLinuxKde::OnSelectMultiFileDialogResponse( gfx::AcceleratedWidget parent, void* params, std::unique_ptr<KDialogOutputParams> results) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); VLOG(1) << "[kdialog] MultiFileResponse: " << results->output; parents_.erase(parent); if (results->exit_code || results->output.empty()) { FileNotSelected(params); return; } std::vector<base::FilePath> filenames_fp; for (const base::StringPiece& line : base::SplitStringPiece(results->output, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) { base::FilePath path(line); if (CallDirectoryExistsOnUIThread(path)) continue; filenames_fp.push_back(path); } if (filenames_fp.empty()) { FileNotSelected(params); return; } MultiFilesSelected(filenames_fp, params); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_linux_kde.cc
C++
unknown
22,763
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_LINUX_KDE_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_LINUX_KDE_H_ #include <string> #include "base/nix/xdg_util.h" #include "ui/shell_dialogs/select_file_dialog.h" namespace ui { class SelectFileDialog; SelectFileDialog* NewSelectFileDialogLinuxKde( SelectFileDialog::Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy, base::nix::DesktopEnvironment desktop, const std::string& kdialog_version); } // namespace ui #endif // UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_LINUX_KDE_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_linux_kde.h
C++
unknown
704
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/select_file_dialog_linux_portal.h" #include "base/containers/contains.h" #include "base/functional/bind.h" #include "base/logging.h" #include "base/no_destructor.h" #include "base/notreached.h" #include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" #include "base/task/sequenced_task_runner.h" #include "base/time/time.h" #include "components/dbus/thread_linux/dbus_thread_linux.h" #include "dbus/object_path.h" #include "dbus/property.h" #include "ui/aura/window_tree_host.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/native_widget_types.h" #include "ui/linux/linux_ui_delegate.h" #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/strings/grit/ui_strings.h" #include "url/gurl.h" #include "url/url_util.h" namespace ui { namespace { constexpr char kDBusMethodNameHasOwner[] = "NameHasOwner"; constexpr char kDBusMethodListActivatableNames[] = "ListActivatableNames"; constexpr char kMethodStartServiceByName[] = "StartServiceByName"; constexpr char kXdgPortalService[] = "org.freedesktop.portal.Desktop"; constexpr char kXdgPortalObject[] = "/org/freedesktop/portal/desktop"; constexpr int kXdgPortalRequiredVersion = 3; constexpr char kXdgPortalRequestInterfaceName[] = "org.freedesktop.portal.Request"; constexpr char kXdgPortalResponseSignal[] = "Response"; constexpr char kFileChooserInterfaceName[] = "org.freedesktop.portal.FileChooser"; constexpr char kFileChooserMethodOpenFile[] = "OpenFile"; constexpr char kFileChooserMethodSaveFile[] = "SaveFile"; constexpr char kFileChooserOptionHandleToken[] = "handle_token"; constexpr char kFileChooserOptionAcceptLabel[] = "accept_label"; constexpr char kFileChooserOptionMultiple[] = "multiple"; constexpr char kFileChooserOptionDirectory[] = "directory"; constexpr char kFileChooserOptionFilters[] = "filters"; constexpr char kFileChooserOptionCurrentFilter[] = "current_filter"; constexpr char kFileChooserOptionCurrentFolder[] = "current_folder"; constexpr char kFileChooserOptionCurrentName[] = "current_name"; constexpr int kFileChooserFilterKindGlob = 0; constexpr char kFileUriPrefix[] = "file://"; // Time to wait for the notification service to start, in milliseconds. constexpr base::TimeDelta kStartServiceTimeout = base::Seconds(1); struct FileChooserProperties : dbus::PropertySet { dbus::Property<uint32_t> version; explicit FileChooserProperties(dbus::ObjectProxy* object_proxy) : dbus::PropertySet(object_proxy, kFileChooserInterfaceName, {}) { RegisterProperty("version", &version); } ~FileChooserProperties() override = default; }; void AppendStringOption(dbus::MessageWriter* writer, const std::string& name, const std::string& value) { dbus::MessageWriter option_writer(nullptr); writer->OpenDictEntry(&option_writer); option_writer.AppendString(name); option_writer.AppendVariantOfString(value); writer->CloseContainer(&option_writer); } void AppendByteStringOption(dbus::MessageWriter* writer, const std::string& name, const std::string& value) { dbus::MessageWriter option_writer(nullptr); writer->OpenDictEntry(&option_writer); option_writer.AppendString(name); dbus::MessageWriter value_writer(nullptr); option_writer.OpenVariant("ay", &value_writer); value_writer.AppendArrayOfBytes( reinterpret_cast<const std::uint8_t*>(value.c_str()), // size + 1 will include the null terminator. value.size() + 1); option_writer.CloseContainer(&value_writer); writer->CloseContainer(&option_writer); } void AppendBoolOption(dbus::MessageWriter* writer, const std::string& name, bool value) { dbus::MessageWriter option_writer(nullptr); writer->OpenDictEntry(&option_writer); option_writer.AppendString(name); option_writer.AppendVariantOfBool(value); writer->CloseContainer(&option_writer); } scoped_refptr<dbus::Bus>* AcquireBusStorageOnBusThread() { static base::NoDestructor<scoped_refptr<dbus::Bus>> bus(nullptr); if (!*bus) { dbus::Bus::Options options; options.bus_type = dbus::Bus::SESSION; options.connection_type = dbus::Bus::PRIVATE; options.dbus_task_runner = dbus_thread_linux::GetTaskRunner(); *bus = base::MakeRefCounted<dbus::Bus>(options); } return bus.get(); } dbus::Bus* AcquireBusOnBusThread() { return AcquireBusStorageOnBusThread()->get(); } void DestroyBusOnBusThread() { scoped_refptr<dbus::Bus>* bus_storage = AcquireBusStorageOnBusThread(); (*bus_storage)->ShutdownAndBlock(); // If the connection is restarted later on, we need to make sure the entire // bus is newly created. Otherwise, references to an old, invalid task runner // may persist. bus_storage->reset(); } } // namespace SelectFileDialogLinuxPortal::SelectFileDialogLinuxPortal( Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) : SelectFileDialogLinux(listener, std::move(policy)) {} SelectFileDialogLinuxPortal::~SelectFileDialogLinuxPortal() = default; // static void SelectFileDialogLinuxPortal::StartAvailabilityTestInBackground() { if (GetAvailabilityTestCompletionFlag()->IsSet()) return; dbus_thread_linux::GetTaskRunner()->PostTask( FROM_HERE, base::BindOnce( &SelectFileDialogLinuxPortal::CheckPortalAvailabilityOnBusThread)); } // static bool SelectFileDialogLinuxPortal::IsPortalAvailable() { if (!GetAvailabilityTestCompletionFlag()->IsSet()) LOG(WARNING) << "Portal availability checked before test was complete"; return is_portal_available_; } // static void SelectFileDialogLinuxPortal::DestroyPortalConnection() { dbus_thread_linux::GetTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&DestroyBusOnBusThread)); } bool SelectFileDialogLinuxPortal::IsRunning( gfx::NativeWindow parent_window) const { if (parent_window && parent_window->GetHost()) { auto window = parent_window->GetHost()->GetAcceleratedWidget(); return parent_ && parent_.value() == window; } return false; } void SelectFileDialogLinuxPortal::SelectFileImpl( Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) { auto info = base::MakeRefCounted<DialogInfo>( base::BindOnce(&SelectFileDialogLinuxPortal::CompleteOpenOnMainThread, this), base::BindOnce(&SelectFileDialogLinuxPortal::CancelOpenOnMainThread, this)); info_ = info; info->type = type; info->main_task_runner = base::SequencedTaskRunner::GetCurrentDefault(); listener_params_ = params; if (owning_window && owning_window->GetHost()) { parent_ = owning_window->GetHost()->GetAcceleratedWidget(); } if (file_types) set_file_types(*file_types); set_file_type_index(file_type_index); PortalFilterSet filter_set = BuildFilterSet(); // Keep a copy of the filters so the index of the chosen one can be identified // and returned to listeners later. filters_ = filter_set.filters; if (parent_) { auto* delegate = ui::LinuxUiDelegate::GetInstance(); if (delegate && delegate->ExportWindowHandle( *parent_, base::BindOnce( &SelectFileDialogLinuxPortal::SelectFileImplWithParentHandle, this, title, default_path, filter_set, default_extension))) { // Return early to skip the fallback below. return; } else { LOG(WARNING) << "Failed to export window handle for portal select dialog"; } } // No parent, so just use a blank parent handle. SelectFileImplWithParentHandle(title, default_path, filter_set, default_extension, ""); } bool SelectFileDialogLinuxPortal::HasMultipleFileTypeChoicesImpl() { return file_types().extensions.size() > 1; } // static void SelectFileDialogLinuxPortal::CheckPortalAvailabilityOnBusThread() { DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence()); base::AtomicFlag* availability_test_complete = GetAvailabilityTestCompletionFlag(); if (availability_test_complete->IsSet()) return; dbus::Bus* bus = AcquireBusOnBusThread(); dbus::ObjectProxy* dbus_proxy = bus->GetObjectProxy(DBUS_SERVICE_DBUS, dbus::ObjectPath(DBUS_PATH_DBUS)); if (IsPortalRunningOnBusThread(dbus_proxy) || IsPortalActivatableOnBusThread(dbus_proxy)) { dbus::ObjectPath portal_path(kXdgPortalObject); dbus::ObjectProxy* portal = bus->GetObjectProxy(kXdgPortalService, portal_path); FileChooserProperties properties(portal); if (!properties.GetAndBlock(&properties.version)) { LOG(ERROR) << "Failed to read portal version property"; } else if (properties.version.value() >= kXdgPortalRequiredVersion) { is_portal_available_ = true; } } VLOG(1) << "File chooser portal available: " << (is_portal_available_ ? "yes" : "no"); availability_test_complete->Set(); } // static bool SelectFileDialogLinuxPortal::IsPortalRunningOnBusThread( dbus::ObjectProxy* dbus_proxy) { dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, kDBusMethodNameHasOwner); dbus::MessageWriter writer(&method_call); writer.AppendString(kXdgPortalService); std::unique_ptr<dbus::Response> response = dbus_proxy->CallMethodAndBlock( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT); if (!response) return false; dbus::MessageReader reader(response.get()); bool owned = false; if (!reader.PopBool(&owned)) { LOG(ERROR) << "Failed to read response"; return false; } return owned; } // static bool SelectFileDialogLinuxPortal::IsPortalActivatableOnBusThread( dbus::ObjectProxy* dbus_proxy) { dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, kDBusMethodListActivatableNames); std::unique_ptr<dbus::Response> response = dbus_proxy->CallMethodAndBlock( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT); if (!response) return false; dbus::MessageReader reader(response.get()); std::vector<std::string> names; if (!reader.PopArrayOfStrings(&names)) { LOG(ERROR) << "Failed to read response"; return false; } if (base::Contains(names, kXdgPortalService)) { dbus::MethodCall start_service_call(DBUS_INTERFACE_DBUS, kMethodStartServiceByName); dbus::MessageWriter start_service_writer(&start_service_call); start_service_writer.AppendString(kXdgPortalService); start_service_writer.AppendUint32(/*flags=*/0); auto start_service_response = dbus_proxy->CallMethodAndBlock( &start_service_call, kStartServiceTimeout.InMilliseconds()); if (!start_service_response) return false; dbus::MessageReader start_service_reader(start_service_response.get()); uint32_t start_service_reply = 0; if (start_service_reader.PopUint32(&start_service_reply) && (start_service_reply == DBUS_START_REPLY_SUCCESS || start_service_reply == DBUS_START_REPLY_ALREADY_RUNNING)) { return true; } } return false; } SelectFileDialogLinuxPortal::PortalFilter::PortalFilter() = default; SelectFileDialogLinuxPortal::PortalFilter::PortalFilter( const PortalFilter& other) = default; SelectFileDialogLinuxPortal::PortalFilter::PortalFilter(PortalFilter&& other) = default; SelectFileDialogLinuxPortal::PortalFilter::~PortalFilter() = default; SelectFileDialogLinuxPortal::PortalFilterSet::PortalFilterSet() = default; SelectFileDialogLinuxPortal::PortalFilterSet::PortalFilterSet( const PortalFilterSet& other) = default; SelectFileDialogLinuxPortal::PortalFilterSet::PortalFilterSet( PortalFilterSet&& other) = default; SelectFileDialogLinuxPortal::PortalFilterSet::~PortalFilterSet() = default; SelectFileDialogLinuxPortal::DialogInfo::DialogInfo( OnSelectFileExecutedCallback selected_callback, OnSelectFileCanceledCallback canceled_callback) : selected_callback_(std::move(selected_callback)), canceled_callback_(std::move(canceled_callback)) {} SelectFileDialogLinuxPortal::DialogInfo::~DialogInfo() = default; // static base::AtomicFlag* SelectFileDialogLinuxPortal::GetAvailabilityTestCompletionFlag() { static base::NoDestructor<base::AtomicFlag> flag; return flag.get(); } SelectFileDialogLinuxPortal::PortalFilterSet SelectFileDialogLinuxPortal::BuildFilterSet() { PortalFilterSet filter_set; for (size_t i = 0; i < file_types().extensions.size(); ++i) { PortalFilter filter; for (const std::string& extension : file_types().extensions[i]) { if (extension.empty()) continue; filter.patterns.push_back("*." + base::ToLowerASCII(extension)); auto upper = "*." + base::ToUpperASCII(extension); if (upper != filter.patterns.back()) filter.patterns.push_back(std::move(upper)); } if (filter.patterns.empty()) continue; // If there is no matching description, use a default description based on // the filter. if (i < file_types().extension_description_overrides.size()) { filter.name = base::UTF16ToUTF8(file_types().extension_description_overrides[i]); } else { std::vector<std::string> patterns_vector(filter.patterns.begin(), filter.patterns.end()); filter.name = base::JoinString(patterns_vector, ","); } // The -1 is required to match against the right filter because // |file_type_index_| is 1-indexed. if (i == file_type_index() - 1) filter_set.default_filter = filter; filter_set.filters.push_back(std::move(filter)); } if (file_types().include_all_files && !filter_set.filters.empty()) { // Add the *.* filter, but only if we have added other filters (otherwise it // is implied). PortalFilter filter; filter.name = l10n_util::GetStringUTF8(IDS_SAVEAS_ALL_FILES); filter.patterns.push_back("*.*"); filter_set.filters.push_back(std::move(filter)); } return filter_set; } void SelectFileDialogLinuxPortal::SelectFileImplWithParentHandle( std::u16string title, base::FilePath default_path, PortalFilterSet filter_set, base::FilePath::StringType default_extension, std::string parent_handle) { bool default_path_exists = CallDirectoryExistsOnUIThread(default_path); dbus_thread_linux::GetTaskRunner()->PostTask( FROM_HERE, base::BindOnce( &SelectFileDialogLinuxPortal::DialogInfo::SelectFileImplOnBusThread, info_, std::move(title), std::move(default_path), default_path_exists, std::move(filter_set), std::move(default_extension), std::move(parent_handle))); } void SelectFileDialogLinuxPortal::DialogInfo::SelectFileImplOnBusThread( std::u16string title, base::FilePath default_path, const bool default_path_exists, PortalFilterSet filter_set, base::FilePath::StringType default_extension, std::string parent_handle) { DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence()); dbus::Bus* bus = AcquireBusOnBusThread(); if (!bus->Connect()) LOG(ERROR) << "Could not connect to bus for XDG portal"; std::string method; switch (type) { case SELECT_FOLDER: case SELECT_UPLOAD_FOLDER: case SELECT_EXISTING_FOLDER: case SELECT_OPEN_FILE: case SELECT_OPEN_MULTI_FILE: method = kFileChooserMethodOpenFile; break; case SELECT_SAVEAS_FILE: method = kFileChooserMethodSaveFile; break; case SELECT_NONE: NOTREACHED(); break; } dbus::MethodCall method_call(kFileChooserInterfaceName, method); dbus::MessageWriter writer(&method_call); writer.AppendString(parent_handle); if (!title.empty()) { writer.AppendString(base::UTF16ToUTF8(title)); } else { int message_id = 0; if (type == SELECT_SAVEAS_FILE) { message_id = IDS_SAVEAS_ALL_FILES; } else if (type == SELECT_OPEN_MULTI_FILE) { message_id = IDS_OPEN_FILES_DIALOG_TITLE; } else { message_id = IDS_OPEN_FILE_DIALOG_TITLE; } writer.AppendString(l10n_util::GetStringUTF8(message_id)); } std::string response_handle_token = base::StringPrintf("handle_%d", handle_token_counter_++); AppendOptions(&writer, response_handle_token, default_path, default_path_exists, filter_set); // The sender part of the handle object contains the D-Bus connection name // without the prefix colon and with all dots replaced with underscores. std::string sender_part; base::ReplaceChars(bus->GetConnectionName().substr(1), ".", "_", &sender_part); dbus::ObjectPath expected_handle_path( base::StringPrintf("/org/freedesktop/portal/desktop/request/%s/%s", sender_part.c_str(), response_handle_token.c_str())); response_handle_ = bus->GetObjectProxy(kXdgPortalService, expected_handle_path); ConnectToHandle(); dbus::ObjectPath portal_path(kXdgPortalObject); dbus::ObjectProxy* portal = bus->GetObjectProxy(kXdgPortalService, portal_path); portal->CallMethodWithErrorResponse( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&DialogInfo::OnCallResponse, this, base::Unretained(bus))); } void SelectFileDialogLinuxPortal::DialogInfo::AppendOptions( dbus::MessageWriter* writer, const std::string& response_handle_token, const base::FilePath& default_path, const bool default_path_exists, const SelectFileDialogLinuxPortal::PortalFilterSet& filter_set) { dbus::MessageWriter options_writer(nullptr); writer->OpenArray("{sv}", &options_writer); AppendStringOption(&options_writer, kFileChooserOptionHandleToken, response_handle_token); if (type == SelectFileDialog::Type::SELECT_UPLOAD_FOLDER) { AppendStringOption(&options_writer, kFileChooserOptionAcceptLabel, l10n_util::GetStringUTF8( IDS_SELECT_UPLOAD_FOLDER_DIALOG_UPLOAD_BUTTON)); } if (type == SelectFileDialog::Type::SELECT_FOLDER || type == SelectFileDialog::Type::SELECT_UPLOAD_FOLDER || type == SelectFileDialog::Type::SELECT_EXISTING_FOLDER) { AppendBoolOption(&options_writer, kFileChooserOptionDirectory, true); } else if (type == SelectFileDialog::Type::SELECT_OPEN_MULTI_FILE) { AppendBoolOption(&options_writer, kFileChooserOptionMultiple, true); } if (type == SelectFileDialog::Type::SELECT_SAVEAS_FILE && !default_path.empty()) { if (default_path_exists) { // If this is an existing directory, navigate to that directory, with no // filename. AppendByteStringOption(&options_writer, kFileChooserOptionCurrentFolder, default_path.value()); } else { // The default path does not exist, or is an existing file. We use // current_folder followed by current_name, as per the recommendation of // the GTK docs and the pattern followed by SelectFileDialogLinuxGtk. AppendByteStringOption(&options_writer, kFileChooserOptionCurrentFolder, default_path.DirName().value()); AppendStringOption(&options_writer, kFileChooserOptionCurrentName, default_path.BaseName().value()); } } AppendFiltersOption(&options_writer, filter_set.filters); if (filter_set.default_filter) { dbus::MessageWriter option_writer(nullptr); options_writer.OpenDictEntry(&option_writer); option_writer.AppendString(kFileChooserOptionCurrentFilter); dbus::MessageWriter value_writer(nullptr); option_writer.OpenVariant("(sa(us))", &value_writer); AppendFilterStruct(&value_writer, *filter_set.default_filter); option_writer.CloseContainer(&value_writer); options_writer.CloseContainer(&option_writer); } writer->CloseContainer(&options_writer); } void SelectFileDialogLinuxPortal::DialogInfo::AppendFiltersOption( dbus::MessageWriter* writer, const std::vector<PortalFilter>& filters) { dbus::MessageWriter option_writer(nullptr); writer->OpenDictEntry(&option_writer); option_writer.AppendString(kFileChooserOptionFilters); dbus::MessageWriter variant_writer(nullptr); option_writer.OpenVariant("a(sa(us))", &variant_writer); dbus::MessageWriter filters_writer(nullptr); variant_writer.OpenArray("(sa(us))", &filters_writer); for (const PortalFilter& filter : filters) { AppendFilterStruct(&filters_writer, filter); } variant_writer.CloseContainer(&filters_writer); option_writer.CloseContainer(&variant_writer); writer->CloseContainer(&option_writer); } void SelectFileDialogLinuxPortal::DialogInfo::AppendFilterStruct( dbus::MessageWriter* writer, const PortalFilter& filter) { dbus::MessageWriter filter_writer(nullptr); writer->OpenStruct(&filter_writer); filter_writer.AppendString(filter.name); dbus::MessageWriter patterns_writer(nullptr); filter_writer.OpenArray("(us)", &patterns_writer); for (const std::string& pattern : filter.patterns) { dbus::MessageWriter pattern_writer(nullptr); patterns_writer.OpenStruct(&pattern_writer); pattern_writer.AppendUint32(kFileChooserFilterKindGlob); pattern_writer.AppendString(pattern); patterns_writer.CloseContainer(&pattern_writer); } filter_writer.CloseContainer(&patterns_writer); writer->CloseContainer(&filter_writer); } void SelectFileDialogLinuxPortal::DialogInfo::ConnectToHandle() { DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence()); response_handle_->ConnectToSignal( kXdgPortalRequestInterfaceName, kXdgPortalResponseSignal, base::BindRepeating(&DialogInfo::OnResponseSignalEmitted, this), base::BindOnce(&DialogInfo::OnResponseSignalConnected, this)); } void SelectFileDialogLinuxPortal::DialogInfo::CompleteOpen( std::vector<base::FilePath> paths, std::string current_filter) { DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence()); response_handle_->Detach(); main_task_runner->PostTask( FROM_HERE, base::BindOnce(std::move(selected_callback_), std::move(paths), std::move(current_filter))); } void SelectFileDialogLinuxPortal::DialogInfo::CancelOpen() { response_handle_->Detach(); main_task_runner->PostTask(FROM_HERE, std::move(canceled_callback_)); } void SelectFileDialogLinuxPortal::CompleteOpenOnMainThread( std::vector<base::FilePath> paths, std::string current_filter) { UnparentOnMainThread(); if (listener_) { if (info_->type == SELECT_OPEN_MULTI_FILE) { listener_->MultiFilesSelected(paths, listener_params_); } else if (paths.size() > 1) { LOG(ERROR) << "Got >1 file URI from a single-file chooser"; } else { int index = 1; for (size_t i = 0; i < filters_.size(); ++i) { if (filters_[i].name == current_filter) { index = 1 + i; break; } } listener_->FileSelected(paths.front(), index, listener_params_); } } } void SelectFileDialogLinuxPortal::CancelOpenOnMainThread() { UnparentOnMainThread(); if (listener_) listener_->FileSelectionCanceled(listener_params_); } void SelectFileDialogLinuxPortal::UnparentOnMainThread() { if (parent_) { parent_.reset(); } } void SelectFileDialogLinuxPortal::DialogInfo::OnCallResponse( dbus::Bus* bus, dbus::Response* response, dbus::ErrorResponse* error_response) { DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence()); if (response) { dbus::MessageReader reader(response); dbus::ObjectPath actual_handle_path; if (!reader.PopObjectPath(&actual_handle_path)) { LOG(ERROR) << "Invalid portal response"; } else { if (response_handle_->object_path() != actual_handle_path) { VLOG(1) << "Re-attaching response handle to " << actual_handle_path.value(); response_handle_->Detach(); response_handle_ = bus->GetObjectProxy(kXdgPortalService, actual_handle_path); ConnectToHandle(); } // Return before the operation is cancelled. return; } } else if (error_response) { std::string error_name = error_response->GetErrorName(); std::string error_message; dbus::MessageReader reader(error_response); reader.PopString(&error_message); LOG(ERROR) << "Portal returned error: " << error_name << ": " << error_message; } else { NOTREACHED(); } // All error paths end up here. CancelOpen(); } void SelectFileDialogLinuxPortal::DialogInfo::OnResponseSignalConnected( const std::string& interface, const std::string& signal, bool connected) { DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence()); if (!connected) { LOG(ERROR) << "Could not connect to Response signal"; CancelOpen(); } } void SelectFileDialogLinuxPortal::DialogInfo::OnResponseSignalEmitted( dbus::Signal* signal) { DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence()); dbus::MessageReader reader(signal); std::vector<std::string> uris; std::string current_filter; if (!CheckResponseCode(&reader) || !ReadResponseResults(&reader, &uris, &current_filter)) { CancelOpen(); return; } std::vector<base::FilePath> paths = ConvertUrisToPaths(uris); if (!paths.empty()) CompleteOpen(std::move(paths), std::move(current_filter)); else CancelOpen(); } bool SelectFileDialogLinuxPortal::DialogInfo::CheckResponseCode( dbus::MessageReader* reader) { std::uint32_t response = 0; if (!reader->PopUint32(&response)) { LOG(ERROR) << "Failed to read response ID"; return false; } else if (response != 0) { return false; } return true; } bool SelectFileDialogLinuxPortal::DialogInfo::ReadResponseResults( dbus::MessageReader* reader, std::vector<std::string>* uris, std::string* current_filter) { dbus::MessageReader results_reader(nullptr); if (!reader->PopArray(&results_reader)) { LOG(ERROR) << "Failed to read file chooser variant"; return false; } while (results_reader.HasMoreData()) { dbus::MessageReader entry_reader(nullptr); std::string key; if (!results_reader.PopDictEntry(&entry_reader) || !entry_reader.PopString(&key)) { LOG(ERROR) << "Failed to read response entry"; return false; } if (key == "uris") { dbus::MessageReader uris_reader(nullptr); if (!entry_reader.PopVariant(&uris_reader) || !uris_reader.PopArrayOfStrings(uris)) { LOG(ERROR) << "Failed to read <uris> response entry value"; return false; } } if (key == "current_filter") { dbus::MessageReader current_filter_reader(nullptr); dbus::MessageReader current_filter_struct_reader(nullptr); if (!entry_reader.PopVariant(&current_filter_reader) || !current_filter_reader.PopStruct(&current_filter_struct_reader) || !current_filter_struct_reader.PopString(current_filter)) { LOG(ERROR) << "Failed to read <current_filter> response entry value"; } } } return true; } std::vector<base::FilePath> SelectFileDialogLinuxPortal::DialogInfo::ConvertUrisToPaths( const std::vector<std::string>& uris) { std::vector<base::FilePath> paths; for (const std::string& uri : uris) { if (!base::StartsWith(uri, kFileUriPrefix, base::CompareCase::SENSITIVE)) { LOG(WARNING) << "Ignoring unknown file chooser URI: " << uri; continue; } base::StringPiece encoded_path(uri); encoded_path.remove_prefix(strlen(kFileUriPrefix)); url::RawCanonOutputT<char16_t> decoded_path; url::DecodeURLEscapeSequences(encoded_path.data(), encoded_path.size(), url::DecodeURLMode::kUTF8OrIsomorphic, &decoded_path); paths.emplace_back(base::UTF16ToUTF8( base::StringPiece16(decoded_path.data(), decoded_path.length()))); } return paths; } bool SelectFileDialogLinuxPortal::is_portal_available_ = false; int SelectFileDialogLinuxPortal::handle_token_counter_ = 0; } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_linux_portal.cc
C++
unknown
28,607
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_LINUX_PORTAL_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_LINUX_PORTAL_H_ #include "base/functional/callback_forward.h" #include "base/memory/raw_ptr.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_refptr.h" #include "base/synchronization/atomic_flag.h" #include "base/task/sequenced_task_runner.h" #include "dbus/bus.h" #include "dbus/message.h" #include "dbus/object_proxy.h" #include "ui/shell_dialogs/select_file_dialog_linux.h" namespace ui { using OnSelectFileExecutedCallback = base::OnceCallback<void(std::vector<base::FilePath> paths, std::string current_filter)>; using OnSelectFileCanceledCallback = base::OnceCallback<void()>; // Implementation of SelectFileDialog that has the XDG file chooser portal show // a platform-dependent file selection dialog. This acts as a modal dialog. class SelectFileDialogLinuxPortal : public SelectFileDialogLinux { public: SelectFileDialogLinuxPortal(Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy); SelectFileDialogLinuxPortal(const SelectFileDialogLinuxPortal& other) = delete; SelectFileDialogLinuxPortal& operator=( const SelectFileDialogLinuxPortal& other) = delete; // Starts running a test to check for the presence of the file chooser portal // on the D-Bus task runner. This should only be called once, preferably // around program start. static void StartAvailabilityTestInBackground(); // Checks if the file chooser portal is available. Blocks if the availability // test from above has not yet completed (which should generally not happen). static bool IsPortalAvailable(); // Destroys the connection to the bus. static void DestroyPortalConnection(); protected: ~SelectFileDialogLinuxPortal() override; // BaseShellDialog implementation: bool IsRunning(gfx::NativeWindow parent_window) const override; // SelectFileDialog implementation. // |params| is user data we pass back via the Listener interface. void SelectFileImpl(Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) override; bool HasMultipleFileTypeChoicesImpl() override; private: // A named set of patterns used as a dialog filter. struct PortalFilter { PortalFilter(); PortalFilter(const PortalFilter& other); PortalFilter(PortalFilter&& other); ~PortalFilter(); PortalFilter& operator=(const PortalFilter& other) = default; PortalFilter& operator=(PortalFilter&& other) = default; std::string name; std::vector<std::string> patterns; }; // A set of PortalFilters, potentially with a default. struct PortalFilterSet { PortalFilterSet(); PortalFilterSet(const PortalFilterSet& other); PortalFilterSet(PortalFilterSet&& other); ~PortalFilterSet(); PortalFilterSet& operator=(const PortalFilterSet& other) = default; PortalFilterSet& operator=(PortalFilterSet&& other) = default; std::vector<PortalFilter> filters; absl::optional<PortalFilter> default_filter; }; // A wrapper over some shared contextual information that needs to be passed // around between SelectFileDialogLinuxPortal and the Portal via D-Bus. // This is ref-counted due to sharing between the 2 sequences: dbus sequence // and main sequence. // Usage: SelectFileDialogLinuxPortal instantiates DialogInfo with the 2 // callbacks, sets the public members and then call SelectFileImplOnDbus(). // DialogInfo notifies the end result via one of the callbacks. class DialogInfo : public base::RefCountedThreadSafe<DialogInfo> { public: DialogInfo(OnSelectFileExecutedCallback selected_callback, OnSelectFileCanceledCallback canceled_callback); // Sets up listeners for the response handle's signals. void SelectFileImplOnBusThread(std::u16string title, base::FilePath default_path, const bool default_path_exists, PortalFilterSet filter_set, base::FilePath::StringType default_extension, std::string parent_handle); Type type; // The task runner the SelectFileImpl method was called on. scoped_refptr<base::SequencedTaskRunner> main_task_runner; private: friend class base::RefCountedThreadSafe<DialogInfo>; ~DialogInfo(); // Should run on D-Bus thread. void ConnectToHandle(); void OnCallResponse(dbus::Bus* bus, dbus::Response* response, dbus::ErrorResponse* error_response); void OnResponseSignalEmitted(dbus::Signal* signal); bool CheckResponseCode(dbus::MessageReader* reader); bool ReadResponseResults(dbus::MessageReader* reader, std::vector<std::string>* uris, std::string* current_filter); void OnResponseSignalConnected(const std::string& interface, const std::string& signal, bool connected); void AppendFiltersOption(dbus::MessageWriter* writer, const std::vector<PortalFilter>& filters); void AppendOptions(dbus::MessageWriter* writer, const std::string& response_handle_token, const base::FilePath& default_path, const bool derfault_path_exists, const PortalFilterSet& filter_set); void AppendFilterStruct(dbus::MessageWriter* writer, const PortalFilter& filter); std::vector<base::FilePath> ConvertUrisToPaths( const std::vector<std::string>& uris); // Completes an open call, notifying the listener with the given paths, and // marks the dialog as closed. void CompleteOpen(std::vector<base::FilePath> paths, std::string current_filter); // Completes an open call, notifying the listener with a cancellation, and // marks the dialog as closed. void CancelOpen(); // These callbacks should run on main thread. // It will point to SelectFileDialogPortal::CompleteOpenOnMainThread. OnSelectFileExecutedCallback selected_callback_; // It will point to SelectFileDialogPortal::CancelOpenOnMainThread. OnSelectFileCanceledCallback canceled_callback_; // The response object handle that the portal will send a signal to upon the // dialog's completion. raw_ptr<dbus::ObjectProxy, DanglingUntriaged> response_handle_ = nullptr; }; // D-Bus configuration and initialization. static void CheckPortalAvailabilityOnBusThread(); static bool IsPortalRunningOnBusThread(dbus::ObjectProxy* dbus_proxy); static bool IsPortalActivatableOnBusThread(dbus::ObjectProxy* dbus_proxy); // Returns a flag, written by the D-Bus thread and read by the UI thread, // indicating whether or not the availability test has completed. static base::AtomicFlag* GetAvailabilityTestCompletionFlag(); PortalFilterSet BuildFilterSet(); void SelectFileImplWithParentHandle( std::u16string title, base::FilePath default_path, PortalFilterSet filter_set, base::FilePath::StringType default_extension, std::string parent_handle); void CompleteOpenOnMainThread(std::vector<base::FilePath> paths, std::string current_filter); void CancelOpenOnMainThread(); // Removes the DialogInfo parent. Must be called on the UI task runner. void UnparentOnMainThread(); // This should be used in the main thread. absl::optional<gfx::AcceleratedWidget> parent_; // The untyped params to pass to the listener, it should be used in the main // thread. raw_ptr<void> listener_params_ = nullptr; // Data shared across main thread and D-Bus thread. scoped_refptr<DialogInfo> info_; // Written by the D-Bus thread and read by the UI thread. static bool is_portal_available_; // Used by the D-Bus thread to generate unique handle tokens. static int handle_token_counter_; std::vector<PortalFilter> filters_; }; } // namespace ui #endif // UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_LINUX_PORTAL_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_linux_portal.h
C++
unknown
8,773
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_MAC_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_MAC_H_ #include <list> #include <memory> #include <vector> #include "base/functional/callback_forward.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "components/remote_cocoa/common/select_file_dialog.mojom.h" #include "mojo/public/cpp/bindings/remote.h" #include "ui/gfx/native_widget_types.h" #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/shell_dialogs_export.h" namespace ui { namespace test { class SelectFileDialogMacTest; } // namespace test // Implementation of SelectFileDialog that shows Cocoa dialogs for choosing a // file or folder. // Exported for unit tests. class SHELL_DIALOGS_EXPORT SelectFileDialogImpl : public ui::SelectFileDialog { public: SelectFileDialogImpl(Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy); SelectFileDialogImpl(const SelectFileDialogImpl&) = delete; SelectFileDialogImpl& operator=(const SelectFileDialogImpl&) = delete; // BaseShellDialog implementation. bool IsRunning(gfx::NativeWindow parent_window) const override; void ListenerDestroyed() override; protected: // SelectFileDialog implementation. // |params| is user data we pass back via the Listener interface. void SelectFileImpl(Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) override; private: friend class test::SelectFileDialogMacTest; // Struct to store data associated with a file dialog while it is showing. struct DialogData { DialogData(gfx::NativeWindow parent_window_, void* params_); DialogData(const DialogData&) = delete; DialogData& operator=(const DialogData&) = delete; ~DialogData(); // The parent window for the panel. Weak, used only for comparisons. gfx::NativeWindow parent_window; // |params| user data associated with this file dialog. raw_ptr<void> params; // Bridge to the Cocoa NSSavePanel. mojo::Remote<remote_cocoa::mojom::SelectFileDialog> select_file_dialog; }; ~SelectFileDialogImpl() override; // Callback made when a panel is closed. void FileWasSelected(DialogData* dialog_data, bool is_multi, bool was_cancelled, const std::vector<base::FilePath>& files, int index); bool HasMultipleFileTypeChoicesImpl() override; // A list containing a DialogData for all active dialogs. std::list<DialogData> dialog_data_list_; bool hasMultipleFileTypeChoices_; // A callback to be called when a selection dialog is closed. For testing // only. base::RepeatingClosure dialog_closed_callback_for_testing_; base::WeakPtrFactory<SelectFileDialogImpl> weak_factory_; }; } // namespace ui #endif // UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_MAC_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_mac.h
C++
unknown
3,388
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/select_file_dialog_mac.h" #include "base/check.h" #include "base/functional/bind.h" #include "base/notreached.h" #include "base/ranges/algorithm.h" #include "base/threading/thread_restrictions.h" #include "components/remote_cocoa/app_shim/select_file_dialog_bridge.h" #include "components/remote_cocoa/browser/window.h" #include "components/remote_cocoa/common/native_widget_ns_window.mojom.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" #include "ui/shell_dialogs/select_file_policy.h" #include "url/gurl.h" using remote_cocoa::mojom::SelectFileDialogType; using remote_cocoa::mojom::SelectFileTypeInfo; using remote_cocoa::mojom::SelectFileTypeInfoPtr; namespace ui { using Type = SelectFileDialog::Type; using FileTypeInfo = SelectFileDialog::FileTypeInfo; SelectFileDialogImpl::SelectFileDialogImpl( Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) : SelectFileDialog(listener, std::move(policy)), weak_factory_(this) {} bool SelectFileDialogImpl::IsRunning(gfx::NativeWindow parent_window) const { for (const auto& dialog_data : dialog_data_list_) { if (dialog_data.parent_window == parent_window) return true; } return false; } void SelectFileDialogImpl::ListenerDestroyed() { listener_ = nullptr; } void SelectFileDialogImpl::FileWasSelected( DialogData* dialog_data, bool is_multi, bool was_cancelled, const std::vector<base::FilePath>& files, int index) { auto it = base::ranges::find(dialog_data_list_, dialog_data, [](const DialogData& d) { return &d; }); DCHECK(it != dialog_data_list_.end()); void* params = dialog_data->params; dialog_data_list_.erase(it); if (dialog_closed_callback_for_testing_) dialog_closed_callback_for_testing_.Run(); if (!listener_) return; if (was_cancelled || files.empty()) { listener_->FileSelectionCanceled(params); } else { if (is_multi) { listener_->MultiFilesSelected(files, params); } else { listener_->FileSelected(files[0], index, params); } } } void SelectFileDialogImpl::SelectFileImpl( Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow gfx_window, void* params, const GURL* caller) { DCHECK(type == SELECT_FOLDER || type == SELECT_UPLOAD_FOLDER || type == SELECT_EXISTING_FOLDER || type == SELECT_OPEN_FILE || type == SELECT_OPEN_MULTI_FILE || type == SELECT_SAVEAS_FILE); hasMultipleFileTypeChoices_ = file_types ? file_types->extensions.size() > 1 : true; // Add a new DialogData to the list. Note that it is safe to pass // |dialog_data| by pointer because it will only be removed from the list when // the callback is made or after the callback has been cancelled by // |weak_factory_|. dialog_data_list_.emplace_back(gfx_window, params); DialogData& dialog_data = dialog_data_list_.back(); // Create a NSSavePanel for it. auto* mojo_window = remote_cocoa::GetWindowMojoInterface(gfx_window); auto receiver = dialog_data.select_file_dialog.BindNewPipeAndPassReceiver(); if (mojo_window) { mojo_window->CreateSelectFileDialog(std::move(receiver)); } else { NSWindow* ns_window = gfx_window.GetNativeNSWindow(); if (!ns_window && owning_widget_) { NSView* view = ((__bridge NSView*)owning_widget_); ns_window = [view window]; } mojo::MakeSelfOwnedReceiver( std::make_unique<remote_cocoa::SelectFileDialogBridge>(ns_window), std::move(receiver)); } // Show the panel. SelectFileDialogType mojo_type = SelectFileDialogType::kFolder; switch (type) { case SELECT_FOLDER: mojo_type = SelectFileDialogType::kFolder; break; case SELECT_UPLOAD_FOLDER: mojo_type = SelectFileDialogType::kUploadFolder; break; case SELECT_EXISTING_FOLDER: mojo_type = SelectFileDialogType::kExistingFolder; break; case SELECT_OPEN_FILE: mojo_type = SelectFileDialogType::kOpenFile; break; case SELECT_OPEN_MULTI_FILE: mojo_type = SelectFileDialogType::kOpenMultiFile; break; case SELECT_SAVEAS_FILE: mojo_type = SelectFileDialogType::kSaveAsFile; break; default: NOTREACHED(); break; } SelectFileTypeInfoPtr mojo_file_types; if (file_types) { mojo_file_types = SelectFileTypeInfo::New(); mojo_file_types->extensions = file_types->extensions; mojo_file_types->extension_description_overrides = file_types->extension_description_overrides; mojo_file_types->include_all_files = file_types->include_all_files; mojo_file_types->keep_extension_visible = file_types->keep_extension_visible; } auto callback = base::BindOnce(&SelectFileDialogImpl::FileWasSelected, weak_factory_.GetWeakPtr(), &dialog_data, type == SELECT_OPEN_MULTI_FILE); dialog_data.select_file_dialog->Show( mojo_type, title, default_path, std::move(mojo_file_types), file_type_index, default_extension, std::move(callback)); } SelectFileDialogImpl::DialogData::DialogData(gfx::NativeWindow parent_window_, void* params_) : parent_window(parent_window_), params(params_) {} SelectFileDialogImpl::DialogData::~DialogData() {} SelectFileDialogImpl::~SelectFileDialogImpl() { // Clear |weak_factory_| beforehand, to ensure that no callbacks will be made // when we cancel the NSSavePanels. weak_factory_.InvalidateWeakPtrs(); // Walk through the open dialogs and issue the cancel callbacks that would // have been made. for (const auto& dialog_data : dialog_data_list_) { if (listener_) listener_->FileSelectionCanceled(dialog_data.params); } // Cancel the NSSavePanels by destroying their bridges. dialog_data_list_.clear(); } bool SelectFileDialogImpl::HasMultipleFileTypeChoicesImpl() { return hasMultipleFileTypeChoices_; } SelectFileDialog* CreateSelectFileDialog( SelectFileDialog::Listener* listener, std::unique_ptr<SelectFilePolicy> policy) { return new SelectFileDialogImpl(listener, std::move(policy)); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_mac.mm
Objective-C++
unknown
6,504
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "ui/shell_dialogs/select_file_dialog_mac.h" #import <UniformTypeIdentifiers/UniformTypeIdentifiers.h> #include "base/files/file_util.h" #include "base/functional/callback_forward.h" #import "base/mac/foundation_util.h" #include "base/mac/mac_util.h" #include "base/memory/raw_ptr.h" #include "base/memory/ref_counted.h" #include "base/ranges/algorithm.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/test/task_environment.h" #include "components/remote_cocoa/app_shim/select_file_dialog_bridge.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest_mac.h" #include "ui/shell_dialogs/select_file_policy.h" #define EXPECT_EQ_BOOL(a, b) \ EXPECT_EQ(static_cast<bool>(a), static_cast<bool>(b)) namespace { const int kFileTypePopupTag = 1234; // Returns a vector containing extension descriptions for a given popup. std::vector<std::u16string> GetExtensionDescriptionList(NSPopUpButton* popup) { std::vector<std::u16string> extension_descriptions; for (NSString* description in popup.itemTitles) { extension_descriptions.push_back(base::SysNSStringToUTF16(description)); } return extension_descriptions; } // Returns the NSPopupButton associated with the given `panel`. NSPopUpButton* GetPopup(NSSavePanel* panel) { return [panel.accessoryView viewWithTag:kFileTypePopupTag]; } } // namespace namespace ui::test { // Helper test base to initialize SelectFileDialogImpl. class SelectFileDialogMacTest : public ::testing::Test, public SelectFileDialog::Listener { public: SelectFileDialogMacTest() : dialog_(new SelectFileDialogImpl(this, nullptr)) {} SelectFileDialogMacTest(const SelectFileDialogMacTest&) = delete; SelectFileDialogMacTest& operator=(const SelectFileDialogMacTest&) = delete; // Overridden from SelectFileDialog::Listener. void FileSelected(const base::FilePath& path, int index, void* params) override {} protected: base::test::TaskEnvironment task_environment_ = base::test::TaskEnvironment( base::test::TaskEnvironment::MainThreadType::UI); struct FileDialogArguments { SelectFileDialog::Type type = SelectFileDialog::SELECT_SAVEAS_FILE; std::u16string title; base::FilePath default_path; raw_ptr<SelectFileDialog::FileTypeInfo> file_types = nullptr; int file_type_index = 0; base::FilePath::StringType default_extension; raw_ptr<void> params = nullptr; }; // Helper method to create a dialog with the given `args`. Returns the created // NSSavePanel. NSSavePanel* SelectFileWithParams(FileDialogArguments args) { base::scoped_nsobject<NSWindow> parent_window([[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 100, 100) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]); [parent_window setReleasedWhenClosed:NO]; parent_windows_.push_back(parent_window); dialog_->SelectFile(args.type, args.title, args.default_path, args.file_types, args.file_type_index, args.default_extension, parent_window.get(), args.params); // At this point, the Mojo IPC to show the dialog is queued up. Spin the // message loop to get the Mojo IPC to happen. base::RunLoop().RunUntilIdle(); // Now there is an actual panel that exists. NSSavePanel* panel = remote_cocoa::SelectFileDialogBridge:: GetLastCreatedNativePanelForTesting(); DCHECK(panel); // Pump the message loop until the panel reports that it's visible. base::RunLoop run_loop; base::RepeatingClosure quit_closure = run_loop.QuitClosure(); id<NSObject> observer = [NSNotificationCenter.defaultCenter addObserverForName:NSWindowDidUpdateNotification object:panel queue:nil usingBlock:^(NSNotification* note) { if (panel.visible) { quit_closure.Run(); } }]; run_loop.Run(); [NSNotificationCenter.defaultCenter removeObserver:observer]; return panel; } // Returns the number of panels currently active. size_t GetActivePanelCount() const { return dialog_->dialog_data_list_.size(); } // Sets a callback to be called when a dialog is closed. void SetDialogClosedCallback(base::RepeatingClosure callback) { dialog_->dialog_closed_callback_for_testing_ = callback; } void ResetDialog() { dialog_ = new SelectFileDialogImpl(this, nullptr); // Spin the run loop to get any pending Mojo IPC sent. base::RunLoop().RunUntilIdle(); } private: scoped_refptr<SelectFileDialogImpl> dialog_; std::vector<base::scoped_nsobject<NSWindow>> parent_windows_; }; class SelectFileDialogMacOpenAndSaveTest : public SelectFileDialogMacTest, public ::testing::WithParamInterface<SelectFileDialog::Type> {}; INSTANTIATE_TEST_SUITE_P(All, SelectFileDialogMacOpenAndSaveTest, ::testing::Values(SelectFileDialog::SELECT_SAVEAS_FILE, SelectFileDialog::SELECT_OPEN_FILE)); // Verify that the extension popup has the correct description and changing the // popup item changes the allowed file types. TEST_F(SelectFileDialogMacTest, ExtensionPopup) { SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions = {{"html", "htm"}, {"jpeg", "jpg"}}; file_type_info.extension_description_overrides = {u"Webpage", u"Image"}; file_type_info.include_all_files = false; FileDialogArguments args; args.file_types = &file_type_info; NSSavePanel* panel = SelectFileWithParams(args); NSPopUpButton* popup = GetPopup(panel); ASSERT_TRUE(popup); // Check that the dropdown list created has the correct description. const std::vector<std::u16string> extension_descriptions = GetExtensionDescriptionList(popup); EXPECT_EQ(file_type_info.extension_description_overrides, extension_descriptions); // Ensure other file types are not allowed. EXPECT_FALSE(panel.allowsOtherFileTypes); // Check that the first item was selected, since a file_type_index of 0 was // passed and no default extension was provided. EXPECT_EQ(0, popup.indexOfSelectedItem); if (@available(macOS 11, *)) { ASSERT_EQ(1lu, panel.allowedContentTypes.count); EXPECT_NSEQ(UTTypeHTML, panel.allowedContentTypes[0]); } else { EXPECT_TRUE([panel.allowedFileTypes containsObject:@"htm"]); EXPECT_TRUE([panel.allowedFileTypes containsObject:@"html"]); // Extensions should appear in order of input. EXPECT_LT([panel.allowedFileTypes indexOfObject:@"html"], [panel.allowedFileTypes indexOfObject:@"htm"]); EXPECT_FALSE([panel.allowedFileTypes containsObject:@"jpg"]); } // Select the second item. [popup.menu performActionForItemAtIndex:1]; EXPECT_EQ(1, popup.indexOfSelectedItem); if (@available(macOS 11, *)) { ASSERT_EQ(1lu, panel.allowedContentTypes.count); EXPECT_NSEQ(UTTypeJPEG, panel.allowedContentTypes[0]); } else { EXPECT_TRUE([panel.allowedFileTypes containsObject:@"jpg"]); EXPECT_TRUE([panel.allowedFileTypes containsObject:@"jpeg"]); // Extensions should appear in order of input. EXPECT_LT([panel.allowedFileTypes indexOfObject:@"jpeg"], [panel.allowedFileTypes indexOfObject:@"jpg"]); EXPECT_FALSE([panel.allowedFileTypes containsObject:@"html"]); } } // Verify file_type_info.include_all_files argument is respected. TEST_P(SelectFileDialogMacOpenAndSaveTest, IncludeAllFiles) { SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions = {{"html", "htm"}, {"jpeg", "jpg"}}; file_type_info.extension_description_overrides = {u"Webpage", u"Image"}; file_type_info.include_all_files = true; FileDialogArguments args; args.type = GetParam(); args.file_types = &file_type_info; NSSavePanel* panel = SelectFileWithParams(args); NSPopUpButton* popup = GetPopup(panel); ASSERT_TRUE(popup); // Ensure other file types are allowed. EXPECT_TRUE(panel.allowsOtherFileTypes); // Check that the dropdown list created has the correct description. const std::vector<std::u16string> extension_descriptions = GetExtensionDescriptionList(popup); // Save dialogs don't have "all files". if (args.type == SelectFileDialog::SELECT_SAVEAS_FILE) { ASSERT_EQ(2lu, extension_descriptions.size()); EXPECT_EQ(u"Webpage", extension_descriptions[0]); EXPECT_EQ(u"Image", extension_descriptions[1]); } else { ASSERT_EQ(3lu, extension_descriptions.size()); EXPECT_EQ(u"Webpage", extension_descriptions[0]); EXPECT_EQ(u"Image", extension_descriptions[1]); EXPECT_EQ(u"All Files", extension_descriptions[2]); // Note that no further testing on the popup can be done. Open dialogs are // out-of-process starting in macOS 10.15, so once it's been run and closed, // the accessory view controls no longer work. } } // Verify that file_type_index and default_extension arguments cause the // appropriate extension group to be initially selected. TEST_F(SelectFileDialogMacTest, InitialSelection) { SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions = {{"html", "htm"}, {"jpeg", "jpg"}}; file_type_info.extension_description_overrides = {u"Webpage", u"Image"}; FileDialogArguments args; args.file_types = &file_type_info; args.file_type_index = 2; args.default_extension = "jpg"; NSSavePanel* panel = SelectFileWithParams(args); NSPopUpButton* popup = GetPopup(panel); ASSERT_TRUE(popup); // Verify that the `file_type_index` causes the second item to be initially // selected. EXPECT_EQ(1, popup.indexOfSelectedItem); if (@available(macOS 11, *)) { ASSERT_EQ(1lu, panel.allowedContentTypes.count); EXPECT_NSEQ(UTTypeJPEG, panel.allowedContentTypes[0]); } else { EXPECT_TRUE([panel.allowedFileTypes containsObject:@"jpg"]); EXPECT_TRUE([panel.allowedFileTypes containsObject:@"jpeg"]); EXPECT_FALSE([panel.allowedFileTypes containsObject:@"html"]); } ResetDialog(); args.file_type_index = 0; args.default_extension = "pdf"; panel = SelectFileWithParams(args); popup = GetPopup(panel); ASSERT_TRUE(popup); // Verify that the first item was selected, since the default extension passed // was not present in the extension list. EXPECT_EQ(0, popup.indexOfSelectedItem); if (@available(macOS 11, *)) { ASSERT_EQ(1lu, panel.allowedContentTypes.count); EXPECT_NSEQ(UTTypeHTML, panel.allowedContentTypes[0]); } else { EXPECT_TRUE([panel.allowedFileTypes containsObject:@"html"]); EXPECT_TRUE([panel.allowedFileTypes containsObject:@"htm"]); EXPECT_FALSE([panel.allowedFileTypes containsObject:@"pdf"]); EXPECT_FALSE([panel.allowedFileTypes containsObject:@"jpeg"]); } ResetDialog(); args.file_type_index = 0; args.default_extension = "jpg"; panel = SelectFileWithParams(args); popup = GetPopup(panel); ASSERT_TRUE(popup); // Verify that the extension group corresponding to the default extension is // initially selected. EXPECT_EQ(1, popup.indexOfSelectedItem); if (@available(macOS 11, *)) { ASSERT_EQ(1lu, panel.allowedContentTypes.count); EXPECT_NSEQ(UTTypeJPEG, panel.allowedContentTypes[0]); } else { EXPECT_TRUE([panel.allowedFileTypes containsObject:@"jpg"]); EXPECT_TRUE([panel.allowedFileTypes containsObject:@"jpeg"]); EXPECT_FALSE([panel.allowedFileTypes containsObject:@"html"]); } } // Verify that an appropriate extension description is shown even if an empty // extension description is passed for a given extension group. TEST_F(SelectFileDialogMacTest, EmptyDescription) { SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions = {{"pdf"}, {"jpg"}, {"qqq"}}; file_type_info.extension_description_overrides = {u"", u"Image", u""}; FileDialogArguments args; args.file_types = &file_type_info; NSSavePanel* panel = SelectFileWithParams(args); NSPopUpButton* popup = GetPopup(panel); ASSERT_TRUE(popup); const std::vector<std::u16string> extension_descriptions = GetExtensionDescriptionList(popup); ASSERT_EQ(3lu, extension_descriptions.size()); // Verify that the correct system description is produced for known file types // like pdf if no extension description is provided by the client. Modern // versions of macOS have settled on "PDF document" as the official // description. EXPECT_EQ(u"PDF document", extension_descriptions[0]); // Verify that if an override description is provided, it is used. EXPECT_EQ(u"Image", extension_descriptions[1]); // Verify the description for unknown file types if no extension description // is provided by the client. EXPECT_EQ(u"QQQ File (.qqq)", extension_descriptions[2]); } // Verify that passing an empty extension list in file_type_info causes no // extension dropdown to display. TEST_P(SelectFileDialogMacOpenAndSaveTest, EmptyExtension) { SelectFileDialog::FileTypeInfo file_type_info; FileDialogArguments args; args.type = GetParam(); args.file_types = &file_type_info; NSSavePanel* panel = SelectFileWithParams(args); EXPECT_FALSE(panel.accessoryView); // Ensure other file types are allowed. EXPECT_TRUE(panel.allowsOtherFileTypes); } // Verify that passing a null file_types value causes no extension dropdown to // display. TEST_F(SelectFileDialogMacTest, FileTypesNull) { NSSavePanel* panel = SelectFileWithParams({}); EXPECT_TRUE(panel.allowsOtherFileTypes); EXPECT_FALSE(panel.accessoryView); // Ensure other file types are allowed. EXPECT_TRUE(panel.allowsOtherFileTypes); } // Verify that appropriate properties are set on the NSSavePanel for different // dialog types. TEST_F(SelectFileDialogMacTest, SelectionType) { SelectFileDialog::FileTypeInfo file_type_info; FileDialogArguments args; args.file_types = &file_type_info; enum { HAS_ACCESSORY_VIEW = 1, PICK_FILES = 2, PICK_DIRS = 4, CREATE_DIRS = 8, MULTIPLE_SELECTION = 16, }; struct SelectionTypeTestCase { SelectFileDialog::Type type; unsigned options; std::string prompt; } test_cases[] = { {SelectFileDialog::SELECT_FOLDER, PICK_DIRS | CREATE_DIRS, "Select"}, {SelectFileDialog::SELECT_UPLOAD_FOLDER, PICK_DIRS, "Upload"}, {SelectFileDialog::SELECT_EXISTING_FOLDER, PICK_DIRS, "Select"}, {SelectFileDialog::SELECT_SAVEAS_FILE, CREATE_DIRS, "Save"}, {SelectFileDialog::SELECT_OPEN_FILE, PICK_FILES, "Open"}, {SelectFileDialog::SELECT_OPEN_MULTI_FILE, PICK_FILES | MULTIPLE_SELECTION, "Open"}, }; for (size_t i = 0; i < std::size(test_cases); i++) { SCOPED_TRACE( base::StringPrintf("i=%lu file_dialog_type=%d", i, test_cases[i].type)); args.type = test_cases[i].type; ResetDialog(); NSSavePanel* panel = SelectFileWithParams(args); EXPECT_EQ_BOOL(test_cases[i].options & HAS_ACCESSORY_VIEW, panel.accessoryView); EXPECT_EQ_BOOL(test_cases[i].options & CREATE_DIRS, panel.canCreateDirectories); EXPECT_EQ(test_cases[i].prompt, base::SysNSStringToUTF8([panel prompt])); if (args.type != SelectFileDialog::SELECT_SAVEAS_FILE) { NSOpenPanel* open_panel = base::mac::ObjCCast<NSOpenPanel>(panel); // Verify that for types other than save file dialogs, an NSOpenPanel is // created. ASSERT_TRUE(open_panel); EXPECT_EQ_BOOL(test_cases[i].options & PICK_FILES, open_panel.canChooseFiles); EXPECT_EQ_BOOL(test_cases[i].options & PICK_DIRS, open_panel.canChooseDirectories); EXPECT_EQ_BOOL(test_cases[i].options & MULTIPLE_SELECTION, open_panel.allowsMultipleSelection); } } } // Verify that the correct message is set on the NSSavePanel. TEST_F(SelectFileDialogMacTest, DialogMessage) { const std::string test_title = "test title"; FileDialogArguments args; args.title = base::ASCIIToUTF16(test_title); NSSavePanel* panel = SelectFileWithParams(args); EXPECT_EQ(test_title, base::SysNSStringToUTF8(panel.message)); } // Verify that multiple file dialogs are correctly handled. TEST_F(SelectFileDialogMacTest, MultipleDialogs) { FileDialogArguments args; NSSavePanel* panel1 = SelectFileWithParams(args); NSSavePanel* panel2 = SelectFileWithParams(args); ASSERT_EQ(2lu, GetActivePanelCount()); // Verify closing the panel decreases the panel count. base::RunLoop run_loop1; SetDialogClosedCallback(run_loop1.QuitClosure()); [panel1 cancel:nil]; run_loop1.Run(); ASSERT_EQ(1lu, GetActivePanelCount()); // In 10.15, file picker dialogs are remote, and the restriction of apps not // being allowed to OK their own file requests has been extended from just // sandboxed apps to all apps. If we can test OK-ing our own dialogs, sure, // but if not, at least try to close them all. base::RunLoop run_loop2; SetDialogClosedCallback(run_loop2.QuitClosure()); if (base::mac::IsAtMostOS10_14()) { [panel2 ok:nil]; } else { [panel2 cancel:nil]; } run_loop2.Run(); EXPECT_EQ(0lu, GetActivePanelCount()); SetDialogClosedCallback({}); } // Verify that the default_path argument is respected. TEST_F(SelectFileDialogMacTest, DefaultPath) { FileDialogArguments args; args.default_path = base::GetHomeDir().AppendASCII("test.txt"); NSSavePanel* panel = SelectFileWithParams(args); panel.extensionHidden = NO; EXPECT_EQ(args.default_path.DirName(), base::mac::NSStringToFilePath(panel.directoryURL.path)); EXPECT_EQ(args.default_path.BaseName(), base::mac::NSStringToFilePath(panel.nameFieldStringValue)); } // Verify that the file dialog does not hide extension for filenames with // multiple extensions. TEST_F(SelectFileDialogMacTest, MultipleExtension) { const std::string fake_path_normal = "/fake_directory/filename.tar"; const std::string fake_path_multiple = "/fake_directory/filename.tar.gz"; const std::string fake_path_long = "/fake_directory/example.com-123.json"; FileDialogArguments args; args.default_path = base::FilePath(FILE_PATH_LITERAL(fake_path_normal)); NSSavePanel* panel = SelectFileWithParams(args); EXPECT_TRUE(panel.canSelectHiddenExtension); EXPECT_TRUE(panel.extensionHidden); ResetDialog(); args.default_path = base::FilePath(FILE_PATH_LITERAL(fake_path_multiple)); panel = SelectFileWithParams(args); EXPECT_FALSE(panel.canSelectHiddenExtension); EXPECT_FALSE(panel.extensionHidden); ResetDialog(); args.default_path = base::FilePath(FILE_PATH_LITERAL(fake_path_long)); panel = SelectFileWithParams(args); EXPECT_FALSE(panel.canSelectHiddenExtension); EXPECT_FALSE(panel.extensionHidden); } // Verify that the file dialog does not hide extension when the // `keep_extension_visible` flag is set to true. TEST_F(SelectFileDialogMacTest, KeepExtensionVisible) { SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions = {{"html", "htm"}, {"jpeg", "jpg"}}; file_type_info.keep_extension_visible = true; FileDialogArguments args; args.file_types = &file_type_info; NSSavePanel* panel = SelectFileWithParams(args); EXPECT_FALSE(panel.canSelectHiddenExtension); EXPECT_FALSE(panel.extensionHidden); } // TODO(crbug.com/1427906): This has been flaky. TEST_F(SelectFileDialogMacTest, DISABLED_DontCrashWithBogusExtension) { SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions = {{"bogus type", "j.pg"}}; FileDialogArguments args; args.file_types = &file_type_info; NSSavePanel* panel = SelectFileWithParams(args); // If execution gets this far, there was no crash. EXPECT_TRUE(panel); } // Test to ensure lifetime is sound if a reference to // the panel outlives the delegate. TEST_F(SelectFileDialogMacTest, Lifetime) { base::scoped_nsobject<NSSavePanel> panel; @autoreleasepool { FileDialogArguments args; // Set a type (Save dialogs do not have a delegate). args.type = SelectFileDialog::SELECT_OPEN_MULTI_FILE; panel.reset([SelectFileWithParams(args) retain]); EXPECT_TRUE([panel isVisible]); EXPECT_NE(nil, [panel delegate]); // Newer versions of AppKit (>= 10.13) appear to clear out weak delegate // pointers when dealloc is called on the delegate. Put a ref into the // autorelease pool to simulate what happens on older versions. [[[panel delegate] retain] autorelease]; // This will cause the `SelectFileDialogImpl` destructor to be called, and // it will tear down the `SelectFileDialogBridge` via a Mojo IPC. ResetDialog(); // The `SelectFileDialogBridge` destructor invokes `[panel cancel]`. That // should close the panel, and run the completion handler. EXPECT_EQ(nil, [panel delegate]); EXPECT_FALSE([panel isVisible]); } EXPECT_EQ(nil, [panel delegate]); } } // namespace ui::test
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_mac_unittest.mm
Objective-C++
unknown
21,330
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <memory> #define private public #include "select_file_dialog_factory.h" #include "select_file_policy.h" #include "ui/shell_dialogs/select_file_dialog.h" #undef private #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" TEST(ShellDialogs, ShortenFileNameIfNeeded) { struct ShortenFileNameTestCase { base::FilePath::StringType input; base::FilePath::StringType expected; } test_cases[] = { // Paths with short paths/file names don't get shortened. {FILE_PATH_LITERAL("folder1111/folder2222/file1.html"), FILE_PATH_LITERAL("folder1111/folder2222/file1.html")}, // Path with long filename gets shortened to 255 chars {FILE_PATH_LITERAL("folder1111/" "abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvw" "xyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnop" "qrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghi" "jklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234ab" "cdefghijklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvwxy" "z1234.html"), FILE_PATH_LITERAL("folder1111/" "abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvw" "xyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnop" "qrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghi" "jklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234ab" "cdefghijklmnopqrstuvwxyz1234abcdefghij.html")}, // Long path but short filename is not truncated, handled by system open // file dialog. {FILE_PATH_LITERAL( "folder1111/folder2222/folder3333/folder4444/folder5555/folder6666/" "folder7777/folder8888/folder9999/folder0000/folder1111/folder2222/" "folder3333/folder4444/folder5555/folder6666/folder7777/folder8888/" "folder9999/folder0000/folder1111/folder2222/folder3333/folder4444/" "folder5555/folder6666/folder7777/folder8888/folder9999/folder0000/" "file1.pdf"), FILE_PATH_LITERAL( "folder1111/folder2222/folder3333/folder4444/folder5555/folder6666/" "folder7777/folder8888/folder9999/folder0000/folder1111/folder2222/" "folder3333/folder4444/folder5555/folder6666/folder7777/folder8888/" "folder9999/folder0000/folder1111/folder2222/folder3333/folder4444/" "folder5555/folder6666/folder7777/folder8888/folder9999/folder0000/" "file1.pdf")}, // Long extension with total file name length < 255 is not truncated. {FILE_PATH_LITERAL("folder1111/folder2222/" "file1." "abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvw" "xyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnop" "qrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghi" "jklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234"), FILE_PATH_LITERAL("folder1111/folder2222/" "file1." "abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvw" "xyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnop" "qrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghi" "jklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvwxyz123" "4")}, // Long extension, medium length file name is truncated so that total // file name length = 255 {FILE_PATH_LITERAL("folder1111/folder2222/" "file1234567890123456789012345678901234567890123456789" "0." "abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvw" "xyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnop" "qrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghi" "jklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234"), FILE_PATH_LITERAL("folder1111/folder2222/" "file1234567890123456789012345678901234567890123456789" "0." "abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvw" "xyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnop" "qrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghi" "jklmnopqrstuvwxyz1234abcdefghijklmnopqrst")}, // Long extension and long file name -> extension truncated to 13 chars // and file name truncated to 255-13. {FILE_PATH_LITERAL("folder1111/folder2222/" "abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvw" "xyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnop" "qrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghi" "jklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234ab" "cdefghijklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvwxy" "z1234." "abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvw" "xyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnop" "qrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghi" "jklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234"), FILE_PATH_LITERAL("folder1111/folder2222/" "abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvw" "xyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghijklmnop" "qrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234abcdefghi" "jklmnopqrstuvwxyz1234abcdefghijklmnopqrstuvwxyz1234ab" "cdefghijklmnopqrstuvwxyz1234ab.abcdefghijkl")}}; for (size_t i = 0; i < std::size(test_cases); ++i) { base::FilePath input = base::FilePath(test_cases[i].input).NormalizePathSeparators(); base::FilePath output = base::FilePath(test_cases[i].expected).NormalizePathSeparators(); EXPECT_EQ(output.value(), ui::SelectFileDialog::GetShortenedFilePath(input).value()); EXPECT_LE(ui::SelectFileDialog::GetShortenedFilePath(input) .BaseName() .value() .length(), 255u); } } namespace ui { class ConcreteListener : public ui::SelectFileDialog::Listener { public: void FileSelected(const base::FilePath& path, int index, void* params) override {} void FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file, int index, void* params) override {} void MultiFilesSelected(const std::vector<base::FilePath>& files, void* params) override {} void MultiFilesSelectedWithExtraInfo( const std::vector<ui::SelectedFileInfo>& files, void* params) override {} void FileSelectionCanceled(void* params) override {} }; class MockSelectFileDialogFactory : public ui::SelectFileDialogFactory { public: bool isCefFactory = false; bool IsCefFactory() const override { return isCefFactory; } MOCK_METHOD(SelectFileDialog*, Create, (ui::SelectFileDialog::Listener * listener, std::unique_ptr<ui::SelectFilePolicy> policy), (override)); }; TEST(ShellDialogs, CreateTest1) { MockSelectFileDialogFactory* factory = new MockSelectFileDialogFactory(); std::unique_ptr<ConcreteListener> listener = std::make_unique<ConcreteListener>(); std::unique_ptr<ui::SelectFilePolicy> policy; bool run_from_cef = false; SelectFileDialog::SetFactory(factory); EXPECT_CALL(*factory, Create(::testing::_, ::testing::_)).Times(1); SelectFileDialog::Create(listener.get(), std::move(policy), run_from_cef); } TEST(ShellDialogs, CreateTest2) { MockSelectFileDialogFactory* factory = new MockSelectFileDialogFactory(); std::unique_ptr<ConcreteListener> listener = std::make_unique<ConcreteListener>(); std::unique_ptr<ui::SelectFilePolicy> policy; bool run_from_cef = true; SelectFileDialog::SetFactory(factory); EXPECT_CALL(*factory, Create(::testing::_, ::testing::_)).Times(1); SelectFileDialog::Create(listener.get(), std::move(policy), run_from_cef); } TEST(ShellDialogs, CreateTest3) { MockSelectFileDialogFactory* factory = new MockSelectFileDialogFactory(); std::unique_ptr<ConcreteListener> listener = std::make_unique<ConcreteListener>(); std::unique_ptr<ui::SelectFilePolicy> policy; bool run_from_cef = false; factory->isCefFactory = true; SelectFileDialog::SetFactory(factory); EXPECT_CALL(*factory, Create(::testing::_, ::testing::_)).Times(1); SelectFileDialog::Create(listener.get(), std::move(policy), run_from_cef); } TEST(ShellDialogs, CreateTest4) { MockSelectFileDialogFactory* factory = new MockSelectFileDialogFactory(); std::unique_ptr<ConcreteListener> listener = std::make_unique<ConcreteListener>(); std::unique_ptr<ui::SelectFilePolicy> policy; bool run_from_cef = true; factory->isCefFactory = true; SelectFileDialog::SetFactory(factory); EXPECT_CALL(*factory, Create(::testing::_, ::testing::_)).Times(0); SelectFileDialog::Create(listener.get(), std::move(policy), run_from_cef); } TEST(ShellDialogs, CreateTest5) { MockSelectFileDialogFactory* factory = new MockSelectFileDialogFactory(); std::unique_ptr<ConcreteListener> listener = std::make_unique<ConcreteListener>(); std::unique_ptr<ui::SelectFilePolicy> policy; bool run_from_cef = true; SelectFileDialog::SetFactory(factory); EXPECT_CALL(*factory, Create(::testing::_, ::testing::_)).Times(1); SelectFileDialog::Create(listener.get(), std::move(policy), run_from_cef); } TEST(ShellDialogs, CreateTest6) { ui::SelectFileDialogFactory* factory_ = nullptr; std::unique_ptr<ConcreteListener> listener = std::make_unique<ConcreteListener>(); std::unique_ptr<ui::SelectFilePolicy> policy; bool run_from_cef = false; SelectFileDialog::SetFactory(factory_); SelectFileDialog::Create(listener.get(), std::move(policy), run_from_cef); EXPECT_FALSE(factory_); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_unittest.cc
C++
unknown
10,604
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/select_file_dialog_win.h" #include <algorithm> #include <memory> #include "base/check_op.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/functional/bind.h" #include "base/i18n/case_conversion.h" #include "base/notreached.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" #include "base/win/registry.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/aura/window_tree_host.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/native_widget_types.h" #include "ui/shell_dialogs/base_shell_dialog_win.h" #include "ui/shell_dialogs/execute_select_file_win.h" #include "ui/shell_dialogs/select_file_policy.h" #include "ui/shell_dialogs/select_file_utils_win.h" #include "ui/strings/grit/ui_strings.h" #include "url/gurl.h" namespace ui { namespace { // Get the file type description from the registry. This will be "Text Document" // for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't // have an entry for the file type, we return false, true if the description was // found. 'file_ext' must be in form ".txt". bool GetRegistryDescriptionFromExtension(const std::u16string& file_ext, std::u16string* reg_description) { DCHECK(reg_description); base::win::RegKey reg_ext(HKEY_CLASSES_ROOT, base::as_wcstr(file_ext), KEY_READ); std::wstring reg_app; if (reg_ext.ReadValue(nullptr, &reg_app) == ERROR_SUCCESS && !reg_app.empty()) { base::win::RegKey reg_link(HKEY_CLASSES_ROOT, reg_app.c_str(), KEY_READ); std::wstring description; if (reg_link.ReadValue(nullptr, &description) == ERROR_SUCCESS) { *reg_description = base::WideToUTF16(description); return true; } } return false; } // Set up a filter for a Save/Open dialog, |ext_desc| as the text descriptions // of the |file_ext| types (optional), and (optionally) the default 'All Files' // view. The purpose of the filter is to show only files of a particular type in // a Windows Save/Open dialog box. The resulting filter is returned. The filter // created here are: // 1. only files that have 'file_ext' as their extension // 2. all files (only added if 'include_all_files' is true) // If a description is not provided for a file extension, it will be retrieved // from the registry. If the file extension does not exist in the registry, a // default description will be created (e.g. "qqq" yields "QQQ File"). std::vector<FileFilterSpec> FormatFilterForExtensions( const std::vector<std::u16string>& file_ext, const std::vector<std::u16string>& ext_desc, bool include_all_files, bool keep_extension_visible) { const std::u16string all_ext = u"*.*"; const std::u16string all_desc = l10n_util::GetStringUTF16(IDS_APP_SAVEAS_ALL_FILES); DCHECK(file_ext.size() >= ext_desc.size()); if (file_ext.empty()) include_all_files = true; std::vector<FileFilterSpec> result; result.reserve(file_ext.size() + 1); for (size_t i = 0; i < file_ext.size(); ++i) { std::u16string ext = RemoveEnvVarFromFileName<char16_t>(file_ext[i], std::u16string(u"%")); std::u16string desc; if (i < ext_desc.size()) desc = ext_desc[i]; if (ext.empty()) { // Force something reasonable to appear in the dialog box if there is no // extension provided. include_all_files = true; continue; } if (desc.empty()) { DCHECK(ext.find(u'.') != std::u16string::npos); std::u16string first_extension = ext.substr(ext.find(u'.')); size_t first_separator_index = first_extension.find(u';'); if (first_separator_index != std::u16string::npos) first_extension = first_extension.substr(0, first_separator_index); // Find the extension name without the preceeding '.' character. std::u16string ext_name = first_extension; size_t ext_index = ext_name.find_first_not_of(u'.'); if (ext_index != std::u16string::npos) ext_name = ext_name.substr(ext_index); if (!GetRegistryDescriptionFromExtension(first_extension, &desc)) { // The extension doesn't exist in the registry. Create a description // based on the unknown extension type (i.e. if the extension is .qqq, // then we create a description "QQQ File"). desc = l10n_util::GetStringFUTF16(IDS_APP_SAVEAS_EXTENSION_FORMAT, base::i18n::ToUpper(ext_name)); include_all_files = true; } if (desc.empty()) desc = u"*." + ext_name; } else if (keep_extension_visible) { // Having '*' in the description could cause the windows file dialog to // not include the file extension in the file dialog. So strip out any '*' // characters if `keep_extension_visible` is set. base::ReplaceChars(desc, u"*", base::StringPiece16(), &desc); } result.push_back({desc, ext}); } if (include_all_files) result.push_back({all_desc, all_ext}); return result; } // Forwards the result from a select file operation to the SelectFileDialog // object on the UI thread. void OnSelectFileExecutedOnDialogTaskRunner( scoped_refptr<base::SequencedTaskRunner> ui_task_runner, OnSelectFileExecutedCallback on_select_file_executed_callback, const std::vector<base::FilePath>& paths, int index) { ui_task_runner->PostTask( FROM_HERE, base::BindOnce(std::move(on_select_file_executed_callback), paths, index)); } // Implementation of SelectFileDialog that shows a Windows common dialog for // choosing a file or folder. class SelectFileDialogImpl : public ui::SelectFileDialog, public ui::BaseShellDialogImpl { public: SelectFileDialogImpl( Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy, const ExecuteSelectFileCallback& execute_select_file_callback); SelectFileDialogImpl(const SelectFileDialogImpl&) = delete; SelectFileDialogImpl& operator=(const SelectFileDialogImpl&) = delete; // BaseShellDialog implementation: bool IsRunning(gfx::NativeWindow owning_window) const override; void ListenerDestroyed() override; protected: // SelectFileDialog implementation: void SelectFileImpl(Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) override; private: ~SelectFileDialogImpl() override; struct SelectFolderDialogOptions { const wchar_t* default_path; bool is_upload; }; // Returns the result of the select file operation to the listener. void OnSelectFileExecuted(Type type, std::unique_ptr<RunState> run_state, void* params, const std::vector<base::FilePath>& paths, int index); bool HasMultipleFileTypeChoicesImpl() override; // Returns the filter to be used while displaying the open/save file dialog. // This is computed from the extensions for the file types being opened. // |file_types| can be NULL in which case the returned filter will be empty. static std::vector<FileFilterSpec> GetFilterForFileTypes( const FileTypeInfo* file_types); bool has_multiple_file_type_choices_; ExecuteSelectFileCallback execute_select_file_callback_; }; SelectFileDialogImpl::SelectFileDialogImpl( Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy, const ExecuteSelectFileCallback& execute_select_file_callback) : SelectFileDialog(listener, std::move(policy)), BaseShellDialogImpl(), has_multiple_file_type_choices_(false), execute_select_file_callback_(execute_select_file_callback) {} SelectFileDialogImpl::~SelectFileDialogImpl() = default; // Invokes the |execute_select_file_callback| and returns the result to void DoSelectFileOnDialogTaskRunner( const ExecuteSelectFileCallback& execute_select_file_callback, SelectFileDialog::Type type, const std::u16string& title, const base::FilePath& default_path, const std::vector<ui::FileFilterSpec>& filter, int file_type_index, const std::wstring& default_extension, HWND owner, scoped_refptr<base::SequencedTaskRunner> ui_task_runner, OnSelectFileExecutedCallback on_select_file_executed_callback) { execute_select_file_callback.Run( type, title, default_path, filter, file_type_index, default_extension, owner, base::BindOnce(&OnSelectFileExecutedOnDialogTaskRunner, std::move(ui_task_runner), std::move(on_select_file_executed_callback))); } void SelectFileDialogImpl::SelectFileImpl( Type type, const std::u16string& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params, const GURL* caller) { has_multiple_file_type_choices_ = file_types ? file_types->extensions.size() > 1 : true; std::vector<FileFilterSpec> filter = GetFilterForFileTypes(file_types); HWND owner = owning_window && owning_window->GetRootWindow() ? owning_window->GetHost()->GetAcceleratedWidget() : nullptr; if (!owner) owner = owning_widget_; std::unique_ptr<RunState> run_state = BeginRun(owner); scoped_refptr<base::SingleThreadTaskRunner> task_runner = run_state->dialog_task_runner; task_runner->PostTask( FROM_HERE, base::BindOnce(&DoSelectFileOnDialogTaskRunner, execute_select_file_callback_, type, title, default_path, filter, file_type_index, default_extension, owner, base::SingleThreadTaskRunner::GetCurrentDefault(), base::BindOnce(&SelectFileDialogImpl::OnSelectFileExecuted, this, type, std::move(run_state), params))); } bool SelectFileDialogImpl::HasMultipleFileTypeChoicesImpl() { return has_multiple_file_type_choices_; } bool SelectFileDialogImpl::IsRunning(gfx::NativeWindow owning_window) const { if (!owning_window->GetRootWindow()) return false; HWND owner = owning_window->GetHost()->GetAcceleratedWidget(); return listener_ && IsRunningDialogForOwner(owner); } void SelectFileDialogImpl::ListenerDestroyed() { // Our associated listener has gone away, so we shouldn't call back to it if // our worker thread returns after the listener is dead. listener_ = nullptr; } void SelectFileDialogImpl::OnSelectFileExecuted( Type type, std::unique_ptr<RunState> run_state, void* params, const std::vector<base::FilePath>& paths, int index) { if (listener_) { // The paths vector is empty when the user cancels the dialog. if (paths.empty()) { listener_->FileSelectionCanceled(params); } else { switch (type) { case SELECT_FOLDER: case SELECT_UPLOAD_FOLDER: case SELECT_EXISTING_FOLDER: case SELECT_SAVEAS_FILE: case SELECT_OPEN_FILE: DCHECK_EQ(paths.size(), 1u); listener_->FileSelected(paths[0], index, params); break; case SELECT_OPEN_MULTI_FILE: listener_->MultiFilesSelected(paths, params); break; case SELECT_NONE: NOTREACHED(); } } } EndRun(std::move(run_state)); } // static std::vector<FileFilterSpec> SelectFileDialogImpl::GetFilterForFileTypes( const FileTypeInfo* file_types) { if (!file_types) return std::vector<FileFilterSpec>(); std::vector<std::u16string> exts; for (size_t i = 0; i < file_types->extensions.size(); ++i) { const std::vector<std::wstring>& inner_exts = file_types->extensions[i]; std::u16string ext_string; for (size_t j = 0; j < inner_exts.size(); ++j) { if (!ext_string.empty()) ext_string.push_back(u';'); ext_string.append(u"*."); ext_string.append(base::WideToUTF16(inner_exts[j])); } exts.push_back(ext_string); } return FormatFilterForExtensions( exts, file_types->extension_description_overrides, file_types->include_all_files, file_types->keep_extension_visible); } } // namespace SelectFileDialog* CreateWinSelectFileDialog( SelectFileDialog::Listener* listener, std::unique_ptr<SelectFilePolicy> policy, const ExecuteSelectFileCallback& execute_select_file_callback) { return new SelectFileDialogImpl(listener, std::move(policy), execute_select_file_callback); } SelectFileDialog* CreateSelectFileDialog( SelectFileDialog::Listener* listener, std::unique_ptr<SelectFilePolicy> policy) { return CreateWinSelectFileDialog(listener, std::move(policy), base::BindRepeating(&ui::ExecuteSelectFile)); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_win.cc
C++
unknown
13,551
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_WIN_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_WIN_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "base/functional/callback_forward.h" #include "ui/gfx/native_widget_types.h" #include "ui/shell_dialogs/execute_select_file_win.h" #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/shell_dialogs_export.h" namespace base { class FilePath; } namespace ui { class SelectFilePolicy; struct FileFilterSpec; using ExecuteSelectFileCallback = base::RepeatingCallback<void( SelectFileDialog::Type type, const std::u16string& title, const base::FilePath& default_path, const std::vector<FileFilterSpec>& filter, int file_type_index, const std::wstring& default_extension, HWND owner, OnSelectFileExecutedCallback on_select_file_executed_callback)>; SHELL_DIALOGS_EXPORT SelectFileDialog* CreateWinSelectFileDialog( SelectFileDialog::Listener* listener, std::unique_ptr<SelectFilePolicy> policy, const ExecuteSelectFileCallback& execute_select_file_callback); } // namespace ui #endif // UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_WIN_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_win.h
C++
unknown
1,332
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/select_file_dialog_win.h" #include <stddef.h> #include <memory> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/memory/scoped_refptr.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/task_environment.h" #include "base/test/test_timeouts.h" #include "base/threading/platform_thread.h" #include "base/win/scoped_com_initializer.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/select_file_policy.h" #include "ui/strings/grit/ui_strings.h" namespace { // The default title for the various dialogs. constexpr wchar_t kSelectFolderDefaultTitle[] = L"Select Folder"; constexpr wchar_t kSelectFileDefaultTitle[] = L"Open"; constexpr wchar_t kSaveFileDefaultTitle[] = L"Save As"; // Returns the title of |window|. std::wstring GetWindowTitle(HWND window) { wchar_t buffer[256]; UINT count = ::GetWindowText(window, buffer, std::size(buffer)); return std::wstring(buffer, count); } // Waits for a dialog window whose title is |dialog_title| to show and returns // its handle. HWND WaitForDialogWindow(const std::wstring& dialog_title) { // File dialogs uses this class name. static constexpr wchar_t kDialogClassName[] = L"#32770"; HWND result = nullptr; base::TimeDelta max_wait_time = TestTimeouts::action_timeout(); base::TimeDelta retry_interval = base::Milliseconds(20); while (!result && (max_wait_time.InMilliseconds() > 0)) { result = ::FindWindow(kDialogClassName, dialog_title.c_str()); base::PlatformThread::Sleep(retry_interval); max_wait_time -= retry_interval; } if (!result) { LOG(ERROR) << "Wait for dialog window timed out."; } // Check the name of the dialog specifically. That's because if multiple file // dialogs are opened in quick successions (e.g. from one test to another), // the ::FindWindow() call above will work for both the previous dialog title // and the current. return GetWindowTitle(result) == dialog_title ? result : nullptr; } struct EnumWindowsParam { // The owner of the dialog. This is used to differentiate the dialog prompt // from the file dialog since they could have the same title. HWND owner; // Holds the resulting window. HWND result; }; BOOL CALLBACK EnumWindowsCallback(HWND hwnd, LPARAM param) { EnumWindowsParam* enum_param = reinterpret_cast<EnumWindowsParam*>(param); // Early continue if the current hwnd is the file dialog. if (hwnd == enum_param->owner) return TRUE; // Only consider visible windows. if (!::IsWindowVisible(hwnd)) return TRUE; // If the window doesn't have |enum_param->owner| as the owner, it can't be // the prompt dialog. if (::GetWindow(hwnd, GW_OWNER) != enum_param->owner) return TRUE; enum_param->result = hwnd; return FALSE; } HWND WaitForDialogPrompt(HWND owner) { // The dialog prompt could have the same title as the file dialog. This means // that it would not be possible to make sure the right window is found using // ::FindWindow(). Instead enumerate all top-level windows and return the one // whose owner is the file dialog. EnumWindowsParam param = {owner, nullptr}; base::TimeDelta max_wait_time = TestTimeouts::action_timeout(); base::TimeDelta retry_interval = base::Milliseconds(20); while (!param.result && (max_wait_time.InMilliseconds() > 0)) { ::EnumWindows(&EnumWindowsCallback, reinterpret_cast<LPARAM>(&param)); base::PlatformThread::Sleep(retry_interval); max_wait_time -= retry_interval; } if (!param.result) { LOG(ERROR) << "Wait for dialog prompt timed out."; } return param.result; } // Returns the text of the dialog item in |window| whose id is |dialog_item_id|. std::wstring GetDialogItemText(HWND window, int dialog_item_id) { if (!window) return std::wstring(); wchar_t buffer[256]; UINT count = ::GetDlgItemText(window, dialog_item_id, buffer, std::size(buffer)); return std::wstring(buffer, count); } // Sends a command to |window| using PostMessage(). void SendCommand(HWND window, int id) { ASSERT_TRUE(window); // Make sure the window is visible first or the WM_COMMAND may not have any // effect. base::TimeDelta max_wait_time = TestTimeouts::action_timeout(); base::TimeDelta retry_interval = base::Milliseconds(20); while (!::IsWindowVisible(window) && (max_wait_time.InMilliseconds() > 0)) { base::PlatformThread::Sleep(retry_interval); max_wait_time -= retry_interval; } if (!::IsWindowVisible(window)) { LOG(ERROR) << "SendCommand timed out."; } ::PostMessage(window, WM_COMMAND, id, 0); } } // namespace class SelectFileDialogWinTest : public ::testing::Test, public ui::SelectFileDialog::Listener { public: SelectFileDialogWinTest() = default; SelectFileDialogWinTest(const SelectFileDialogWinTest&) = delete; SelectFileDialogWinTest& operator=(const SelectFileDialogWinTest&) = delete; ~SelectFileDialogWinTest() override = default; // ui::SelectFileDialog::Listener: void FileSelected(const base::FilePath& path, int index, void* params) override { selected_paths_.push_back(path); } void MultiFilesSelected(const std::vector<base::FilePath>& files, void* params) override { selected_paths_ = files; } void FileSelectionCanceled(void* params) override { was_cancelled_ = true; } // Runs the scheduler until no tasks are executing anymore. void RunUntilIdle() { task_environment_.RunUntilIdle(); } const std::vector<base::FilePath>& selected_paths() { return selected_paths_; } // Return a fake NativeWindow. This will result in the dialog having no // parent window but the tests will still work. static gfx::NativeWindow native_window() { return reinterpret_cast<gfx::NativeWindow>(0); } bool was_cancelled() { return was_cancelled_; } // Resets the results so that this instance can be reused as a // SelectFileDialog listener. void ResetResults() { was_cancelled_ = false; selected_paths_.clear(); } private: base::test::TaskEnvironment task_environment_; std::vector<base::FilePath> selected_paths_; bool was_cancelled_ = false; }; TEST_F(SelectFileDialogWinTest, CancelAllDialogs) { // Intentionally not testing SELECT_UPLOAD_FOLDER because the dialog is // customized for that case. struct { ui::SelectFileDialog::Type dialog_type; const wchar_t* dialog_title; } kTestCases[] = { { ui::SelectFileDialog::SELECT_FOLDER, kSelectFolderDefaultTitle, }, { ui::SelectFileDialog::SELECT_EXISTING_FOLDER, kSelectFolderDefaultTitle, }, { ui::SelectFileDialog::SELECT_SAVEAS_FILE, kSaveFileDefaultTitle, }, { ui::SelectFileDialog::SELECT_OPEN_FILE, kSelectFileDefaultTitle, }, { ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE, kSelectFileDefaultTitle, }}; for (size_t i = 0; i < std::size(kTestCases); ++i) { SCOPED_TRACE(base::StringPrintf("i=%zu", i)); const auto& test_case = kTestCases[i]; scoped_refptr<ui::SelectFileDialog> dialog = ui::SelectFileDialog::Create(this, nullptr); std::unique_ptr<ui::SelectFileDialog::FileTypeInfo> file_type_info; int file_type_info_index = 0; // The Save As dialog requires a filetype info. if (test_case.dialog_type == ui::SelectFileDialog::SELECT_SAVEAS_FILE) { file_type_info = std::make_unique<ui::SelectFileDialog::FileTypeInfo>(); file_type_info->extensions.push_back({L"html"}); file_type_info_index = 1; } dialog->SelectFile(test_case.dialog_type, std::u16string(), base::FilePath(), file_type_info.get(), file_type_info_index, std::wstring(), native_window(), nullptr); // Accept the default value. HWND window = WaitForDialogWindow(test_case.dialog_title); SendCommand(window, IDCANCEL); RunUntilIdle(); EXPECT_TRUE(was_cancelled()); EXPECT_TRUE(selected_paths().empty()); ResetResults(); } } // When using SELECT_UPLOAD_FOLDER, the title and the ok button strings are // modified to put emphasis on the fact that the whole folder will be uploaded. TEST_F(SelectFileDialogWinTest, UploadFolderCheckStrings) { base::ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); base::FilePath default_path = scoped_temp_dir.GetPath(); scoped_refptr<ui::SelectFileDialog> dialog = ui::SelectFileDialog::Create(this, nullptr); dialog->SelectFile(ui::SelectFileDialog::SELECT_UPLOAD_FOLDER, std::u16string(), default_path, nullptr, 0, L"", native_window(), nullptr); // Wait for the window to open and make sure the window title was changed from // the default title for a regular select folder operation. HWND window = WaitForDialogWindow(base::UTF16ToWide( l10n_util::GetStringUTF16(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE))); EXPECT_NE(GetWindowTitle(window), kSelectFolderDefaultTitle); // Check the OK button text. EXPECT_EQ(GetDialogItemText(window, 1), base::UTF16ToWide(l10n_util::GetStringUTF16( IDS_SELECT_UPLOAD_FOLDER_DIALOG_UPLOAD_BUTTON))); // Close the dialog. SendCommand(window, IDOK); RunUntilIdle(); EXPECT_FALSE(was_cancelled()); ASSERT_EQ(1u, selected_paths().size()); // On some machines GetSystemDirectory returns C:\WINDOWS which is then // normalized to C:\Windows by the file dialog, leading to spurious failures // if a case-sensitive comparison is used. EXPECT_TRUE(base::FilePath::CompareEqualIgnoreCase( selected_paths()[0].value(), default_path.value())); } // Specifying the title when opening a dialog to select a file, select multiple // files or save a file doesn't do anything. TEST_F(SelectFileDialogWinTest, SpecifyTitle) { static constexpr char16_t kTitle[] = u"FooBar Title"; // Create some file in a test folder. base::ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); // Create an existing file since it is required. base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt"); std::string contents = "Hello test!"; ASSERT_TRUE(base::WriteFile(default_path, contents)); scoped_refptr<ui::SelectFileDialog> dialog = ui::SelectFileDialog::Create(this, nullptr); dialog->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, kTitle, default_path, nullptr, 0, L"", native_window(), nullptr); // Wait for the window to open. The title is unchanged. Note that if this // hangs, it possibly is because the title changed. HWND window = WaitForDialogWindow(kSelectFileDefaultTitle); // Close the dialog and the result doesn't matter. SendCommand(window, IDCANCEL); } // Tests the selection of one file in both the single and multiple case. It's // too much trouble to select a different file in the dialog so the default_path // is used to pre-select a file and the OK button is clicked as soon as the // dialog opens. This tests the default_path parameter and the single file // selection. TEST_F(SelectFileDialogWinTest, TestSelectFile) { // Create some file in a test folder. base::ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); // Create an existing file since it is required. base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt"); std::string contents = "Hello test!"; ASSERT_TRUE(base::WriteFile(default_path, contents)); scoped_refptr<ui::SelectFileDialog> dialog = ui::SelectFileDialog::Create(this, nullptr); dialog->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, std::u16string(), default_path, nullptr, 0, L"", native_window(), nullptr); // Wait for the window to open HWND window = WaitForDialogWindow(kSelectFileDefaultTitle); SendCommand(window, IDOK); RunUntilIdle(); EXPECT_FALSE(was_cancelled()); ASSERT_EQ(1u, selected_paths().size()); // On some machines GetSystemDirectory returns C:\WINDOWS which is then // normalized to C:\Windows by the file dialog, leading to spurious failures // if a case-sensitive comparison is used. EXPECT_TRUE(base::FilePath::CompareEqualIgnoreCase( selected_paths()[0].value(), default_path.value())); } // Tests that the file extension is automatically added. TEST_F(SelectFileDialogWinTest, TestSaveFile) { // Create some file in a test folder. base::ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo"); ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.push_back({L"html"}); scoped_refptr<ui::SelectFileDialog> dialog = ui::SelectFileDialog::Create(this, nullptr); dialog->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(), default_path, &file_type_info, 1, L"", native_window(), nullptr); // Wait for the window to open HWND window = WaitForDialogWindow(kSaveFileDefaultTitle); SendCommand(window, IDOK); RunUntilIdle(); EXPECT_FALSE(was_cancelled()); ASSERT_EQ(1u, selected_paths().size()); // On some machines GetSystemDirectory returns C:\WINDOWS which is then // normalized to C:\Windows by the file dialog, leading to spurious failures // if a case-sensitive comparison is used. EXPECT_TRUE(base::FilePath::CompareEqualIgnoreCase( selected_paths()[0].value(), default_path.AddExtension(L"html").value())); } // Tests that only specifying a basename as the default path works. TEST_F(SelectFileDialogWinTest, OnlyBasename) { base::FilePath default_path(L"foobar.html"); ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.push_back({L"html"}); scoped_refptr<ui::SelectFileDialog> dialog = ui::SelectFileDialog::Create(this, nullptr); dialog->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(), default_path, &file_type_info, 1, L"", native_window(), nullptr); // Wait for the window to open HWND window = WaitForDialogWindow(kSaveFileDefaultTitle); SendCommand(window, IDOK); RunUntilIdle(); EXPECT_FALSE(was_cancelled()); ASSERT_EQ(1u, selected_paths().size()); EXPECT_EQ(selected_paths()[0].BaseName(), default_path); } TEST_F(SelectFileDialogWinTest, SaveAsDifferentExtension) { // Create some file in a test folder. base::ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt"); ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.push_back({L"exe"}); scoped_refptr<ui::SelectFileDialog> dialog = ui::SelectFileDialog::Create(this, nullptr); dialog->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(), default_path, &file_type_info, 1, L"html", native_window(), nullptr); HWND window = WaitForDialogWindow(kSaveFileDefaultTitle); SendCommand(window, IDOK); RunUntilIdle(); EXPECT_FALSE(was_cancelled()); // On some machines GetSystemDirectory returns C:\WINDOWS which is then // normalized to C:\Windows by the file dialog, leading to spurious failures // if a case-sensitive comparison is used. EXPECT_TRUE(base::FilePath::CompareEqualIgnoreCase( selected_paths()[0].value(), default_path.value())); } TEST_F(SelectFileDialogWinTest, OpenFileDifferentExtension) { // Create some file in a test folder. base::ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt"); std::string contents = "Hello test!"; ASSERT_TRUE(base::WriteFile(default_path, contents)); ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.push_back({L"exe"}); scoped_refptr<ui::SelectFileDialog> dialog = ui::SelectFileDialog::Create(this, nullptr); dialog->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, std::u16string(), default_path, &file_type_info, 1, L"html", native_window(), nullptr); HWND window = WaitForDialogWindow(kSelectFileDefaultTitle); SendCommand(window, IDOK); RunUntilIdle(); EXPECT_FALSE(was_cancelled()); // On some machines GetSystemDirectory returns C:\WINDOWS which is then // normalized to C:\Windows by the file dialog, leading to spurious failures // if a case-sensitive comparison is used. EXPECT_TRUE(base::FilePath::CompareEqualIgnoreCase( selected_paths()[0].value(), default_path.value())); } TEST_F(SelectFileDialogWinTest, SelectNonExistingFile) { // Create some file in a test folder. base::ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"does-not-exist.html"); scoped_refptr<ui::SelectFileDialog> dialog = ui::SelectFileDialog::Create(this, nullptr); dialog->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, std::u16string(), default_path, nullptr, 0, L"", native_window(), nullptr); HWND window = WaitForDialogWindow(kSelectFileDefaultTitle); SendCommand(window, IDOK); // Since selecting a non-existing file is not supported, a error dialog box // should have appeared. HWND error_box = WaitForDialogPrompt(window); SendCommand(error_box, IDOK); // Now actually cancel the file dialog box. SendCommand(window, IDCANCEL); RunUntilIdle(); EXPECT_TRUE(was_cancelled()); EXPECT_TRUE(selected_paths().empty()); } // Tests that selecting an existing file when saving should prompt the user with // a dialog to confirm the overwrite. TEST_F(SelectFileDialogWinTest, SaveFileOverwritePrompt) { // Create some file in a test folder. base::ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt"); std::string contents = "Hello test!"; ASSERT_TRUE(base::WriteFile(default_path, contents)); ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.push_back({L"txt"}); scoped_refptr<ui::SelectFileDialog> dialog = ui::SelectFileDialog::Create(this, nullptr); dialog->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(), default_path, &file_type_info, 1, L"", native_window(), nullptr); HWND window = WaitForDialogWindow(kSaveFileDefaultTitle); SendCommand(window, IDOK); // Check that the prompt appears and close it. By default, the "no" option is // selected so sending IDOK cancels the operation. HWND error_box = WaitForDialogPrompt(window); SendCommand(error_box, IDOK); // Cancel the dialog. SendCommand(window, IDCANCEL); RunUntilIdle(); EXPECT_TRUE(was_cancelled()); EXPECT_TRUE(selected_paths().empty()); }
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_dialog_win_unittest.cc
C++
unknown
19,605
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/select_file_policy.h" namespace ui { SelectFilePolicy::~SelectFilePolicy() = default; } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_policy.cc
C++
unknown
279
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_SELECT_FILE_POLICY_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_POLICY_H_ #include "ui/shell_dialogs/shell_dialogs_export.h" namespace ui { // An optional policy class that provides decisions on whether to allow showing // a native file dialog. Some ports need this. class SHELL_DIALOGS_EXPORT SelectFilePolicy { public: virtual ~SelectFilePolicy(); // Returns true if the current policy allows for file selection dialogs. virtual bool CanOpenSelectFileDialog() = 0; // Called from the SelectFileDialog when we've denied a request. virtual void SelectFileDenied() = 0; }; } // namespace ui #endif // UI_SHELL_DIALOGS_SELECT_FILE_POLICY_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_policy.h
C++
unknown
824
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_SELECT_FILE_UTILS_WIN_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_UTILS_WIN_H_ #include "base/strings/string_tokenizer.h" namespace ui { // Given a file name, return the sanitized version by removing substrings that // are embedded in double '%' characters as those are reserved for environment // variables. Implementation detail exported for unit tests. template <typename T> std::basic_string<T> RemoveEnvVarFromFileName( const std::basic_string<T>& file_name, const std::basic_string<T>& env_delimit) { base::StringTokenizerT<std::basic_string<T>, typename std::basic_string<T>::const_iterator> t(file_name, env_delimit); t.set_options(base::StringTokenizer::RETURN_EMPTY_TOKENS); std::basic_string<T> result; bool token_valid = t.GetNext(); while (token_valid) { // Append substring before the first "%". result.append(t.token()); // Done if we are reaching the end delimiter, if (!t.GetNext()) { break; } std::basic_string<T> string_after_first_percent = t.token(); token_valid = t.GetNext(); // If there are no other "%", append the string after // the first "%". Otherwise, remove the string between // the "%" and continue handing the remaining string. if (!token_valid) { result.append(env_delimit); result.append(string_after_first_percent); break; } } return result; } } // namespace ui #endif // UI_SHELL_DIALOGS_SELECT_FILE_UTILS_WIN_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_utils_win.h
C++
unknown
1,648
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/select_file_utils_win.h" #include <stddef.h> #include "base/strings/stringprintf.h" #include "testing/gtest/include/gtest/gtest.h" TEST(SelectFileUtilsWin, RemoveEnvVarFromFileName) { struct RemoveEnvFromFileNameTestCase { const wchar_t* filename; const wchar_t* sanitized_filename; } test_cases[] = { {L"", L""}, {L"a.txt", L"a.txt"}, // Only 1 "%" in file name. {L"%", L"%"}, {L"%.txt", L"%.txt"}, {L"ab%c.txt", L"ab%c.txt"}, {L"abc.t%", L"abc.t%"}, // 2 "%" in file name. {L"%%", L""}, {L"%c%", L""}, {L"%c%d", L"d"}, {L"d%c%.txt", L"d.txt"}, {L"ab%c.t%", L"ab"}, {L"abc.%t%", L"abc."}, {L"*.%txt%", L"*."}, // More than 2 "%" in file name. {L"%ab%c%.txt", L"c%.txt"}, {L"%abc%.%txt%", L"."}, {L"%ab%c%.%txt%", L"ctxt%"}, }; for (size_t i = 0; i < std::size(test_cases); ++i) { SCOPED_TRACE(base::StringPrintf("i=%zu", i)); std::wstring sanitized = ui::RemoveEnvVarFromFileName<wchar_t>( std::wstring(test_cases[i].filename), std::wstring(L"%")); EXPECT_EQ(std::wstring(test_cases[i].sanitized_filename), sanitized); } }
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/select_file_utils_win_unittest.cc
C++
unknown
1,354
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/shell_dialogs/selected_file_info.h" namespace ui { SelectedFileInfo::SelectedFileInfo() {} SelectedFileInfo::SelectedFileInfo(const base::FilePath& in_file_path, const base::FilePath& in_local_path) : file_path(in_file_path), local_path(in_local_path) { display_name = in_file_path.BaseName().value(); } SelectedFileInfo::SelectedFileInfo(const SelectedFileInfo& other) = default; SelectedFileInfo::SelectedFileInfo(SelectedFileInfo&& other) = default; SelectedFileInfo::~SelectedFileInfo() {} SelectedFileInfo& SelectedFileInfo::operator=(const SelectedFileInfo& other) = default; SelectedFileInfo& SelectedFileInfo::operator=(SelectedFileInfo&& other) = default; bool SelectedFileInfo::operator==(const SelectedFileInfo& other) const { return file_path == other.file_path && local_path == other.local_path && display_name == other.display_name && url == other.url && virtual_path == other.virtual_path; } // Converts a list of FilePaths to a list of ui::SelectedFileInfo. std::vector<SelectedFileInfo> FilePathListToSelectedFileInfoList( const std::vector<base::FilePath>& paths) { std::vector<SelectedFileInfo> selected_files; for (const auto& path : paths) selected_files.push_back(SelectedFileInfo(path, path)); return selected_files; } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/selected_file_info.cc
C++
unknown
1,516
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_SHELL_DIALOGS_SELECTED_FILE_INFO_H_ #define UI_SHELL_DIALOGS_SELECTED_FILE_INFO_H_ #include <vector> #include "base/files/file_path.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/shell_dialogs/shell_dialogs_export.h" #include "url/gurl.h" namespace ui { // Struct used for passing selected file info to WebKit. struct SHELL_DIALOGS_EXPORT SelectedFileInfo { // Selected file's user friendly path as seen in the UI. base::FilePath file_path; // The actual local path to the selected file. This can be a snapshot file // with a human unreadable name like /blah/.d41d8cd98f00b204e9800998ecf8427e. // |local_path| can differ from |file_path| for drive files (e.g. // /drive_cache/temporary/d41d8cd98f00b204e9800998ecf8427e vs. // /special/drive/foo.txt). base::FilePath local_path; // This field is optional. The display name contains only the base name // portion of a file name (ex. no path separators), and used for displaying // selected file names. If this field is empty, the base name portion of // |path| is used for displaying. base::FilePath::StringType display_name; // If set, this URL may be used to access the file. If the user is capable of // using a URL to access the file, it should be used in preference to // |local_path|. For example, when opening a .gdoc file from Google Drive the // file is opened by navigating to a docs.google.com URL. absl::optional<GURL> url; // If set, this virtual path may be used to access the file. If the user is // capable of using a virtual path to access the file (using the file system // abstraction in //storage/browser/file_system with a // storage::kFileSystemTypeExternal FileSystemURL), it should be used in // preference over |local_path| and |url|. absl::optional<base::FilePath> virtual_path; SelectedFileInfo(); SelectedFileInfo(const base::FilePath& in_file_path, const base::FilePath& in_local_path); SelectedFileInfo(const SelectedFileInfo& other); SelectedFileInfo(SelectedFileInfo&& other); ~SelectedFileInfo(); SelectedFileInfo& operator=(const SelectedFileInfo& other); SelectedFileInfo& operator=(SelectedFileInfo&& other); bool operator==(const SelectedFileInfo& other) const; }; // Converts a list of FilePaths to a list of ui::SelectedFileInfo. SHELL_DIALOGS_EXPORT std::vector<SelectedFileInfo> FilePathListToSelectedFileInfoList(const std::vector<base::FilePath>& paths); } // namespace ui #endif // UI_SHELL_DIALOGS_SELECTED_FILE_INFO_H_
Zhao-PengFei35/chromium_src_4
ui/shell_dialogs/selected_file_info.h
C++
unknown
2,692